code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* ModifiedFieldType
*
* @package PayPal
*/
class ModifiedFieldType extends XSDSimpleType
{
var $Field;
var $ModifyType;
function ModifiedFieldType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'Field' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'ModifyType' =>
array (
'required' => false,
'type' => 'ModifyCodeType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getField()
{
return $this->Field;
}
function setField($Field, $charset = 'iso-8859-1')
{
$this->Field = $Field;
$this->_elements['Field']['charset'] = $charset;
}
function getModifyType()
{
return $this->ModifyType;
}
function setModifyType($ModifyType, $charset = 'iso-8859-1')
{
$this->ModifyType = $ModifyType;
$this->_elements['ModifyType']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/ModifiedFieldType.php | PHP | asf20 | 1,402 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* IncentiveInfoType
*
* @package PayPal
*/
class IncentiveInfoType extends XSDSimpleType
{
var $ReverseTransactionResponseDetails;
/**
* Incentive redemption code.
*/
var $IncentiveCode;
/**
* Defines which bucket or item that the incentive should be applied to.
*/
var $ApplyIndication;
function IncentiveInfoType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'ReverseTransactionResponseDetails' =>
array (
'required' => true,
'type' => NULL,
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'IncentiveCode' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'ApplyIndication' =>
array (
'required' => false,
'type' => 'IncentiveApplyIndicationType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getReverseTransactionResponseDetails()
{
return $this->ReverseTransactionResponseDetails;
}
function setReverseTransactionResponseDetails($ReverseTransactionResponseDetails, $charset = 'iso-8859-1')
{
$this->ReverseTransactionResponseDetails = $ReverseTransactionResponseDetails;
$this->_elements['ReverseTransactionResponseDetails']['charset'] = $charset;
}
function getIncentiveCode()
{
return $this->IncentiveCode;
}
function setIncentiveCode($IncentiveCode, $charset = 'iso-8859-1')
{
$this->IncentiveCode = $IncentiveCode;
$this->_elements['IncentiveCode']['charset'] = $charset;
}
function getApplyIndication()
{
return $this->ApplyIndication;
}
function setApplyIndication($ApplyIndication, $charset = 'iso-8859-1')
{
$this->ApplyIndication = $ApplyIndication;
$this->_elements['ApplyIndication']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/IncentiveInfoType.php | PHP | asf20 | 2,364 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/AbstractResponseType.php';
/**
* BMCreateButtonResponseType
*
* @package PayPal
*/
class BMCreateButtonResponseType extends AbstractResponseType
{
var $Website;
var $Email;
var $Mobile;
var $HostedButtonID;
function BMCreateButtonResponseType()
{
parent::AbstractResponseType();
$this->_namespace = 'urn:ebay:api:PayPalAPI';
$this->_elements = array_merge($this->_elements,
array (
'Website' =>
array (
'required' => true,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'Email' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'Mobile' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'HostedButtonID' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
));
}
function getWebsite()
{
return $this->Website;
}
function setWebsite($Website, $charset = 'iso-8859-1')
{
$this->Website = $Website;
$this->_elements['Website']['charset'] = $charset;
}
function getEmail()
{
return $this->Email;
}
function setEmail($Email, $charset = 'iso-8859-1')
{
$this->Email = $Email;
$this->_elements['Email']['charset'] = $charset;
}
function getMobile()
{
return $this->Mobile;
}
function setMobile($Mobile, $charset = 'iso-8859-1')
{
$this->Mobile = $Mobile;
$this->_elements['Mobile']['charset'] = $charset;
}
function getHostedButtonID()
{
return $this->HostedButtonID;
}
function setHostedButtonID($HostedButtonID, $charset = 'iso-8859-1')
{
$this->HostedButtonID = $HostedButtonID;
$this->_elements['HostedButtonID']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/bmcreatebuttonresponsetype.php | PHP | asf20 | 2,341 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/AbstractResponseType.php';
/**
* GetBillingAgreementCustomerDetailsResponseType
*
* @package PayPal
*/
class GetBillingAgreementCustomerDetailsResponseType extends AbstractResponseType
{
var $GetBillingAgreementCustomerDetailsResponseDetails;
function GetBillingAgreementCustomerDetailsResponseType()
{
parent::AbstractResponseType();
$this->_namespace = 'urn:ebay:api:PayPalAPI';
$this->_elements = array_merge($this->_elements,
array (
'GetBillingAgreementCustomerDetailsResponseDetails' =>
array (
'required' => true,
'type' => 'GetBillingAgreementCustomerDetailsResponseDetailsType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getGetBillingAgreementCustomerDetailsResponseDetails()
{
return $this->GetBillingAgreementCustomerDetailsResponseDetails;
}
function setGetBillingAgreementCustomerDetailsResponseDetails($GetBillingAgreementCustomerDetailsResponseDetails, $charset = 'iso-8859-1')
{
$this->GetBillingAgreementCustomerDetailsResponseDetails = $GetBillingAgreementCustomerDetailsResponseDetails;
$this->_elements['GetBillingAgreementCustomerDetailsResponseDetails']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/GetBillingAgreementCustomerDetailsResponseType.php | PHP | asf20 | 1,449 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* DoExpressCheckoutPaymentResponseDetailsType
*
* @package PayPal
*/
class DoExpressCheckoutPaymentResponseDetailsType extends XSDSimpleType
{
/**
* The timestamped token value that was returned by SetExpressCheckoutResponse and
* passed on GetExpressCheckoutDetailsRequest.
*/
var $Token;
/**
* Information about the transaction
*/
var $PaymentInfo;
var $BillingAgreementID;
var $RedirectRequired;
/**
* Memo entered by sender in PayPal Review Page note field.
*/
var $Note;
/**
* Redirect back to PayPal, PayPal can host the success page.
*/
var $SuccessPageRedirectRequested;
/**
* Information about the user selected options.
*/
var $UserSelectedOptions;
function DoExpressCheckoutPaymentResponseDetailsType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'Token' =>
array (
'required' => true,
'type' => 'ExpressCheckoutTokenType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'PaymentInfo' =>
array (
'required' => false,
'type' => 'PaymentInfoType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'BillingAgreementID' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'RedirectRequired' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'Note' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'SuccessPageRedirectRequested' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'UserSelectedOptions' =>
array (
'required' => false,
'type' => 'UserSelectedOptionType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getToken()
{
return $this->Token;
}
function setToken($Token, $charset = 'iso-8859-1')
{
$this->Token = $Token;
$this->_elements['Token']['charset'] = $charset;
}
function getPaymentInfo()
{
return $this->PaymentInfo;
}
function setPaymentInfo($PaymentInfo, $charset = 'iso-8859-1')
{
$this->PaymentInfo = $PaymentInfo;
$this->_elements['PaymentInfo']['charset'] = $charset;
}
function getBillingAgreementID()
{
return $this->BillingAgreementID;
}
function setBillingAgreementID($BillingAgreementID, $charset = 'iso-8859-1')
{
$this->BillingAgreementID = $BillingAgreementID;
$this->_elements['BillingAgreementID']['charset'] = $charset;
}
function getRedirectRequired()
{
return $this->RedirectRequired;
}
function setRedirectRequired($RedirectRequired, $charset = 'iso-8859-1')
{
$this->RedirectRequired = $RedirectRequired;
$this->_elements['RedirectRequired']['charset'] = $charset;
}
function getNote()
{
return $this->Note;
}
function setNote($Note, $charset = 'iso-8859-1')
{
$this->Note = $Note;
$this->_elements['Note']['charset'] = $charset;
}
function getSuccessPageRedirectRequested()
{
return $this->SuccessPageRedirectRequested;
}
function setSuccessPageRedirectRequested($SuccessPageRedirectRequested, $charset = 'iso-8859-1')
{
$this->SuccessPageRedirectRequested = $SuccessPageRedirectRequested;
$this->_elements['SuccessPageRedirectRequested']['charset'] = $charset;
}
function getUserSelectedOptions()
{
return $this->UserSelectedOptions;
}
function setUserSelectedOptions($UserSelectedOptions, $charset = 'iso-8859-1')
{
$this->UserSelectedOptions = $UserSelectedOptions;
$this->_elements['UserSelectedOptions']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/DoExpressCheckoutPaymentResponseDetailsType.php | PHP | asf20 | 4,709 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/AbstractResponseType.php';
/**
* CreateBillingAgreementResponseType
*
* @package PayPal
*/
class CreateBillingAgreementResponseType extends AbstractResponseType
{
var $BillingAgreementID;
function CreateBillingAgreementResponseType()
{
parent::AbstractResponseType();
$this->_namespace = 'urn:ebay:api:PayPalAPI';
$this->_elements = array_merge($this->_elements,
array (
'BillingAgreementID' =>
array (
'required' => true,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
));
}
function getBillingAgreementID()
{
return $this->BillingAgreementID;
}
function setBillingAgreementID($BillingAgreementID, $charset = 'iso-8859-1')
{
$this->BillingAgreementID = $BillingAgreementID;
$this->_elements['BillingAgreementID']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/CreateBillingAgreementResponseType.php | PHP | asf20 | 1,078 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* RecurringPaymentsProfileDetailsType
*
* @package PayPal
*/
class RecurringPaymentsProfileDetailsType extends XSDSimpleType
{
/**
* Subscriber name - if missing, will use name in buyer's account
*/
var $SubscriberName;
/**
* Subscriber address - if missing, will use address in buyer's account
*/
var $SubscriberShippingAddress;
/**
* When does this Profile begin billing?
*/
var $BillingStartDate;
/**
* Your own unique invoice or tracking number.
*/
var $ProfileReference;
function RecurringPaymentsProfileDetailsType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'SubscriberName' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'SubscriberShippingAddress' =>
array (
'required' => false,
'type' => 'AddressType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'BillingStartDate' =>
array (
'required' => true,
'type' => 'dateTime',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'ProfileReference' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getSubscriberName()
{
return $this->SubscriberName;
}
function setSubscriberName($SubscriberName, $charset = 'iso-8859-1')
{
$this->SubscriberName = $SubscriberName;
$this->_elements['SubscriberName']['charset'] = $charset;
}
function getSubscriberShippingAddress()
{
return $this->SubscriberShippingAddress;
}
function setSubscriberShippingAddress($SubscriberShippingAddress, $charset = 'iso-8859-1')
{
$this->SubscriberShippingAddress = $SubscriberShippingAddress;
$this->_elements['SubscriberShippingAddress']['charset'] = $charset;
}
function getBillingStartDate()
{
return $this->BillingStartDate;
}
function setBillingStartDate($BillingStartDate, $charset = 'iso-8859-1')
{
$this->BillingStartDate = $BillingStartDate;
$this->_elements['BillingStartDate']['charset'] = $charset;
}
function getProfileReference()
{
return $this->ProfileReference;
}
function setProfileReference($ProfileReference, $charset = 'iso-8859-1')
{
$this->ProfileReference = $ProfileReference;
$this->_elements['ProfileReference']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/RecurringPaymentsProfileDetailsType.php | PHP | asf20 | 3,056 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/AbstractResponseType.php';
/**
* DoDirectPaymentResponseType
*
* @package PayPal
*/
class DoDirectPaymentResponseType extends AbstractResponseType
{
/**
* The amount of the payment as specified by you on DoDirectPaymentRequest.
*/
var $Amount;
/**
* Address Verification System response code. Character limit: One single-byte
* alphanumeric character
*/
var $AVSCode;
/**
* Result of the CVV2 check by PayPal.
*/
var $CVV2Code;
/**
* Transaction identification number.
*/
var $TransactionID;
/**
* The reason why a particular transaction went in pending.
*/
var $PendingReason;
/**
* This will identify the actual transaction status.
*/
var $PaymentStatus;
var $FMFDetails;
var $ThreeDSecureResponse;
function DoDirectPaymentResponseType()
{
parent::AbstractResponseType();
$this->_namespace = 'urn:ebay:api:PayPalAPI';
$this->_elements = array_merge($this->_elements,
array (
'Amount' =>
array (
'required' => true,
'type' => 'BasicAmountType',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'AVSCode' =>
array (
'required' => true,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'CVV2Code' =>
array (
'required' => true,
'type' => 'string',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'TransactionID' =>
array (
'required' => true,
'type' => 'TransactionId',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'PendingReason' =>
array (
'required' => false,
'type' => 'PendingStatusCodeType',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'PaymentStatus' =>
array (
'required' => false,
'type' => 'PaymentStatusCodeType',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'FMFDetails' =>
array (
'required' => false,
'type' => 'FMFDetailsType',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
'ThreeDSecureResponse' =>
array (
'required' => false,
'type' => 'ThreeDSecureResponseType',
'namespace' => 'urn:ebay:api:PayPalAPI',
),
));
}
function getAmount()
{
return $this->Amount;
}
function setAmount($Amount, $charset = 'iso-8859-1')
{
$this->Amount = $Amount;
$this->_elements['Amount']['charset'] = $charset;
}
function getAVSCode()
{
return $this->AVSCode;
}
function setAVSCode($AVSCode, $charset = 'iso-8859-1')
{
$this->AVSCode = $AVSCode;
$this->_elements['AVSCode']['charset'] = $charset;
}
function getCVV2Code()
{
return $this->CVV2Code;
}
function setCVV2Code($CVV2Code, $charset = 'iso-8859-1')
{
$this->CVV2Code = $CVV2Code;
$this->_elements['CVV2Code']['charset'] = $charset;
}
function getTransactionID()
{
return $this->TransactionID;
}
function setTransactionID($TransactionID, $charset = 'iso-8859-1')
{
$this->TransactionID = $TransactionID;
$this->_elements['TransactionID']['charset'] = $charset;
}
function getPendingReason()
{
return $this->PendingReason;
}
function setPendingReason($PendingReason, $charset = 'iso-8859-1')
{
$this->PendingReason = $PendingReason;
$this->_elements['PendingReason']['charset'] = $charset;
}
function getPaymentStatus()
{
return $this->PaymentStatus;
}
function setPaymentStatus($PaymentStatus, $charset = 'iso-8859-1')
{
$this->PaymentStatus = $PaymentStatus;
$this->_elements['PaymentStatus']['charset'] = $charset;
}
function getFMFDetails()
{
return $this->FMFDetails;
}
function setFMFDetails($FMFDetails, $charset = 'iso-8859-1')
{
$this->FMFDetails = $FMFDetails;
$this->_elements['FMFDetails']['charset'] = $charset;
}
function getThreeDSecureResponse()
{
return $this->ThreeDSecureResponse;
}
function setThreeDSecureResponse($ThreeDSecureResponse, $charset = 'iso-8859-1')
{
$this->ThreeDSecureResponse = $ThreeDSecureResponse;
$this->_elements['ThreeDSecureResponse']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/DoDirectPaymentResponseType.php | PHP | asf20 | 4,978 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* CalculatedShippingRateType
*
* @package PayPal
*/
class CalculatedShippingRateType extends XSDSimpleType
{
/**
* Potal/zip code from where package will be shipped.
*/
var $OriginatingPostalCode;
/**
* Indicates an item that cannot go through the stamping machine at the shipping
* service office (a value of True) and requires special or fragile handling. Only
* returned if ShippingType = 2.
*/
var $ShippingIrregular;
/**
* contains information about shipping fees per each shipping service chosen by the
* seller
*/
var $CarrierDetails;
/**
* May need to be moved into details - wait for George! The size of the package to
* be shipped. Possible values are: None Letter Large envelope USPS flat rate
* envelope Package/thick envelope USPS large package/oversize 1 Very large
* package/oversize 2 UPS Letter
*/
var $ShippingPackage;
/**
* Shipping weight unit of measure (major). If unit of weight is kilogram (i.e.,
* metric system) this would be the exact weight value in kilogram (i.e., complete
* decimal number, e.g., 2.23 kg). Only returned if ShippingType is 2.
*/
var $WeightMajor;
/**
* Shipping weight unit of measure (minor). If unit of weight is in pounds and/or
* ounces, this would be the exact weight value in ounces (i.e., complete decimal
* number, e.g., 8.2 or 8.0 ounces). Only returned if ShippingType is 2.
*/
var $WeightMinor;
function CalculatedShippingRateType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'OriginatingPostalCode' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'ShippingIrregular' =>
array (
'required' => false,
'type' => 'boolean',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'CarrierDetails' =>
array (
'required' => false,
'type' => 'ShippingCarrierDetailsType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'ShippingPackage' =>
array (
'required' => false,
'type' => 'ShippingPackageCodeType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'WeightMajor' =>
array (
'required' => false,
'type' => 'MeasureType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'WeightMinor' =>
array (
'required' => false,
'type' => 'MeasureType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getOriginatingPostalCode()
{
return $this->OriginatingPostalCode;
}
function setOriginatingPostalCode($OriginatingPostalCode, $charset = 'iso-8859-1')
{
$this->OriginatingPostalCode = $OriginatingPostalCode;
$this->_elements['OriginatingPostalCode']['charset'] = $charset;
}
function getShippingIrregular()
{
return $this->ShippingIrregular;
}
function setShippingIrregular($ShippingIrregular, $charset = 'iso-8859-1')
{
$this->ShippingIrregular = $ShippingIrregular;
$this->_elements['ShippingIrregular']['charset'] = $charset;
}
function getCarrierDetails()
{
return $this->CarrierDetails;
}
function setCarrierDetails($CarrierDetails, $charset = 'iso-8859-1')
{
$this->CarrierDetails = $CarrierDetails;
$this->_elements['CarrierDetails']['charset'] = $charset;
}
function getShippingPackage()
{
return $this->ShippingPackage;
}
function setShippingPackage($ShippingPackage, $charset = 'iso-8859-1')
{
$this->ShippingPackage = $ShippingPackage;
$this->_elements['ShippingPackage']['charset'] = $charset;
}
function getWeightMajor()
{
return $this->WeightMajor;
}
function setWeightMajor($WeightMajor, $charset = 'iso-8859-1')
{
$this->WeightMajor = $WeightMajor;
$this->_elements['WeightMajor']['charset'] = $charset;
}
function getWeightMinor()
{
return $this->WeightMinor;
}
function setWeightMinor($WeightMinor, $charset = 'iso-8859-1')
{
$this->WeightMinor = $WeightMinor;
$this->_elements['WeightMinor']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/CalculatedShippingRateType.php | PHP | asf20 | 4,966 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* UserType
*
* @package PayPal
*/
class UserType extends XSDSimpleType
{
var $AboutMePage;
var $EAISToken;
var $Email;
/**
* Feedback scores are a quantitative expression of the desirability of dealing
* with that person as a Buyer or a Seller in auction transactions. Each auction
* transaction can result in one feedback entry for a given user (the Buyer can
* leave one feedback about the Seller and the Seller can leave one feedback about
* the Buyer). That one feedback can be positive, negative, or neutral. The
* aggregated feedback counts for a particular user represent that user's overall
* feedback score (referred to as a "feedback rating" on the eBay site). This
* rating is commonly expressed as the eBay Feedback score for the user.
*/
var $FeedbackScore;
var $FeedbackPrivate;
var $FeedbackRatingStar;
var $IDVerified;
var $NewUser;
var $RegistrationAddress;
var $RegistrationDate;
var $Site;
var $Status;
var $UserID;
var $UserIDChanged;
var $UserIDLastChanged;
/**
* If present, indicates whether or not the user is subject to VAT. Users who have
* registered with eBay as VAT-exempt are not subject to VAT. See Value-Added Tax
* (VAT). Not returned for users whose country of residence is outside the EU.
* Possible values for the user's status: 2 = Residence in an EU country but user
* registered as VAT-exempt 3 = Residence in an EU country and user not registered
* as VAT-exempt
*/
var $VATStatus;
var $BuyerInfo;
var $SellerInfo;
function UserType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'AboutMePage' =>
array (
'required' => false,
'type' => 'boolean',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'EAISToken' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'Email' =>
array (
'required' => true,
'type' => NULL,
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'FeedbackScore' =>
array (
'required' => false,
'type' => NULL,
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'FeedbackPrivate' =>
array (
'required' => false,
'type' => 'boolean',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'FeedbackRatingStar' =>
array (
'required' => false,
'type' => 'FeedbackRatingStarCodeType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'IDVerified' =>
array (
'required' => false,
'type' => 'boolean',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'NewUser' =>
array (
'required' => false,
'type' => 'boolean',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'RegistrationAddress' =>
array (
'required' => false,
'type' => NULL,
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'RegistrationDate' =>
array (
'required' => false,
'type' => 'dateTime',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'Site' =>
array (
'required' => false,
'type' => NULL,
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'Status' =>
array (
'required' => false,
'type' => 'UserStatusCodeType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'UserID' =>
array (
'required' => false,
'type' => NULL,
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'UserIDChanged' =>
array (
'required' => false,
'type' => 'boolean',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'UserIDLastChanged' =>
array (
'required' => false,
'type' => 'dateTime',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'VATStatus' =>
array (
'required' => false,
'type' => 'VATStatusCodeType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'BuyerInfo' =>
array (
'required' => false,
'type' => 'BuyerType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'SellerInfo' =>
array (
'required' => false,
'type' => 'SellerType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getAboutMePage()
{
return $this->AboutMePage;
}
function setAboutMePage($AboutMePage, $charset = 'iso-8859-1')
{
$this->AboutMePage = $AboutMePage;
$this->_elements['AboutMePage']['charset'] = $charset;
}
function getEAISToken()
{
return $this->EAISToken;
}
function setEAISToken($EAISToken, $charset = 'iso-8859-1')
{
$this->EAISToken = $EAISToken;
$this->_elements['EAISToken']['charset'] = $charset;
}
function getEmail()
{
return $this->Email;
}
function setEmail($Email, $charset = 'iso-8859-1')
{
$this->Email = $Email;
$this->_elements['Email']['charset'] = $charset;
}
function getFeedbackScore()
{
return $this->FeedbackScore;
}
function setFeedbackScore($FeedbackScore, $charset = 'iso-8859-1')
{
$this->FeedbackScore = $FeedbackScore;
$this->_elements['FeedbackScore']['charset'] = $charset;
}
function getFeedbackPrivate()
{
return $this->FeedbackPrivate;
}
function setFeedbackPrivate($FeedbackPrivate, $charset = 'iso-8859-1')
{
$this->FeedbackPrivate = $FeedbackPrivate;
$this->_elements['FeedbackPrivate']['charset'] = $charset;
}
function getFeedbackRatingStar()
{
return $this->FeedbackRatingStar;
}
function setFeedbackRatingStar($FeedbackRatingStar, $charset = 'iso-8859-1')
{
$this->FeedbackRatingStar = $FeedbackRatingStar;
$this->_elements['FeedbackRatingStar']['charset'] = $charset;
}
function getIDVerified()
{
return $this->IDVerified;
}
function setIDVerified($IDVerified, $charset = 'iso-8859-1')
{
$this->IDVerified = $IDVerified;
$this->_elements['IDVerified']['charset'] = $charset;
}
function getNewUser()
{
return $this->NewUser;
}
function setNewUser($NewUser, $charset = 'iso-8859-1')
{
$this->NewUser = $NewUser;
$this->_elements['NewUser']['charset'] = $charset;
}
function getRegistrationAddress()
{
return $this->RegistrationAddress;
}
function setRegistrationAddress($RegistrationAddress, $charset = 'iso-8859-1')
{
$this->RegistrationAddress = $RegistrationAddress;
$this->_elements['RegistrationAddress']['charset'] = $charset;
}
function getRegistrationDate()
{
return $this->RegistrationDate;
}
function setRegistrationDate($RegistrationDate, $charset = 'iso-8859-1')
{
$this->RegistrationDate = $RegistrationDate;
$this->_elements['RegistrationDate']['charset'] = $charset;
}
function getSite()
{
return $this->Site;
}
function setSite($Site, $charset = 'iso-8859-1')
{
$this->Site = $Site;
$this->_elements['Site']['charset'] = $charset;
}
function getStatus()
{
return $this->Status;
}
function setStatus($Status, $charset = 'iso-8859-1')
{
$this->Status = $Status;
$this->_elements['Status']['charset'] = $charset;
}
function getUserID()
{
return $this->UserID;
}
function setUserID($UserID, $charset = 'iso-8859-1')
{
$this->UserID = $UserID;
$this->_elements['UserID']['charset'] = $charset;
}
function getUserIDChanged()
{
return $this->UserIDChanged;
}
function setUserIDChanged($UserIDChanged, $charset = 'iso-8859-1')
{
$this->UserIDChanged = $UserIDChanged;
$this->_elements['UserIDChanged']['charset'] = $charset;
}
function getUserIDLastChanged()
{
return $this->UserIDLastChanged;
}
function setUserIDLastChanged($UserIDLastChanged, $charset = 'iso-8859-1')
{
$this->UserIDLastChanged = $UserIDLastChanged;
$this->_elements['UserIDLastChanged']['charset'] = $charset;
}
function getVATStatus()
{
return $this->VATStatus;
}
function setVATStatus($VATStatus, $charset = 'iso-8859-1')
{
$this->VATStatus = $VATStatus;
$this->_elements['VATStatus']['charset'] = $charset;
}
function getBuyerInfo()
{
return $this->BuyerInfo;
}
function setBuyerInfo($BuyerInfo, $charset = 'iso-8859-1')
{
$this->BuyerInfo = $BuyerInfo;
$this->_elements['BuyerInfo']['charset'] = $charset;
}
function getSellerInfo()
{
return $this->SellerInfo;
}
function setSellerInfo($SellerInfo, $charset = 'iso-8859-1')
{
$this->SellerInfo = $SellerInfo;
$this->_elements['SellerInfo']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/UserType.php | PHP | asf20 | 10,526 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* GetBillingAgreementCustomerDetailsResponseDetailsType
*
* @package PayPal
*/
class GetBillingAgreementCustomerDetailsResponseDetailsType extends XSDSimpleType
{
var $PayerInfo;
/**
* Customer's billing address.
*/
var $BillingAddress;
function GetBillingAgreementCustomerDetailsResponseDetailsType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'PayerInfo' =>
array (
'required' => true,
'type' => 'PayerInfoType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'BillingAddress' =>
array (
'required' => false,
'type' => 'AddressType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getPayerInfo()
{
return $this->PayerInfo;
}
function setPayerInfo($PayerInfo, $charset = 'iso-8859-1')
{
$this->PayerInfo = $PayerInfo;
$this->_elements['PayerInfo']['charset'] = $charset;
}
function getBillingAddress()
{
return $this->BillingAddress;
}
function setBillingAddress($BillingAddress, $charset = 'iso-8859-1')
{
$this->BillingAddress = $BillingAddress;
$this->_elements['BillingAddress']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/GetBillingAgreementCustomerDetailsResponseDetailsType.php | PHP | asf20 | 1,636 |
<?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* CreateRecurringPaymentsProfileRequestDetailsType
*
* @package PayPal
*/
class CreateRecurringPaymentsProfileRequestDetailsType extends XSDSimpleType
{
/**
* Billing Agreement token (required if Express Checkout)
*/
var $Token;
/**
* Information about the credit card to be charged (required if Direct Payment)
*/
var $CreditCard;
/**
* Customer Information for this Recurring Payments
*/
var $RecurringPaymentsProfileDetails;
/**
* Schedule Information for this Recurring Payments
*/
var $ScheduleDetails;
function CreateRecurringPaymentsProfileRequestDetailsType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'Token' =>
array (
'required' => false,
'type' => 'string',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'CreditCard' =>
array (
'required' => false,
'type' => 'CreditCardDetailsType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'RecurringPaymentsProfileDetails' =>
array (
'required' => true,
'type' => 'RecurringPaymentsProfileDetailsType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'ScheduleDetails' =>
array (
'required' => true,
'type' => 'ScheduleDetailsType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getToken()
{
return $this->Token;
}
function setToken($Token, $charset = 'iso-8859-1')
{
$this->Token = $Token;
$this->_elements['Token']['charset'] = $charset;
}
function getCreditCard()
{
return $this->CreditCard;
}
function setCreditCard($CreditCard, $charset = 'iso-8859-1')
{
$this->CreditCard = $CreditCard;
$this->_elements['CreditCard']['charset'] = $charset;
}
function getRecurringPaymentsProfileDetails()
{
return $this->RecurringPaymentsProfileDetails;
}
function setRecurringPaymentsProfileDetails($RecurringPaymentsProfileDetails, $charset = 'iso-8859-1')
{
$this->RecurringPaymentsProfileDetails = $RecurringPaymentsProfileDetails;
$this->_elements['RecurringPaymentsProfileDetails']['charset'] = $charset;
}
function getScheduleDetails()
{
return $this->ScheduleDetails;
}
function setScheduleDetails($ScheduleDetails, $charset = 'iso-8859-1')
{
$this->ScheduleDetails = $ScheduleDetails;
$this->_elements['ScheduleDetails']['charset'] = $charset;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Type/CreateRecurringPaymentsProfileRequestDetailsType.php | PHP | asf20 | 3,070 |
<?php
/**
* @package PayPal
*/
/**
* Include SDK base class.
*/
require_once 'PayPal.php';
/**
* The base class for all Profile handlers
*
* @package PayPal
* @abstract
*/
class ProfileHandler
{
/**
* @access private
*/
var $_params;
function ProfileHandler($parameters)
{
$this->_params = $parameters;
}
function listProfiles()
{
return PayPal::raiseError("Cannot call this method from the base ProfileHandler class");
}
function loadProfile($id)
{
return PayPal::raiseError("Cannot call this method from the base ProfileHandler class");
}
function saveProfile($data)
{
return PayPal::raiseError("Cannot call this method from the base ProfileHandler class");
}
function getParamInfo()
{
return null;
}
function deleteProfile($id)
{
return PayPal::raiseError("Cannot call this method from the base ProfileHandler class");
}
function generateID()
{
return md5(uniqid(mt_rand(), true));
}
function validateParams()
{
return true;
}
function &getInstance($params)
{
return PayPal::raiseError("Cannot call this method from the base ProfileHandler class");
}
function initialize()
{
return true;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Profile/Handler.php | PHP | asf20 | 1,409 |
<?php
/**
* APIProfile encapsulates Profile data
*
* $Id: API.php,v 1.1 2011/09/18 05:16:09 iling Exp $
*
* Modified for 3-token authentication, DHarvey, 3/5/2006
*
* @package PayPal
*/
/**
* Include parent and package classes.
*/
require_once 'PayPal.php';
require_once 'PayPal/Profile.php';
/**
* Stores API Profile information used for performing transactions on the PayPal API
*
* @package PayPal
*/
class APIProfile extends Profile
{
/**
* The API username to make API calls with. Must be a valid PayPal
* API account (not a paypal.com account or developer.paypal.com
* account).
*
* @access private
*/
var $_username;
/**
* The API password to use. This must be set before making any API
* calls; it is not stored by the ProfileHandler backend.
*
* @see setAPIPassword()
*
* @access private
*/
var $_password;
/**
* The 3-token signature
*
* @see setSignature()
*
* @access private
*/
var $_signature;
/**
* The location of the user's private certificate. This should be
* a .pem file.
*
* @access private
*/
var $_certificateFile;
/**
* The password, if any, on the user's private certificate. This
* must be set before making any API calls; it is not stored by
* the ProfileHandler backend.
*
* @see setCertificatePassword()
*
* @access private
*/
var $_certificatePassword;
/**
* Subject to be used when making API calls. This is for making
* calls on behalf of another PayPal user with your own API
* account.
*
* @access private
*/
var $_subject;
/*
* Used for permissoning APIs, sent as HTTPHeader
* @access private
*/
var $_authSignature;
/*
* Used for permissoning APIs, sent as HTTPHeader
* @access private
*/
var $_authToken;
/*
* Used for permissoning APIs, sent as HTTPHeader
* @access private
*/
var $_authTimestamp;
/**
* Constructor
*
* @param string $id A unique id for the profile.
* @param ProfileHandler $handler A handler object where the profile is stored.
*
*/
function APIProfile($id, &$handler)
{
parent::Profile($id, $handler);
}
/**
* Validates the profile data currently loaded before use.
*
* @return mixed true if the data is valid, or a PayPal_Error object on failure.
*/
function validate()
{
// certificate or signature or UNI pay op permissioning is required
if(empty($this->_subject)&& (empty($this->_authSignature)&& empty($this->_authToken)&& empty($this->_authTimestamp))) {
if (empty($this->_username) ||
empty($this->_password) ||
(empty($this->_certificateFile) && empty($this->_signature)) ||
empty($this->_environment)) {
return PayPal::raiseError("API Username, Password, Certificate File and Environment must all be set or auth token,auth signature and auth timestamp must be set");
}
if (! empty($this->_certificateFile) && !file_exists($this->_certificateFile)) {
return PayPal::raiseError("Could not find certificate file '{$this->_certificateFile}'");
}
if (!in_array(strtolower($this->_environment), $this->_validEnvironments, true)) {
return PayPal::raiseError("Environment '{$this->_environment}' is not a valid environment.");
}
}
return true;
}
/**
* Sets the API username for the profile.
*
* @param string The API username.
*/
function setAPIUsername($username)
{
$this->_username = $username;
}
/**
* Returns the API username for the profile.
*
* @return string The API username.
*/
function getAPIUsername()
{
return $this->_username;
}
/**
* Sets the API password for the profile.
*
* @param string The password for the profile.
*/
function setAPIPassword($password)
{
$this->_password = $password;
}
/**
* Get the API password for the profile.
*
* @return string The password for the profile.
*/
function getAPIPassword()
{
return $this->_password;
}
/**
* Sets the 3-token signature
*
* @param string The password for the profile.
*/
function setSignature($signature)
{
$this->_signature = $signature;
}
/**
* Get the 3-token signature.
*
* @return string The password for the profile.
*/
function getSignature()
{
return $this->_signature;
}
/**
* Get the Certificate file associated with the profile.
*
* @return string The certificate file associated with the profile.
*/
function getCertificateFile()
{
return $this->_certificateFile;
}
/**
* Set the certificate file associated with the profile.
*
* @param string The certificate file associated with the profile.
*/
function setCertificateFile($filename)
{
$this->_certificateFile = $filename;
}
/**
* Set the certificate password.
*
* @param string The certificate password.
*/
function setCertificatePassword($password)
{
$this->_certificatePassword = $password;
}
/**
* Get the certificate password.
*
* @return string The certificate password.
*/
function getCertificatePassword()
{
return $this->_certificatePassword;
}
/**
* Set the subject associated with the profile.
*
* @param string The subject of the profile.
*/
function setSubject($subject)
{
$this->_subject = $subject;
}
/**
* Get the subject of the associated profile.
*
* @return string The subject associated with the profile.
*/
function getSubject()
{
return $this->_subject;
}
/**
* set the AuthSignature of the associated profile.
* Used for permissioning APIs
* @return string The subject associated with the profile.
*/
function setAuthSignature($AuthSignature)
{
$this->_authSignature =$AuthSignature;
}
/**
* get the AuthSignature of the associated profile.
* Used for permissioning APIs
* @return string The subject associated with the profile.
*/
function getAuthSignature()
{
return $this->_authSignature;
}
/**
* set the Authtoken of the associated profile.
* Used for permissioning APIs
* @return string The subject associated with the profile.
*/
function setAuthToken($AuthToken)
{
$this->_authToken =$AuthToken;
}
/**
* get the Authtoken of the associated profile.
* Used for permissioning APIs
* @return string The subject associated with the profile.
*/
function getAuthToken()
{
return $this->_authToken;
}
/**
* set the Authtimestamp of the associated profile.
* Used for permissioning APIs
* @return string The subject associated with the profile.
*/
function setAuthTimestamp($AuthTimestamp)
{
$this->_authTimestamp =$AuthTimestamp;
}
/**
* get the Authtimestamp of the associated profile.
* Used for permissioning APIs
* @return string The subject associated with the profile.
*/
function getAuthTimestamp()
{
return $this->_authTimestamp;
}
/**
* Returns an array of member variables names which should be
* included when storing the profile.
*
* @return array An array of member variable names which should be included.
* @access protected
*/
function _getSerializeList()
{
return array('username', 'certificateFile',
'subject', 'environment');
}
function getInstance($id, &$handler)
{
$classname = __CLASS__;
$inst = &new $classname($id, $handler);
$result = $inst->_load();
if (PayPal::isError($result)) {
return $result;
}
$result = $inst->loadEnvironments();
if (PayPal::isError($result)) {
return $result;
}
return $inst;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Profile/API.php | PHP | asf20 | 8,789 |
<?php
/**
* @package PayPal
*/
/**
* Include parent and package classes.
*/
require_once 'PayPal.php';
require_once 'PayPal/Profile/Handler.php';
/**
* Array handler class for hardcoding a PayPal profile.
*
* @package PayPal
*/
class ProfileHandler_Array extends ProfileHandler
{
function ProfileHandler_Array($parameters)
{
parent::ProfileHandler($parameters);
}
function loadProfile($id)
{
return $this->_params;
}
function saveProfile($data)
{
$this->_params = $data;
return 'default';
}
function deleteProfile($id)
{
$this->_params = null;
}
function getParamInfo()
{
return null;
}
function listProfiles()
{
return array('default');
}
function &getInstance($params)
{
$classname = __CLASS__;
$inst =& new $classname($params);
return $inst;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Profile/Handler/Array.php | PHP | asf20 | 987 |
<?php
/**
* @package PayPal
*/
/**
* Include parent and package classes.
*/
require_once 'PayPal.php';
require_once 'PayPal/Profile/Handler.php';
/**
* File handler class for storing PayPal profiles
*
* @package PayPal
*/
class ProfileHandler_File extends ProfileHandler
{
function ProfileHandler_File($parameters)
{
parent::ProfileHandler($parameters);
}
/**
* @access private
*/
function _getFilename($id)
{
return "{$this->_params['path']}/$id.ppd";
}
function listProfiles()
{
$validate = $this->validateParams();
if (PayPal::isError($validate)) {
return $retval;
}
$filemask = $this->_getFilename("*");
$profile_files = glob($filemask);
$retval = array();
foreach ($profile_files as $pf) {
$filename = basename($pf);
$retval[] = substr($filename, 0, strpos($filename, '.'));
}
return $retval;
}
function loadProfile($id)
{
$retval = $this->validateParams();
if (PayPal::isError($retval)) {
return $retval;
}
$open_file = $this->_getFileName($id);
if (!file_exists($open_file)) {
return PayPal::raiseError("Profile '$id' cannot be loaded, does not exist.");
}
$data = file_get_contents($open_file, false);
$retval = @unserialize($data);
if (!is_array($retval)) {
return PayPal::raiseError("Unserialization of data failed.");
}
return $retval;
}
function saveProfile($data, $id = null)
{
$retval = $this->validateParams();
if (PayPal::isError($retval)) {
return $retval;
}
$id = (is_null($id)) ? $this->generateID() : $id;
$write_file = $this->_getFileName($id);
$fr = @fopen($write_file, 'w', false);
if (!$fr) {
return PayPal::raiseError("Could not open file '$write_file' for writing.");
}
$serialized = serialize($data);
fputs($fr, $serialized);
fclose($fr);
return $id;
}
function deleteProfile($id)
{
$retval = $this->validateParams();
if (PayPal::isError($retval)) {
return $retval;
}
$delete_file = $this->_getFileName($id);
if (!@unlink($delete_file)) {
return PayPal::raiseError("Could not delete the Profile file '$delete_file'");
}
return true;
}
function getParamInfo()
{
return array('path' => array('desc' => 'Profile Save Path',
'type' => 'string'));
}
function validateParams()
{
if (!isset($this->_params['path'])) {
return PayPal::raiseError("You must provide the 'path' parameter for this handler");
}
if (file_exists($this->_params['path']) &&
is_dir($this->_params['path'])) {
return true;
}
return false;
}
function &getInstance($params)
{
$classname = __CLASS__;
$inst =& new $classname($params);
return $inst;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Profile/Handler/File.php | PHP | asf20 | 3,366 |
<?php
/**
* @package PayPal
*
* $Id: EWP.php,v 1.1 2011/09/18 05:16:09 iling Exp $
*/
/**
* Include parent and package classes.
*/
require_once 'PayPal.php';
require_once 'PayPal/Profile.php';
require_once 'PayPal/EWPServices.php';
/**
* Stores EWP Profile information used for encrypting buttons and PayPal forms.
*
* @package PayPal
*/
class EWPProfile extends Profile
{
/**
* The private Key file
*
* @access private
*/
var $_privateKeyFile;
/**
* The password on the private key.
*
* @access private
*/
var $_privateKeyPassword;
/**
* The URL to the button image
*
* @access private
*/
var $_buttonImageURL;
/**
* The URL the button posts to
*
* @access private
*/
var $_buttonURL;
/**
* The PayPal-assigned id of the certificate.
*
* @access private
*/
var $_certificateId;
/**
* The location of the .pem certificate file.
*
* @access private
*/
var $_certificateFile;
/**
* Class constructor
*
* @param ProfileHandler &$handler A handler where the profile should be stored.
*/
function EWPProfile($id, &$handler)
{
parent::Profile($id, $handler);
}
/**
* Validates the profile data currently loaded before use.
*
* @return mixed true if the data is valid, or a PayPal_Error object on failure.
*/
function validate()
{
if (empty($this->_certificateFile)) {
return PayPal::raiseError("Certificate File must be set!");
}
if (empty($this->_certificateId)) {
return PayPal::raiseError("Certificate ID must be set.");
}
if (empty($this->_environment)) {
return PayPal::raiseError("Environment must be set.");
}
if (!file_exists($this->_certificateFile)) {
return PayPal::raiseError("Could not find certificate file '{$this->_certificateFile}'");
}
if (!in_array(strtolower($this->_environment), $this->_validEnvironments, true)) {
return PayPal::raiseError("Environment '{$this->_environment}' is not a valid environment.");
}
return true;
}
/**
* Get the merchant certificate id associated with the profile
*
* @return string The certificate id associated with the profile
*/
function getCertificateId()
{
return $this->_certificateId;
}
/**
* Set the merchant certificate id associated with the profile
*
* @param string The certificate id associated with the profile
*/
function setCertificateId($filename)
{
$this->_certificateId = $filename;
}
/**
* Get the merchant certificate file associated with the profile
*
* @return string The certificate file associated with the profile
*/
function getCertificateFile()
{
return $this->_certificateFile;
}
/**
* Set the merchant certificate file associated with the profile
*
* @param string The certificate file associated with the profile
*/
function setCertificateFile($filename)
{
if (!file_exists($filename)) {
return PayPal::raiseError("The private key '$filename' does not exist");
}
$this->_certificateFile = $filename;
}
/**
* Returns the URL where the button image is
*
* @return string The URL to the button image
*/
function getButtonImage()
{
return $this->_buttonImageURL;
}
/**
* Set the URL where the button image is
*
* @param string The URL to the button image
*/
function setButtonImage($url)
{
$this->_buttonImageURL = $url;
}
/**
* Returns the URL where the button will post to
*
* @return string The URL where the button will post to
*/
function getUrl()
{
return $this->_buttonURL;
}
/**
* Sets the URL where the button will post to
*
* @param string The URL where the button should post to
*/
function setUrl($url)
{
$this->_buttonURL = $url;
}
/**
* Set the Merchant private key file
*
* @param string The Merchant Private Key File
* @return mixed True on success, a PayPal error object on faliure
*/
function setPrivateKeyFile($filename)
{
if (!file_exists($filename)) {
return PayPal::raiseError("The private key '$filename' does not exist");
}
$this->_privateKeyFile = $filename;
return true;
}
/**
* Get the merchant private key file associated with the profile
*
* @return string The merchant private key file associated with the profile
*/
function getPrivateKeyFile()
{
return $this->_privateKeyFile;
}
/**
* Set the merchant private key password
*
* @param string The private key password
*/
function setPrivateKeyPassword($password)
{
$this->_privateKeyPassword = $password;
}
/**
* Get the merchant private key password
*
* @return string The private key password.
*/
function getPrivateKeyPassword()
{
return $this->_privateKeyPassword;
}
/**
* Returns an array of member variables names which should be included
* when storing the profile.
*
* @return array An array of member variable names which should be included
* @access protected
*/
function _getSerializeList()
{
return array('environment', 'certificateId', 'certificateFile', 'privateKeyFile', 'buttonImageURL', 'buttonURL');
}
/**
* Factory for creating instances of the EWPProfile. Used when
* providing an existing Profile ID to load from
*
* @param string The Profile ID of this instance
* @param object A valid Profile Handler instance
* @return object A new instance of EWPProfile for the given ID or a PayPal error object on failure
*/
function getInstance($id, &$handler)
{
$classname = __CLASS__;
$inst = new $classname($id, $handler);
$result = $inst->_load();
if (PayPal::isError($result)) {
return $result;
}
return $inst;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Profile/EWP.php | PHP | asf20 | 6,647 |
<?php
/**
* @package PayPal
*
* $Id: Profile.php,v 1.1 2011/09/18 05:16:15 iling Exp $
*/
/**
* Base package class.
*/
require_once 'PayPal.php';
/**
* Base class for PayPal Profiles, managaes interaction with handlers, etc.
*
* @package PayPal
* @abstract
*/
class Profile
{
/**
* Which environment should API calls be made against?
*
* @see $_validEnvironments
*
* @access protected
*/
var $_environment;
/**
* The list of valid environments that API calls can be executed
* against.
*
* @access protected
*/
var $_validEnvironments = array();
/**
* The ProfileHandler instance associated with this Profile.
*
* @access protected
*/
var $_handler;
/**
* The ProfileHandler ID.
*
* @access protected
*/
var $_handler_id;
/**
* Base constructor which creates a default handler if none was
* provided.
*
* @param string The name of the profile
* @param object An optional handler to store the profile in
*/
function Profile($id, &$handler)
{
$this->_handler =& $handler;
$this->_handler_id = $id;
}
/**
* Loads the profile data from the defined handler.
*
* @return mixed true on success or a PayPal_Error object on failure
* @final
* @access private
*/
function _load()
{
$loaded_data = $this->_handler->loadProfile($this->_handler_id);
$expected_keys = $this->_getSerializeList();
if (!is_a($this->_handler, 'ProfileHandler_Array')) {
$expected_keys[] = 'classname';
}
if (PayPal::isError($loaded_data)) {
foreach ($expected_keys as $key) {
$ikey = "_$key";
$this->$ikey = null;
}
return PayPal::raiseError("Could not load data for non-existant profile '{$this->_handler_id}'");
}
$expected_keys = array_flip($expected_keys);
foreach ($loaded_data as $key => $value) {
$ikey = "_$key";
$this->$ikey = $value;
unset($expected_keys[$key]);
}
if (!empty($expected_keys)) {
$key_list = implode(', ', array_flip($expected_keys));
return PayPal::raiseError("The following values were expected but not found in the profile data: $key_list");
}
return $this->loadEnvironments();
}
function getID()
{
return $this->_handler_id;
}
function getInstance($id, &$handler)
{
return PayPal::raiseError("Cannot return an instance of the base Profile class");
}
/**
* Loads the environment names from the endpoint map.
*
* @return mixed True on success or a PayPal error object on failure
*/
function loadEnvironments()
{
$version = PayPal::getWSDLVersion();
$endpoints = PayPal::getEndpoints();
if (PayPal::isError($endpoints)) {
return $endpoints;
}
foreach ($endpoints as $range) {
if ($version >= $range['min'] &&
$version <= $range['max']) {
foreach (array_keys($range['environments']) as $environment) {
$this->_validEnvironments[] = strtolower($environment);
}
return true;
}
}
return PayPal::raiseError("Could not find any endpoint mappings for WSDL version '$version'");
}
/**
* Saves the profile data to the defined handler.
*
* @return mixed true on success or a PayPal_Error object on failure
* @final
*/
function save()
{
$values = $this->_getSerializeList();
foreach ($values as $value) {
$ivalue = "_$value";
if (isset($this->$ivalue)) {
$data[$value] = $this->$ivalue;
} else {
$data[$value] = null;
}
}
$data['classname'] = get_class($this);
return $this->_handler->saveProfile($data, $this->_handler_id);
}
/**
* Returns an array of member variables names which should be
* included when storing the profile.
*
* @return array An array of member variable names which should be included
* @access protected
*/
function _getSerializeList()
{
return array();
}
/**
* Set the environment associated with this profile.
*
* @param string True on success, a Paypal error object on failure
*/
function setEnvironment($environment)
{
$environment = strtolower($environment);
$envs = $this->getValidEnvironments();
if (PayPal::isError($envs)) {
return $envs;
}
if (in_array($environment, $envs)) {
$this->_environment = $environment;
return true;
}
return PayPal::raiseError("Invalid Environment Specified");
}
/**
* Get the environment associated with the profile.
*
* @return string The environment associated with the profile.
*/
function getEnvironment()
{
return strtolower($this->_environment);
}
/**
* Returns an array of valid Environments
*
* @return array An array of valid environment names
*/
function getValidEnvironments()
{
if (empty($this->_validEnvironments)) {
$res = $this->loadEnvironments();
if (PayPal::isError($res)) {
return $res;
}
}
return $this->_validEnvironments;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Profile.php | PHP | asf20 | 5,876 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: WSDL.php,v 1.1 2011/09/18 05:16:03 iling Exp $
//
require_once 'PayPal/SOAP/Base.php';
require_once 'PayPal/SOAP/Fault.php';
require_once 'HTTP/Request.php';
define('WSDL_CACHE_MAX_AGE', 43200);
define('WSDL_CACHE_USE', 0); // set to zero to turn off caching
/**
* This class parses WSDL files, and can be used by SOAP::Client to
* properly register soap values for services.
*
* Originally based on SOAPx4 by Dietrich Ayala
* http://dietrich.ganx4.com/soapx4
*
* TODO:
* add wsdl caching
* refactor namespace handling ($namespace/$ns)
* implement IDL type syntax declaration so we can generate WSDL
*
* @access public
* @package SOAP::Client
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
* @author Dietrich Ayala <dietrich@ganx4.com> Original Author
*/
class SOAP_WSDL extends SOAP_Base
{
var $tns = null;
var $definition = array();
var $namespaces = array();
var $ns = array();
var $xsd = SOAP_XML_SCHEMA_VERSION;
var $complexTypes = array();
var $elements = array();
var $messages = array();
var $portTypes = array();
var $bindings = array();
var $imports = array();
var $services = array();
var $service = '';
var $uri = '';
var $docs = false;
/**
* Proxy parameters
*
* @var array
*/
var $proxy = null;
var $trace = 0;
/**
* Use WSDL cache
*
* @var boolean
*/
var $cacheUse = null;
/**
* Cache max lifetime (in seconds)
*
* @var int
*/
var $cacheMaxAge = null;
/**
* Class to use for WSDL parsing. Can be overridden for special
* cases, subclasses, etc.
* @var string $wsdlParserClass
*/
var $wsdlParserClass = 'SOAP_WSDL_Parser';
/**
* SOAP_WSDL constructor.
*
* @param string $wsdl_uri URL to WSDL file.
* @param array $proxy Contains options for HTTP_Request class (see HTTP/Request.php).
* @param boolean $cacheUse Use WSDL caching. Defaults to false.
* @param integer $cacheMaxAge Cache max lifetime (in seconds).
* @param boolean $docs Parse documentation in the WSDL? Defaults to false.
*
* @access public
*/
function SOAP_WSDL($wsdl_uri = false,
$proxy = array(),
$cacheUse = WSDL_CACHE_USE,
$cacheMaxAge = WSDL_CACHE_MAX_AGE,
$docs = false)
{
parent::SOAP_Base('WSDL');
$this->uri = $wsdl_uri;
$this->proxy = $proxy;
$this->cacheUse = $cacheUse;
$this->cacheMaxAge = $cacheMaxAge;
$this->docs = $docs;
if ($wsdl_uri) {
$this->parseURL($wsdl_uri);
reset($this->services);
$this->service = key($this->services);
}
}
function set_service($service)
{
if (array_key_exists($service, $this->services)) {
$this->service = $service;
}
}
/**
* @deprecated use parseURL instead
*/
function parse($wsdl_uri, $proxy = array())
{
$this->parseURL($wsdl_uri, $proxy);
}
/**
* Fill the WSDL array tree with data from a WSDL file
*
* @param string
* @param array proxy related parameters
* @return void
*/
function parseURL($wsdl_uri, $proxy = array())
{
$parser =& new $this->wsdlParserClass($wsdl_uri, $this, $this->docs);
if ($parser->fault) {
$this->_raiseSoapFault($parser->fault);
}
}
/**
* Fill the WSDL array tree with data from one or more PHP class objects
*
* @param mixed $wsdl_obj An object or array of objects to add to the internal WSDL tree
* @param string $service_name Name of the WSDL <service>
* @param string $service_desc Optional description of the WSDL <service>
* @return void
*/
function parseObject(&$wsdl_obj, $targetNamespace, $service_name, $service_desc = '')
{
$parser =& new SOAP_WSDL_ObjectParser($wsdl_obj, $this, $targetNamespace, $service_name, $service_desc);
if ($parser->fault) {
$this->_raiseSoapFault($parser->fault);
}
}
function getEndpoint($portName)
{
return (isset($this->services[$this->service]['ports'][$portName]['address']['location']))
? $this->services[$this->service]['ports'][$portName]['address']['location']
: $this->_raiseSoapFault("no endpoint for port for $portName", $this->uri);
}
function _getPortName($operation, $service)
{
if (isset($this->services[$service]['ports'])) {
foreach ($this->services[$service]['ports'] as $port => $portAttrs) {
$type = $this->services[$service]['ports'][$port]['type'];
if ($type == 'soap' &&
isset($this->bindings[$portAttrs['binding']]['operations'][$operation])) {
return $port;
}
}
}
return null;
}
/**
* find the name of the first port that contains an operation of
* name $operation. always returns a the soap portName.
*/
function getPortName($operation, $service = null)
{
if (!$service) $service = $this->service;
if (isset($this->services[$service]['ports'])) {
$portName = $this->_getPortName($operation, $service);
if ($portName) return $portName;
}
// Try any service in the WSDL.
foreach ($this->services as $serviceName => $service) {
if (isset($this->services[$serviceName]['ports'])) {
$portName = $this->_getPortName($operation, $serviceName);
if ($portName) {
$this->service = $serviceName;
return $portName;
}
}
}
return $this->_raiseSoapFault("no operation $operation in wsdl", $this->uri);
}
function getOperationData($portName, $operation)
{
if (isset($this->services[$this->service]['ports'][$portName]['binding'])
&& $binding = $this->services[$this->service]['ports'][$portName]['binding']) {
// get operation data from binding
if (is_array($this->bindings[$binding]['operations'][$operation])) {
$opData = $this->bindings[$binding]['operations'][$operation];
}
// get operation data from porttype
$portType = $this->bindings[$binding]['type'];
if (!$portType) {
return $this->_raiseSoapFault("no port type for binding $binding in wsdl " . $this->uri);
}
if (is_array($this->portTypes[$portType][$operation])) {
if (isset($this->portTypes[$portType][$operation]['parameterOrder']))
$opData['parameterOrder'] = $this->portTypes[$portType][$operation]['parameterOrder'];
$opData['input'] = array_merge($opData['input'], $this->portTypes[$portType][$operation]['input']);
$opData['output'] = array_merge($opData['output'], $this->portTypes[$portType][$operation]['output']);
}
if (!$opData)
return $this->_raiseSoapFault("no operation $operation for port $portName, in wsdl", $this->uri);
$opData['parameters'] = false;
if (isset($this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['input']['namespace']))
$opData['namespace'] = $this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['input']['namespace'];
// message data from messages
$inputMsg = $opData['input']['message'];
if (is_array($this->messages[$inputMsg])) {
foreach ($this->messages[$inputMsg] as $pname => $pattrs) {
if ($opData['style'] == 'document' && $opData['input']['use'] == 'literal'
&& $pname == 'parameters') {
$opData['parameters'] = true;
$opData['namespace'] = $this->namespaces[$pattrs['namespace']];
$el = $this->elements[$pattrs['namespace']][$pattrs['type']];
if (isset($el['elements'])) {
foreach ($el['elements'] as $elname => $elattrs) {
$opData['input']['parts'][$elname] = $elattrs;
}
}
} else {
$opData['input']['parts'][$pname] = $pattrs;
}
}
}
$outputMsg = $opData['output']['message'];
if (is_array($this->messages[$outputMsg])) {
foreach ($this->messages[$outputMsg] as $pname => $pattrs) {
if ($opData['style'] == 'document' && $opData['output']['use'] == 'literal'
&& $pname == 'parameters') {
$el = $this->elements[$pattrs['namespace']][$pattrs['type']];
if (isset($el['elements'])) {
foreach ($el['elements'] as $elname => $elattrs) {
$opData['output']['parts'][$elname] = $elattrs;
}
}
} else {
$opData['output']['parts'][$pname] = $pattrs;
}
}
}
return $opData;
}
return $this->_raiseSoapFault("no binding for port $portName in wsdl", $this->uri);
}
function matchMethod(&$operation)
{
// Overloading lowercases function names :(
foreach ($this->services[$this->service]['ports'] as $port => $portAttrs) {
foreach (array_keys($this->bindings[$portAttrs['binding']]['operations']) as $op) {
if (strcasecmp($op, $operation) == 0) {
$operation = $op;
}
}
}
}
/**
* getDataHandler
*
* Given a datatype, what function handles the processing?
* this is used for doc/literal requests where we receive
* a datatype, and we need to pass it to a method in out
* server class
*
* @param string datatype
* @param string namespace
* @returns string methodname
* @access public
*/
function getDataHandler($datatype, $namespace)
{
// see if we have an element by this name
if (isset($this->namespaces[$namespace]))
$namespace = $this->namespaces[$namespace];
if (isset($this->ns[$namespace])) {
$nsp = $this->ns[$namespace];
//if (!isset($this->elements[$nsp]))
// $nsp = $this->namespaces[$nsp];
if (isset($this->elements[$nsp][$datatype])) {
$checkmessages = array();
// find what messages use this datatype
foreach ($this->messages as $messagename => $message) {
foreach ($message as $partname => $part) {
if ($part['type'] == $datatype) {
$checkmessages[] = $messagename;
break;
}
}
}
// find the operation that uses this message
$dataHandler = null;
foreach($this->portTypes as $portname => $porttype) {
foreach ($porttype as $opname => $opinfo) {
foreach ($checkmessages as $messagename) {
if ($opinfo['input']['message'] == $messagename) {
return $opname;
}
}
}
}
}
}
return null;
}
function getSoapAction($portName, $operation)
{
if (isset($this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['soapAction']) &&
$soapAction = $this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['soapAction']) {
return $soapAction;
}
return false;
}
function getNamespace($portName, $operation)
{
if (isset($this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]) &&
isset($this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['input']['namespace']) &&
$namespace = $this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['input']['namespace']) {
return $namespace;
}
return false;
}
function getNamespaceAttributeName($namespace)
{
/* If it doesn't exist at first, flip the array and check
* again. */
if (empty($this->ns[$namespace])) {
$this->ns = array_flip($this->namespaces);
}
/* If it doesn't exist now, add it. */
if (empty($this->ns[$namespace])) {
return $this->addNamespace($namespace);
}
return $this->ns[$namespace];
}
function addNamespace($namespace)
{
if (!empty($this->ns[$namespace])) {
return $this->ns[$namespace];
}
$n = count($this->ns);
$attr = 'ns' . $n;
$this->namespaces['ns' . $n] = $namespace;
$this->ns[$namespace] = $attr;
return $attr;
}
function _validateString($string)
{
// XXX this should be done sooner or later
// return true;
return preg_match("/^[\w_:#\/]+$/", $string);
}
function _addArg(&$args, &$argarray, $argname)
{
if ($args) {
$args .= ', ';
}
$args .= "\$" . $argname;
if (!$this->_validateString($argname)) {
return null;
}
if ($argarray) {
$argarray .= ', ';
}
$argarray .= "\"$argname\" => \$" . $argname;
}
function _elementArg(&$args, &$argarray, &$_argtype, $_argname)
{
$comments = '';
$el = $this->elements[$_argtype['namespace']][$_argtype['type']];
$tns = isset($this->ns[$el['namespace']]) ? $this->ns[$el['namespace']] : $_argtype['namespace'];
if (!empty($el['complex']) || (isset($el['type']) && isset($this->complexTypes[$tns][$el['type']]))) {
// The element is a complex type.
$comments .= " // {$_argtype['type']} is a ComplexType, refer to the WSDL for more info.\n";
$attrname = "{$_argtype['type']}_attr";
if (isset($el['type']) && isset($this->complexTypes[$tns][$el['type']]['attribute'])) {
$comments .= " // {$_argtype['type']} may require attributes, refer to the WSDL for more info.\n";
}
$comments .= " \${$attrname}['xmlns'] = '{$this->namespaces[$_argtype['namespace']]}';\n";
$comments .= " \${$_argtype['type']} =& new SOAP_Value('{$_argtype['type']}', false, \${$_argtype['type']}, \$$attrname);\n";
$this->_addArg($args, $argarray, $_argtype['type']);
if (isset($el['type']) && isset($this->complexTypes[$tns][$el['type']]['attribute'])) {
if ($args) {
$args .= ', ';
}
$args .= '$' . $attrname;
}
} elseif (isset($el['elements'])) {
foreach ($el['elements'] as $ename => $element) {
$comments .= " \$$ename =& new SOAP_Value('{{$this->namespaces[$element['namespace']]}}$ename', '" .
(isset($element['type']) ? $element['type'] : false) . "', \$$ename);\n";
$this->_addArg($args, $argarray, $ename);
}
} else {
$comments .= " \$$_argname =& new SOAP_Value('{{$this->namespaces[$tns]}}$_argname', '{$el['type']}', \$$_argname);\n";
$this->_addArg($args, $argarray, $_argname);
}
return $comments;
}
function _complexTypeArg(&$args, &$argarray, &$_argtype, $_argname)
{
$comments = '';
if (isset($this->complexTypes[$_argtype['namespace']][$_argtype['type']])) {
$comments = " // $_argname is a ComplexType {$_argtype['type']},\n";
$comments .= " // refer to wsdl for more info\n";
if (isset($this->complexTypes[$_argtype['namespace']][$_argtype['type']]['attribute'])) {
$comments .= " // $_argname may require attributes, refer to wsdl for more info\n";
}
$wrapname = '{' . $this->namespaces[$_argtype['namespace']].'}' . $_argtype['type'];
$comments .= " \$$_argname =& new SOAP_Value('$_argname', '$wrapname', \$$_argname);\n";
}
$this->_addArg($args, $argarray, $_argname);
return $comments;
}
/**
* Generates stub code from the WSDL that can be saved to a file
* or eval'd into existence.
*/
function generateProxyCode($port = '', $classname='')
{
$multiport = count($this->services[$this->service]['ports']) > 1;
if (!$port) {
reset($this->services[$this->service]['ports']);
$port = current($this->services[$this->service]['ports']);
}
// XXX currently do not support HTTP ports
if ($port['type'] != 'soap') {
return null;
}
// XXX currentPort is BAD
$clienturl = $port['address']['location'];
if (!$classname) {
if ($multiport || $port) {
$classname = 'WebService_' . $this->service . '_' . $port['name'];
} else {
$classname = 'WebService_' . $this->service;
}
$classname = preg_replace('/[ .\-\(\)]+/', '_', $classname);
}
if (!$this->_validateString($classname)) {
return null;
}
if (is_array($this->proxy) && count($this->proxy)) {
$class = "class $classname extends SOAP_Client\n{\n" .
" function $classname(\$path = \"$clienturl\")\n{\n" .
" \$this->SOAP_Client(\$path, 0, 0,
array(";
foreach ($this->proxy as $key => $val) {
if (is_array($val)) {
$class .= "\"$key\" => array(";
foreach ($val as $key2 => $val2) {
$class .= "\"$key2\" => \"$val2\",";
}
$class .= ')';
} else {
$class .= "\"$key\" => \"$val\",";
}
}
$class .= "));\n }\n";
$class = str_replace(',))', '))', $class);
} else {
$class = "class $classname extends SOAP_Client\n{\n" .
" function $classname(\$path = \"$clienturl\")\n {\n" .
" \$this->SOAP_Client(\$path, 0);\n" .
" }\n";
}
// get the binding, from that get the port type
$primaryBinding = $port['binding']; //$this->services[$this->service]['ports'][$port['name']]["binding"];
$primaryBinding = preg_replace("/^(.*:)/", '', $primaryBinding);
$portType = $this->bindings[$primaryBinding]['type'];
$portType = preg_replace("/^(.*:)/", '', $portType);
$style = $this->bindings[$primaryBinding]['style'];
// XXX currentPortType is BAD
foreach ($this->portTypes[$portType] as $opname => $operation) {
$soapaction = isset($this->bindings[$primaryBinding]['operations'][$opname]['soapAction']) ?
$this->bindings[$primaryBinding]['operations'][$opname]['soapAction'] :
null;
if (isset($this->bindings[$primaryBinding]['operations'][$opname]['style'])) {
$opstyle = $this->bindings[$primaryBinding]['operations'][$opname]['style'];
} else {
$opstyle = $style;
}
$use = $this->bindings[$primaryBinding]['operations'][$opname]['input']['use'];
if ($use == 'encoded') {
$namespace = $this->bindings[$primaryBinding]['operations'][$opname]['input']['namespace'];
} else {
$bindingType = $this->bindings[$primaryBinding]['type'];
$ns = $this->portTypes[$bindingType][$opname]['input']['namespace'];
$namespace = $this->namespaces[$ns];
}
$args = '';
$argarray = '';
$comments = '';
$wrappers = '';
foreach ($operation['input'] as $argname => $argtype) {
if ($argname == 'message') {
foreach ($this->messages[$argtype] as $_argname => $_argtype) {
if ($opstyle == 'document' && $use == 'literal' &&
$_argtype['name'] == 'parameters') {
// The type or element refered to is used
// for parameters.
$elattrs = null;
$element = $_argtype['element'];
$el = $this->elements[$_argtype['namespace']][$_argtype['type']];
if ($el['complex']) {
$namespace = $this->namespaces[$_argtype['namespace']];
// XXX need to wrap the parameters in
// a soap_value.
}
if (isset($el['elements'])) {
foreach ($el['elements'] as $elname => $elattrs) {
// Is the element a complex type?
if (isset($this->complexTypes[$elattrs['namespace']][$elname])) {
$comments .= $this->_complexTypeArg($args, $argarray, $_argtype, $_argname);
} else {
$this->_addArg($args, $argarray, $elname);
}
}
}
if ($el['complex'] && $argarray) {
$wrapname = '{' . $this->namespaces[$_argtype['namespace']].'}' . $el['name'];
$comments .= " \${$el['name']} =& new SOAP_Value('$wrapname', false, \$v = array($argarray));\n";
$argarray = "'{$el['name']}' => \${$el['name']}";
}
} else {
if (isset($_argtype['element'])) {
// Element argument.
$comments .= $this->_elementArg($args, $argarray, $_argtype, $_argtype['type']);
} else {
// Complex type argument.
$comments .= $this->_complexTypeArg($args, $argarray, $_argtype, $_argname);
}
}
}
}
}
// Validate entries.
// Operation names are function names, so try to make sure
// it's legal. This could potentially cause collisions,
// but let's try to make everything callable and see how
// many problems that causes.
$opname_php = preg_replace('/[ .\-\(\)]+/', '_', $opname);
if (!$this->_validateString($opname_php)) {
return null;
}
if ($argarray) {
$argarray = "array($argarray)";
} else {
$argarray = 'null';
}
$class .= " function &$opname_php($args)\n {\n$comments$wrappers" .
" return \$this->call('$opname',\n" .
" \$v = $argarray,\n" .
" array('namespace' => '$namespace',\n" .
" 'soapaction' => '$soapaction',\n" .
" 'style' => '$opstyle',\n" .
" 'use' => '$use'" .
($this->trace?",\n 'trace' => 1" : '') . "));\n" .
" }\n";
}
$class .= "}\n";
return $class;
}
function generateAllProxies()
{
$proxycode = '';
foreach (array_keys($this->services[$this->service]['ports']) as $key) {
$port =& $this->services[$this->service]['ports'][$key];
$proxycode .= $this->generateProxyCode($port);
}
return $proxycode;
}
function &getProxy($port = '', $name = '')
{
$multiport = count($this->services[$this->service]['ports']) > 1;
if (!$port) {
reset($this->services[$this->service]['ports']);
$port = current($this->services[$this->service]['ports']);
}
if ($multiport || $port) {
$classname = 'WebService_' . $this->service . '_' . $port['name'];
} else {
$classname = 'WebService_' . $this->service;
}
if ($name) {
$classname = $name . '_' . $classname;
}
$classname = preg_replace('/[ .\-\(\)]+/', '_', $classname);
if (!class_exists($classname)) {
$proxy = $this->generateProxyCode($port, $classname);
require_once 'PayPal/SOAP/Client.php';
eval($proxy);
}
return new $classname;
}
function &_getComplexTypeForElement($name, $namespace)
{
$t = null;
if (isset($this->ns[$namespace]) &&
isset($this->elements[$this->ns[$namespace]][$name]['type'])) {
$type = $this->elements[$this->ns[$namespace]][$name]['type'];
$ns = $this->elements[$this->ns[$namespace]][$name]['namespace'];
if (isset($this->complexTypes[$ns][$type])) {
$t = $this->complexTypes[$ns][$type];
}
}
return $t;
}
function getComplexTypeNameForElement($name, $namespace)
{
$t = $this->_getComplexTypeForElement($name, $namespace);
if ($t) {
return $t['name'];
}
return null;
}
function getComplexTypeChildType($ns, $name, $child_ns, $child_name)
{
// is the type an element?
$t = $this->_getComplexTypeForElement($name, $ns);
if ($t) {
// no, get it from complex types directly
if (isset($t['elements'][$child_name]['type']))
return $t['elements'][$child_name]['type'];
}
return null;
}
function getSchemaType($type, $name, $type_namespace)
{
// see if it's a complex type so we can deal properly with
// SOAPENC:arrayType.
if ($name && $type) {
// XXX TODO:
// look up the name in the wsdl and validate the type.
foreach ($this->complexTypes as $ns => $types) {
if (array_key_exists($type, $types)) {
if (array_key_exists('type', $types[$type])) {
list($arraytype_ns, $arraytype, $array_depth) = isset($types[$type]['arrayType'])?
$this->_getDeepestArrayType($types[$type]['namespace'], $types[$type]['arrayType'])
: array($this->namespaces[$types[$type]['namespace']], null, 0);
return array($types[$type]['type'], $arraytype, $arraytype_ns, $array_depth);
}
if (array_key_exists('arrayType', $types[$type])) {
list($arraytype_ns, $arraytype, $array_depth) =
$this->_getDeepestArrayType($types[$type]['namespace'], $types[$type]['arrayType']);
return array('Array', $arraytype, $arraytype_ns, $array_depth);
}
if (array_key_exists('elements', $types[$type]) &&
array_key_exists($name, $types[$type]['elements'])) {
$type = $types[$type]['elements']['type'];
return array($type, null, $this->namespaces[$types[$type]['namespace']], null);
}
}
}
}
if ($type && $type_namespace) {
$arrayType = null;
// XXX TODO:
// this code currently handles only one way of encoding array types in wsdl
// need to do a generalized function to figure out complex types
$p = $this->ns[$type_namespace];
if ($p &&
array_key_exists($p, $this->complexTypes) &&
array_key_exists($type, $this->complexTypes[$p])) {
if ($arrayType = $this->complexTypes[$p][$type]['arrayType']) {
$type = 'Array';
} elseif ($this->complexTypes[$p][$type]['order']=='sequence' &&
array_key_exists('elements', $this->complexTypes[$p][$type])) {
reset($this->complexTypes[$p][$type]['elements']);
// assume an array
if (count($this->complexTypes[$p][$type]['elements']) == 1) {
$arg = current($this->complexTypes[$p][$type]['elements']);
$arrayType = $arg['type'];
$type = 'Array';
} else {
foreach ($this->complexTypes[$p][$type]['elements'] as $element) {
if ($element['name'] == $type) {
$arrayType = $element['type'];
$type = $element['type'];
}
}
}
} else {
$type = 'Struct';
}
return array($type, $arrayType, $type_namespace, null);
}
}
return array(null, null, null, null);
}
/**
* Recurse through the WSDL structure looking for the innermost
* array type of multi-dimensional arrays.
*
* Takes a namespace prefix and a type, which can be in the form
* 'type' or 'type[]', and returns the full namespace URI, the
* type of the most deeply nested array type found, and the number
* of levels of nesting.
*
* @access private
* @return mixed array or nothing
*/
function _getDeepestArrayType($nsPrefix, $arrayType)
{
static $trail = array();
$arrayType = ereg_replace('\[\]$', '', $arrayType);
// Protect against circular references
// XXX We really need to remove trail from this altogether (it's very inefficient and
// in the wrong place!) and put circular reference checking in when the WSDL info
// is generated in the first place
if (array_search($nsPrefix . ':' . $arrayType, $trail)) {
return array(null, null, -count($trail));
}
if (array_key_exists($nsPrefix, $this->complexTypes) &&
array_key_exists($arrayType, $this->complexTypes[$nsPrefix]) &&
array_key_exists('arrayType', $this->complexTypes[$nsPrefix][$arrayType])) {
$trail[] = $nsPrefix . ':' . $arrayType;
$result = $this->_getDeepestArrayType($this->complexTypes[$nsPrefix][$arrayType]['namespace'],
$this->complexTypes[$nsPrefix][$arrayType]['arrayType']);
return array($result[0], $result[1], $result[2] + 1);
}
return array($this->namespaces[$nsPrefix], $arrayType, 0);
}
}
class SOAP_WSDL_Cache extends SOAP_Base
{
// Cache settings
/**
* Use WSDL cache
*
* @var boolean
*/
var $_cacheUse = null;
/**
* Cache max lifetime (in seconds)
*
* @var int
*/
var $_cacheMaxAge = null;
/**
* SOAP_WSDL_Cache constructor
*
* @param boolean use caching
* @param int cache max lifetime (in seconds)
* @access public
*/
function SOAP_WSDL_Cache($cacheUse = WSDL_CACHE_USE,
$cacheMaxAge = WSDL_CACHE_MAX_AGE)
{
parent::SOAP_Base('WSDLCACHE');
$this->_cacheUse = $cacheUse;
$this->_cacheMaxAge = $cacheMaxAge;
}
/**
* _cacheDir
* return the path to the cache, if it doesn't exist, make it
*/
function _cacheDir()
{
$dir = getenv("WSDLCACHE");
if (!$dir) $dir = " ./wsdlcache";
@mkdir($dir, 0700);
return $dir;
}
/**
* Retrieves a file from cache if it exists, otherwise retreive from net,
* add to cache, and return from cache.
*
* @param string URL to WSDL
* @param array proxy parameters
* @param int expected MD5 of WSDL URL
* @access public
* @return string data
*/
function get($wsdl_fname, $proxy_params = array(), $cache = 0)
{
$cachename = $md5_wsdl = $file_data = '';
if ($this->_cacheUse) {
// Try to retrieve WSDL from cache
$cachename = SOAP_WSDL_Cache::_cacheDir() . '/' . md5($wsdl_fname). ' .wsdl';
if (file_exists($cachename)) {
$wf = fopen($cachename, 'rb');
if ($wf) {
// Reading cached file
$file_data = fread($wf, filesize($cachename));
$md5_wsdl = md5($file_data);
fclose($wf);
}
if ($cache) {
if ($cache != $md5_wsdl) {
return $this->_raiseSoapFault('WSDL Checksum error!', $wsdl_fname);
}
} else {
$fi = stat($cachename);
$cache_mtime = $fi[8];
//print cache_mtime, time()
if ($cache_mtime + $this->_cacheMaxAge < time()) {
// expired
$md5_wsdl = ''; // refetch
}
}
}
}
if (!$md5_wsdl) {
// Not cached or not using cache. Retrieve WSDL from URL
// is it a local file?
// this section should be replace by curl at some point
if (!preg_match('/^(https?|file):\/\//', $wsdl_fname)) {
if (!file_exists($wsdl_fname)) {
return $this->_raiseSoapFault("Unable to read local WSDL $wsdl_fname", $wsdl_fname);
}
if (function_exists('file_get_contents')) {
$file_data = file_get_contents($wsdl_fname);
} else {
$file_data = implode('',file($wsdl_fname));
}
} else {
$uri = explode('?', $wsdl_fname);
$rq =& new HTTP_Request($uri[0], $proxy_params);
// the user agent HTTP_Request uses fouls things up
if (isset($uri[1])) {
$rq->addRawQueryString($uri[1]);
}
if (isset($proxy_params['proxy_host']) &&
isset($proxy_params['proxy_port']) &&
isset($proxy_params['proxy_user']) &&
isset($proxy_params['proxy_pass'])) {
$rq->setProxy($proxy_params['proxy_host'], $proxy_params['proxy_port'],
$proxy_params['proxy_user'], $proxy_params['proxy_pass']);
} elseif (isset($proxy_params['proxy_host']) &&
isset($proxy_params['proxy_port'])) {
$rq->setProxy($proxy_params['proxy_host'], $proxy_params['proxy_port']);
}
$result = $rq->sendRequest();
if (PEAR::isError($result)) {
return $this->_raiseSoapFault("Unable to retrieve WSDL $wsdl_fname," . $rq->getResponseCode(), $wsdl_fname);
}
$file_data = $rq->getResponseBody();
if (!$file_data) {
return $this->_raiseSoapFault("Unable to retrieve WSDL $wsdl_fname, no http body", $wsdl_fname);
}
}
$md5_wsdl = md5($file_data);
if ($this->_cacheUse) {
$fp = fopen($cachename, "wb");
fwrite($fp, $file_data);
fclose($fp);
}
}
if ($this->_cacheUse && $cache && $cache != $md5_wsdl) {
return $this->_raiseSoapFault("WSDL Checksum error!", $wsdl_fname);
}
return $file_data;
}
}
class SOAP_WSDL_Parser extends SOAP_Base
{
/**
* Define internal arrays of bindings, ports, operations,
* messages, etc.
*/
var $currentMessage;
var $currentOperation;
var $currentPortType;
var $currentBinding;
var $currentPort;
/**
* Parser vars.
*/
var $cache;
var $tns = null;
var $soapns = array('soap');
var $uri = '';
var $wsdl = null;
var $status = '';
var $element_stack = array();
var $parentElement = '';
var $schema = '';
var $schemaStatus = '';
var $schema_stack = array();
var $currentComplexType;
var $schema_element_stack = array();
var $currentElement;
/**
* constructor
*/
function SOAP_WSDL_Parser($uri, &$wsdl, $docs = false)
{
parent::SOAP_Base('WSDLPARSER');
$this->cache =& new SOAP_WSDL_Cache($wsdl->cacheUse, $wsdl->cacheMaxAge);
$this->uri = $uri;
$this->wsdl = &$wsdl;
$this->docs = $docs;
$this->parse($uri);
}
function parse($uri)
{
// Check whether content has been read.
$fd = $this->cache->get($uri, $this->wsdl->proxy);
if (PEAR::isError($fd)) {
return $this->_raiseSoapFault($fd);
}
// Create an XML parser.
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_set_object($parser, $this);
xml_set_element_handler($parser, 'startElement', 'endElement');
if ($this->docs) {
xml_set_character_data_handler($parser, 'characterData');
}
if (!xml_parse($parser, $fd, true)) {
$detail = sprintf('XML error on line %d: %s',
xml_get_current_line_number($parser),
xml_error_string(xml_get_error_code($parser)));
return $this->_raiseSoapFault("Unable to parse WSDL file $uri\n$detail");
}
xml_parser_free($parser);
return true;
}
/**
* start-element handler
*/
function startElement($parser, $name, $attrs)
{
// Get element prefix.
$qname =& new QName($name);
if ($qname->ns) {
$ns = $qname->ns;
if ($ns && ((!$this->tns && strcasecmp($qname->name, 'definitions') == 0) || $ns == $this->tns)) {
$name = $qname->name;
}
}
$this->currentTag = $qname->name;
$this->parentElement = '';
$stack_size = count($this->element_stack);
if ($stack_size) {
$this->parentElement = $this->element_stack[$stack_size - 1];
}
$this->element_stack[] = $this->currentTag;
// Find status, register data.
switch ($this->status) {
case 'types':
// sect 2.2 wsdl:types
// children: xsd:schema
$parent_tag = '';
$stack_size = count($this->schema_stack);
if ($stack_size) {
$parent_tag = $this->schema_stack[$stack_size - 1];
}
switch ($qname->name) {
case 'schema':
// No parent should be in the stack.
if (!$parent_tag || $parent_tag == 'types') {
if (array_key_exists('targetNamespace', $attrs)) {
$this->schema = $this->wsdl->getNamespaceAttributeName($attrs['targetNamespace']);
} else {
$this->schema = $this->wsdl->getNamespaceAttributeName($this->wsdl->tns);
}
$this->wsdl->complexTypes[$this->schema] = array();
$this->wsdl->elements[$this->schema] = array();
}
break;
case 'complexType':
if ($parent_tag == 'schema') {
$this->currentComplexType = $attrs['name'];
if (!isset($attrs['namespace'])) {
$attrs['namespace'] = $this->schema;
}
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType] = $attrs;
if (array_key_exists('base', $attrs)) {
$qn =& new QName($attrs['base']);
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = $qn->name;
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['namespace'] = $qn->ns;
} else {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct';
}
$this->schemaStatus = 'complexType';
} else {
$this->wsdl->elements[$this->schema][$this->currentElement]['complex'] = true;
}
break;
case 'element':
if (isset($attrs['type'])) {
$qn =& new QName($attrs['type']);
$attrs['type'] = $qn->name;
if ($qn->ns && array_key_exists($qn->ns, $this->wsdl->namespaces)) {
$attrs['namespace'] = $qn->ns;
}
}
$parentElement = '';
$stack_size = count($this->schema_element_stack);
if ($stack_size > 0) {
$parentElement = $this->schema_element_stack[$stack_size - 1];
}
if (isset($attrs['ref'])) {
$qn =& new QName($attrs['ref']);
$this->currentElement = $qn->name;
} else {
$this->currentElement = $attrs['name'];
}
$this->schema_element_stack[] = $this->currentElement;
if (!isset($attrs['namespace'])) {
$attrs['namespace'] = $this->schema;
}
if ($parent_tag == 'schema') {
$this->wsdl->elements[$this->schema][$this->currentElement] = $attrs;
$this->wsdl->elements[$this->schema][$this->currentElement]['complex'] = false;
$this->schemaStatus = 'element';
} elseif ($this->currentComplexType) {
// we're inside a complexType
if ((isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order']) &&
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] == 'sequence')
&& $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] == 'Array') {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['arrayType'] = isset($attrs['type']) ? $attrs['type'] : null;
}
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['elements'][$this->currentElement] = $attrs;
} else {
$this->wsdl->elements[$this->schema][$parentElement]['elements'][$this->currentElement] = $attrs;
}
break;
case 'complexContent':
case 'simpleContent':
break;
case 'extension':
case 'restriction':
if ($this->schemaStatus == 'complexType') {
if (!empty($attrs['base'])) {
$qn =& new QName($attrs['base']);
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = $qn->name;
// Types that extend from other types aren't
// *of* those types. Reflect this by denoting
// which type they extend. I'm leaving the
// 'type' setting here since I'm not sure what
// removing it might break at the moment.
if ($qname->name == 'extension') {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['extends'] = $qn->name;
}
} else {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct';
}
}
break;
case 'sequence':
if ($this->schemaStatus == 'complexType') {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] = $qname->name;
if (!isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])) {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Array';
}
}
break;
case 'all':
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] = $qname->name;
if (!isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])) {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct';
}
break;
case 'choice':
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] = $qname->name;
if (!isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])) {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Array';
}
case 'attribute':
if ($this->schemaStatus == 'complexType') {
if (isset($attrs['name'])) {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['attribute'][$attrs['name']] = $attrs;
} else {
if (isset($attrs['ref'])) {
$q =& new QName($attrs['ref']);
foreach ($attrs as $k => $v) {
if ($k != 'ref' && strstr($k, $q->name)) {
$vq =& new QName($v);
if ($q->name == 'arrayType') {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType][$q->name] = $vq->name. $vq->arrayInfo;
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Array';
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['namespace'] = $vq->ns;
} else {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType][$q->name] = $vq->name;
}
}
}
}
}
}
break;
}
$this->schema_stack[] = $qname->name;
break;
case 'message':
// sect 2.3 wsdl:message child wsdl:part
switch ($qname->name) {
case 'part':
$qn = null;
if (isset($attrs['type'])) {
$qn =& new QName($attrs['type']);
} elseif (isset($attrs['element'])) {
$qn =& new QName($attrs['element']);
}
if ($qn) {
$attrs['type'] = $qn->name;
$attrs['namespace'] = $qn->ns;
}
$this->wsdl->messages[$this->currentMessage][$attrs['name']] = $attrs;
// error in wsdl
case 'documentation':
break;
default:
break;
}
break;
case 'portType':
// sect 2.4
switch ($qname->name) {
case 'operation':
// attributes: name
// children: wsdl:input wsdl:output wsdl:fault
$this->currentOperation = $attrs['name'];
$this->wsdl->portTypes[$this->currentPortType][$this->currentOperation] = $attrs;
break;
case 'input':
case 'output':
case 'fault':
// wsdl:input wsdl:output wsdl:fault
// attributes: name message parameterOrder(optional)
if ($this->currentOperation) {
if (isset($this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name])) {
$this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name] = array_merge($this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name], $attrs);
} else {
$this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name] = $attrs;
}
if (array_key_exists('message', $attrs)) {
$qn =& new QName($attrs['message']);
$this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name]['message'] = $qn->name;
$this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name]['namespace'] = $qn->ns;
}
}
break;
case 'documentation':
break;
default:
break;
}
break;
case 'binding':
$ns = $qname->ns ? $this->wsdl->namespaces[$qname->ns] : SCHEMA_WSDL;
switch ($ns) {
case SCHEMA_SOAP:
// this deals with wsdl section 3 soap binding
switch ($qname->name) {
case 'binding':
// sect 3.3
// soap:binding, attributes: transport(required), style(optional, default = document)
// if style is missing, it is assumed to be 'document'
if (!isset($attrs['style'])) {
$attrs['style'] = 'document';
}
$this->wsdl->bindings[$this->currentBinding] = array_merge($this->wsdl->bindings[$this->currentBinding], $attrs);
break;
case 'operation':
// sect 3.4
// soap:operation, attributes: soapAction(required), style(optional, default = soap:binding:style)
if (!isset($attrs['style'])) {
$attrs['style'] = $this->wsdl->bindings[$this->currentBinding]['style'];
}
if (isset($this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation])) {
$this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation] = array_merge($this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation], $attrs);
} else {
$this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation] = $attrs;
}
break;
case 'body':
// sect 3.5
// soap:body attributes:
// part - optional. listed parts must appear in body, missing means all parts appear in body
// use - required. encoded|literal
// encodingStyle - optional. space seperated list of encodings (uri's)
$this->wsdl->bindings[$this->currentBinding]
['operations'][$this->currentOperation][$this->opStatus] = $attrs;
break;
case 'fault':
// sect 3.6
// soap:fault attributes: name use encodingStyle namespace
$this->wsdl->bindings[$this->currentBinding]
['operations'][$this->currentOperation][$this->opStatus] = $attrs;
break;
case 'header':
// sect 3.7
// soap:header attributes: message part use encodingStyle namespace
$this->wsdl->bindings[$this->currentBinding]
['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs;
break;
case 'headerfault':
// sect 3.7
// soap:header attributes: message part use encodingStyle namespace
$header = count($this->wsdl->bindings[$this->currentBinding]
['operations'][$this->currentOperation][$this->opStatus]['headers'])-1;
$this->wsdl->bindings[$this->currentBinding]
['operations'][$this->currentOperation][$this->opStatus]['headers'][$header]['fault'] = $attrs;
break;
case 'documentation':
break;
default:
// error! not a valid element inside binding
break;
}
break;
case SCHEMA_WSDL:
// XXX verify correct namespace
// for now, default is the 'wsdl' namespace
// other possible namespaces include smtp, http, etc. for alternate bindings
switch ($qname->name) {
case 'operation':
// sect 2.5
// wsdl:operation attributes: name
$this->currentOperation = $attrs['name'];
break;
case 'output':
case 'input':
case 'fault':
// sect 2.5
// wsdl:input attributes: name
$this->opStatus = $qname->name;
break;
case 'documentation':
break;
default:
break;
}
break;
case SCHEMA_WSDL_HTTP:
switch ($qname->name) {
case 'binding':
// sect 4.4
// http:binding attributes: verb
// parent: wsdl:binding
$this->wsdl->bindings[$this->currentBinding] = array_merge($this->wsdl->bindings[$this->currentBinding], $attrs);
break;
case 'operation':
// sect 4.5
// http:operation attributes: location
// parent: wsdl:operation
$this->wsdl->bindings[$this->currentBinding]['operations']
[$this->currentOperation] = $attrs;
break;
case 'urlEncoded':
// sect 4.6
// http:urlEncoded attributes: location
// parent: wsdl:input wsdl:output etc.
$this->wsdl->bindings[$this->currentBinding]['operations'][$this->opStatus]
[$this->currentOperation]['uri'] = 'urlEncoded';
break;
case 'urlReplacement':
// sect 4.7
// http:urlReplacement attributes: location
// parent: wsdl:input wsdl:output etc.
$this->wsdl->bindings[$this->currentBinding]['operations'][$this->opStatus]
[$this->currentOperation]['uri'] = 'urlReplacement';
break;
case 'documentation':
break;
default:
// error
break;
}
case SCHEMA_MIME:
// sect 5
// all mime parts are children of wsdl:input, wsdl:output, etc.
// unsuported as of yet
switch ($qname->name) {
case 'content':
// sect 5.3 mime:content
// <mime:content part="nmtoken"? type="string"?/>
// part attribute only required if content is child of multipart related,
// it contains the name of the part
// type attribute contains the mime type
case 'multipartRelated':
// sect 5.4 mime:multipartRelated
case 'part':
case 'mimeXml':
// sect 5.6 mime:mimeXml
// <mime:mimeXml part="nmtoken"?/>
//
case 'documentation':
break;
default:
// error
break;
}
case SCHEMA_DIME:
// DIME is defined in:
// http://gotdotnet.com/team/xml_wsspecs/dime/WSDL-Extension-for-DIME.htm
// all DIME parts are children of wsdl:input, wsdl:output, etc.
// unsuported as of yet
switch ($qname->name) {
case 'message':
// sect 4.1 dime:message
// appears in binding section
$this->wsdl->bindings[$this->currentBinding]['dime'] = $attrs;
break;
default:
break;
}
default:
break;
}
break;
case 'service':
$ns = $qname->ns ? $this->wsdl->namespaces[$qname->ns] : SCHEMA_WSDL;
switch ($qname->name) {
case 'port':
// sect 2.6 wsdl:port attributes: name binding
$this->currentPort = $attrs['name'];
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort] = $attrs;
// XXX hack to deal with binding namespaces
$qn =& new QName($attrs['binding']);
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['binding'] = $qn->name;
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['namespace'] = $qn->ns;
break;
case 'address':
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['address'] = $attrs;
// what TYPE of port is it? SOAP or HTTP?
$ns = $qname->ns ? $this->wsdl->namespaces[$qname->ns] : SCHEMA_WSDL;
switch ($ns) {
case SCHEMA_WSDL_HTTP:
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['type']='http';
break;
case SCHEMA_SOAP:
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['type']='soap';
break;
default:
// Shouldn't happen, we'll assume SOAP.
$this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['type']='soap';
}
break;
case 'documentation':
break;
default:
break;
}
}
// Top level elements found under wsdl:definitions.
switch ($qname->name) {
case 'import':
// sect 2.1.1 wsdl:import attributes: namespace location
if ((isset($attrs['location']) || isset($attrs['schemaLocation'])) &&
!isset($this->wsdl->imports[$attrs['namespace']])) {
$uri = isset($attrs['location']) ? $attrs['location'] : $attrs['schemaLocation'];
$location = @parse_url($uri);
if (!isset($location['scheme'])) {
$base = @parse_url($this->uri);
$uri = $this->mergeUrl($base, $uri);
}
$this->wsdl->imports[$attrs['namespace']] = $attrs;
$import_parser_class = get_class($this);
$import_parser =& new $import_parser_class($uri, $this->wsdl, $this->docs);
if ($import_parser->fault) {
unset($this->wsdl->imports[$attrs['namespace']]);
return false;
}
$this->currentImport = $attrs['namespace'];
}
// Continue on to the 'types' case - lack of break; is
// intentional.
case 'types':
// sect 2.2 wsdl:types
$this->status = 'types';
break;
case 'schema':
// We can hit this at the top level if we've been asked to
// import an XSD file.
if (!empty($attrs['targetNamespace'])) {
$this->schema = $this->wsdl->getNamespaceAttributeName($attrs['targetNamespace']);
} else {
$this->schema = $this->wsdl->getNamespaceAttributeName($this->wsdl->tns);
}
$this->wsdl->complexTypes[$this->schema] = array();
$this->wsdl->elements[$this->schema] = array();
$this->schema_stack[] = $qname->name;
$this->status = 'types';
break;
case 'message':
// sect 2.3 wsdl:message attributes: name children:wsdl:part
$this->status = 'message';
if (isset($attrs['name'])) {
$this->currentMessage = $attrs['name'];
$this->wsdl->messages[$this->currentMessage] = array();
}
break;
case 'portType':
// sect 2.4 wsdl:portType
// attributes: name
// children: wsdl:operation
$this->status = 'portType';
$this->currentPortType = $attrs['name'];
$this->wsdl->portTypes[$this->currentPortType] = array();
break;
case 'binding':
// sect 2.5 wsdl:binding attributes: name type
// children: wsdl:operation soap:binding http:binding
if ($qname->ns && $qname->ns != $this->tns) {
break;
}
$this->status = 'binding';
$this->currentBinding = $attrs['name'];
$qn =& new QName($attrs['type']);
$this->wsdl->bindings[$this->currentBinding]['type'] = $qn->name;
$this->wsdl->bindings[$this->currentBinding]['namespace'] = $qn->ns;
break;
case 'service':
// sect 2.7 wsdl:service attributes: name children: ports
$this->currentService = $attrs['name'];
$this->wsdl->services[$this->currentService]['ports'] = array();
$this->status = 'service';
break;
case 'definitions':
// sec 2.1 wsdl:definitions
// attributes: name targetNamespace xmlns:*
// children: wsdl:import wsdl:types wsdl:message wsdl:portType wsdl:binding wsdl:service
$this->wsdl->definition = $attrs;
foreach ($attrs as $key => $value) {
if (strstr($key, 'xmlns:') !== false) {
$qn =& new QName($key);
// XXX need to refactor ns handling.
$this->wsdl->namespaces[$qn->name] = $value;
$this->wsdl->ns[$value] = $qn->name;
if ($key == 'targetNamespace' ||
strcasecmp($value,SOAP_SCHEMA) == 0) {
$this->soapns[] = $qn->name;
} else {
if (in_array($value, $this->_XMLSchema)) {
$this->wsdl->xsd = $value;
}
}
}
}
if (isset($ns) && $ns) {
$namespace = 'xmlns:' . $ns;
if (!$this->wsdl->definition[$namespace]) {
return $this->_raiseSoapFault("parse error, no namespace for $namespace", $this->uri);
}
$this->tns = $ns;
}
break;
}
}
/**
* end-element handler.
*/
function endElement($parser, $name)
{
$stacksize = count($this->element_stack);
if ($stacksize) {
if ($this->element_stack[$stacksize - 1] == 'definitions') {
$this->status = '';
}
array_pop($this->element_stack);
}
if (stristr($name, 'schema')) {
array_pop($this->schema_stack);
$this->schema = '';
}
if ($this->schema) {
array_pop($this->schema_stack);
if (count($this->schema_stack) <= 1) {
/* Correct the type for sequences with multiple
* elements. */
if (isset($this->currentComplexType) && isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])
&& $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] == 'Array'
&& array_key_exists('elements', $this->wsdl->complexTypes[$this->schema][$this->currentComplexType])
&& count($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['elements']) > 1) {
$this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct';
}
}
if (stristr($name, 'complexType')) {
$this->currentComplexType = '';
if (count($this->schema_element_stack)) {
$this->currentElement = array_pop($this->schema_element_stack);
} else {
$this->currentElement = '';
}
} elseif (stristr($name, 'element')) {
if (count($this->schema_element_stack)) {
$this->currentElement = array_pop($this->schema_element_stack);
} else {
$this->currentElement = '';
}
}
}
}
/**
* Element content handler.
*/
function characterData($parser, $data)
{
// Store the documentation in the WSDL file.
if ($this->currentTag == 'documentation') {
$data = trim(preg_replace('/\s+/', ' ', $data));
if (!strlen($data)) {
return;
}
switch ($this->status) {
case 'service':
$ptr =& $this->wsdl->services[$this->currentService];
break;
case 'portType':
$ptr =& $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation];
break;
case 'binding':
$ptr =& $this->wsdl->bindings[$this->currentBinding];
break;
case 'message':
$ptr =& $this->wsdl->messages[$this->currentMessage];
break;
case 'operation':
break;
case 'types':
if (isset($this->currentComplexType) &&
isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType])) {
if ($this->currentElement) {
$ptr =& $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['elements'][$this->currentElement];
} else {
$ptr =& $this->wsdl->complexTypes[$this->schema][$this->currentComplexType];
}
}
break;
}
if (isset($ptr)) {
if (!isset($ptr['documentation'])) {
$ptr['documentation'] = '';
} else {
$ptr['documentation'] .= ' ';
}
$ptr['documentation'] .= $data;
}
}
}
/**
* $parsed is an array returned by parse_url().
*
* @access private
*/
function mergeUrl($parsed, $path)
{
if (!is_array($parsed)) {
return false;
}
$uri = '';
if (!empty($parsed['scheme'])) {
$sep = (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://');
$uri = $parsed['scheme'] . $sep;
}
if (isset($parsed['pass'])) {
$uri .= "$parsed[user]:$parsed[pass]@";
} elseif (isset($parsed['user'])) {
$uri .= "$parsed[user]@";
}
if (isset($parsed['host'])) {
$uri .= $parsed['host'];
}
if (isset($parsed['port'])) {
$uri .= ":$parsed[port]";
}
if ($path[0] != '/' && isset($parsed['path'])) {
if ($parsed['path'][strlen($parsed['path']) - 1] != '/') {
$path = dirname($parsed['path']) . '/' . $path;
} else {
$path = $parsed['path'] . $path;
}
$path = $this->_normalize($path);
}
$sep = $path[0] == '/' ? '' : '/';
$uri .= $sep . $path;
return $uri;
}
function _normalize($path_str)
{
$pwd = '';
$strArr = preg_split('/(\/)/', $path_str, -1, PREG_SPLIT_NO_EMPTY);
$pwdArr = '';
$j = 0;
for ($i = 0; $i < count($strArr); $i++) {
if ($strArr[$i] != ' ..') {
if ($strArr[$i] != ' .') {
$pwdArr[$j] = $strArr[$i];
$j++;
}
} else {
array_pop($pwdArr);
$j--;
}
}
$pStr = implode('/', $pwdArr);
$pwd = (strlen($pStr) > 0) ? ('/' . $pStr) : '/';
return $pwd;
}
}
/**
* Parses the types and methods used in web service objects into the internal
* data structures used by SOAP_WSDL.
*
* Assumes the SOAP_WSDL class is unpopulated to start with.
*
* @author Chris Coe <info@intelligentstreaming.com>
*/
class SOAP_WSDL_ObjectParser extends SOAP_Base
{
/**
* Target namespace for the WSDL document will have the following
* prefix.
*/
var $tnsPrefix = 'tns';
/**
* Reference to the SOAP_WSDL object to populate.
*/
var $wsdl = null;
/** Constructor
*
* @param $objects Reference to the object or array of objects to parse
* @param $wsdl Reference to the SOAP_WSDL object to populate
* @param $targetNamespace The target namespace of schema types etc.
* @param $service_name Name of the WSDL <service>
* @param $service_desc Optional description of the WSDL <service>
*/
function SOAP_WSDL_ObjectParser(&$objects, &$wsdl, $targetNamespace, $service_name, $service_desc = '')
{
parent::SOAP_Base('WSDLOBJECTPARSER');
$this->wsdl = &$wsdl;
// Set up the SOAP_WSDL object
$this->_initialise($service_name);
// Parse each web service object
$wsdl_ref = (is_array($objects)? $objects : array(&$objects));
foreach ($wsdl_ref as $ref_item) {
if (!is_object($ref_item))
return $this->_raiseSoapFault('Invalid web service object passed to object parser', 'urn:' . get_class($object));
if ($this->_parse($ref_item, $targetNamespace, $service_name) != true)
break;
}
// Build bindings from abstract data.
if ($this->fault == null) {
$this->_generateBindingsAndServices($targetNamespace, $service_name, $service_desc);
}
}
/**
* Initialise the SOAP_WSDL tree (destructive).
*
* If the object has already been initialised, the only effect
* will be to change the tns namespace to the new service name.
*
* @param $service_name Name of the WSDL <service>
* @access private
*/
function _initialise($service_name)
{
// Set up the basic namespaces that all WSDL definitions use.
$this->wsdl->namespaces['wsdl'] = SCHEMA_WSDL; // WSDL language
$this->wsdl->namespaces['soap'] = SCHEMA_SOAP; // WSDL SOAP bindings
$this->wsdl->namespaces[$this->tnsPrefix] = 'urn:' . $service_name; // Target namespace
$this->wsdl->namespaces['xsd'] = array_search('xsd', $this->_namespaces); // XML Schema
$this->wsdl->namespaces['SOAP-ENC'] = array_search('SOAP-ENC', $this->_namespaces); // SOAP types
// XXX Refactor $namespace/$ns for Shane :-)
unset($this->wsdl->ns['urn:' . $service_name]);
$this->wsdl->ns += array_flip($this->wsdl->namespaces);
// Imports are not implemented in WSDL generation from classes.
// *** <wsdl:import> ***
}
/**
* Parser - takes a single object to add to tree
* (non-destructive).
*
* @param $object Reference to the object to parse
* @param $service_name Name of the WSDL <service>
* @access private
*/
function _parse(&$object, $schemaNamespace, $service_name)
{
// Create namespace prefix for the schema
// XXX not very elegant :-(
list($schPrefix, $foo) = $this->_getTypeNs('{' . $schemaNamespace.'}');
unset($foo);
// Parse all the types defined by the object in whatever
// schema language we are using (currently __typedef arrays)
// *** <wsdl:types> ***
foreach ($object->__typedef as $typeName => $typeValue) {
// Get/create namespace definition
list($nsPrefix, $typeName) = $this->_getTypeNs($typeName);
// Create type definition
$this->wsdl->complexTypes[$schPrefix][$typeName] = array('name' => $typeName);
$thisType =& $this->wsdl->complexTypes[$schPrefix][$typeName];
// According to Dmitri's documentation, __typedef comes in two
// flavors:
// Array = array(array("item" => "value"))
// Struct = array("item1" => "value1", "item2" => "value2", ...)
if (is_array($typeValue)) {
reset($typeValue);
if (is_array(current($typeValue)) && count($typeValue) == 1
&& count(current($typeValue)) == 1) {
// It's an array
$thisType['type'] = 'Array';
reset(current($typeValue));
list($nsPrefix, $typeName) = $this->_getTypeNs(current(current($typeValue)));
$thisType['namespace'] = $nsPrefix;
$thisType['arrayType'] = $typeName . '[]';
} elseif (!is_array(current($typeValue))) {
// It's a struct
$thisType['type'] = 'Struct';
$thisType['order'] = 'all';
$thisType['namespace'] = $nsPrefix;
$thisType['elements'] = array();
foreach ($typeValue as $elementName => $elementType) {
list($nsPrefix, $typeName) = $this->_getTypeNs($elementType);
$thisType['elements'][$elementName]['name'] = $elementName;
$thisType['elements'][$elementName]['type'] = $typeName;
$thisType['elements'][$elementName]['namespace'] = $nsPrefix;
}
} else {
// It's erroneous
return $this->_raiseSoapFault("The type definition for $nsPrefix:$typeName is invalid.", 'urn:' . get_class($object));
}
} else {
// It's erroneous
return $this->_raiseSoapFault("The type definition for $nsPrefix:$typeName is invalid.", 'urn:' . get_class($object));
}
}
// Create an empty element array with the target namespace
// prefix, to match the results of WSDL parsing.
$this->wsdl->elements[$schPrefix] = array();
// Populate tree with message information
// *** <wsdl:message> ***
foreach ($object->__dispatch_map as $operationName => $messages) {
foreach ($messages as $messageType => $messageParts) {
unset($thisMessage);
switch ($messageType) {
case 'in':
$this->wsdl->messages[$operationName . 'Request'] = array();
$thisMessage =& $this->wsdl->messages[$operationName . 'Request'];
break;
case 'out':
$this->wsdl->messages[$operationName . 'Response'] = array();
$thisMessage =& $this->wsdl->messages[$operationName . 'Response'];
break;
case 'alias':
// Do nothing
break;
default:
// Error condition
break;
}
if (isset($thisMessage)) {
foreach ($messageParts as $partName => $partType) {
list ($nsPrefix, $typeName) = $this->_getTypeNs($partType);
$thisMessage[$partName] = array(
'name' => $partName,
'type' => $typeName,
'namespace' => $nsPrefix
);
}
}
}
}
// Populate tree with portType information
// XXX Current implementation only supports one portType that
// encompasses all of the operations available.
// *** <wsdl:portType> ***
if (!isset($this->wsdl->portTypes[$service_name . 'Port'])) {
$this->wsdl->portTypes[$service_name . 'Port'] = array();
}
$thisPortType =& $this->wsdl->portTypes[$service_name . 'Port'];
foreach ($object->__dispatch_map as $operationName => $messages) {
$thisPortType[$operationName] = array('name' => $operationName);
foreach ($messages as $messageType => $messageParts) {
switch ($messageType) {
case 'in':
$thisPortType[$operationName]['input'] = array(
'message' => $operationName . 'Request',
'namespace' => $this->tnsPrefix);
break;
case 'out':
$thisPortType[$operationName]['output'] = array(
'message' => $operationName . 'Response',
'namespace' => $this->tnsPrefix);
break;
}
}
}
return true;
}
/**
* Take all the abstract WSDL data and build concrete bindings and
* services (destructive).
*
* XXX Current implementation discards $service_desc.
*
* @param $schemaNamespace Namespace for types etc.
* @param $service_name Name of the WSDL <service>
* @param $service_desc Optional description of the WSDL <service>
* @access private
*/
function _generateBindingsAndServices($schemaNamespace, $service_name, $service_desc = '')
{
// Populate tree with bindings information
// XXX Current implementation only supports one binding that
// matches the single portType and all of its operations.
// XXX Is this the correct use of $schemaNamespace here?
// *** <wsdl:binding> ***
$this->wsdl->bindings[$service_name . 'Binding'] = array(
'type' => $service_name . 'Port',
'namespace' => $this->tnsPrefix,
'style' => 'rpc',
'transport' => SCHEMA_SOAP_HTTP,
'operations' => array());
$thisBinding =& $this->wsdl->bindings[$service_name . 'Binding'];
foreach ($this->wsdl->portTypes[$service_name . 'Port'] as $operationName => $operationData) {
$thisBinding['operations'][$operationName] = array(
'soapAction' => $schemaNamespace . '#' . $operationName,
'style' => $thisBinding['style']);
foreach (array('input', 'output') as $messageType)
if (isset($operationData[$messageType])) {
$thisBinding['operations'][$operationName][$messageType] = array(
'use' => 'encoded',
'namespace' => $schemaNamespace,
'encodingStyle' => SOAP_SCHEMA_ENCODING);
}
}
// Populate tree with service information
// XXX Current implementation supports one service which groups
// all of the ports together, one port per binding
// XXX What about https?
// *** <wsdl:service> ***
$this->wsdl->services[$service_name . 'Service'] = array('ports' => array());
$thisService =& $this->wsdl->services[$service_name . 'Service']['ports'];
foreach ($this->wsdl->bindings as $bindingName => $bindingData) {
$thisService[$bindingData['type']] = array(
'name' => $bindingData['type'],
'binding' => $bindingName,
'namespace' => $this->tnsPrefix,
'address' => array('location' =>
'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] .
(isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '')),
'type' => 'soap');
}
// Set service
$this->wsdl->set_service($service_name . 'Service');
$this->wsdl->uri = $this->wsdl->namespaces[$this->tnsPrefix];
// Create WSDL definition
// *** <wsdl:definitions> ***
$this->wsdl->definition = array(
'name' => $service_name,
'targetNamespace' => $this->wsdl->namespaces[$this->tnsPrefix],
'xmlns' => SCHEMA_WSDL);
foreach ($this->wsdl->namespaces as $nsPrefix => $namespace) {
$this->wsdl->definition['xmlns:' . $nsPrefix] = $namespace;
}
}
/**
* This function is adapted from Dmitri V's implementation of
* DISCO/WSDL generation. It separates namespace from type name in
* a __typedef key and creates a new namespace entry in the WSDL
* structure if the namespace has not been used before. The
* namespace prefix and type name are returned. If no namespace is
* specified, xsd is assumed.
*
* We will not need this function anymore once __typedef is
* eliminated.
*/
function _getTypeNs($type)
{
preg_match_all("'\{(.*)\}'sm", $type, $m);
if (isset($m[1][0]) && $m[1][0] != '') {
if (!array_key_exists($m[1][0], $this->wsdl->ns)) {
$ns_pref = 'ns' . count($this->wsdl->namespaces);
$this->wsdl->ns[$m[1][0]] = $ns_pref;
$this->wsdl->namespaces[$ns_pref] = $m[1][0];
}
$typens = $this->wsdl->ns[$m[1][0]];
$type = ereg_replace($m[0][0], '', $type);
} else {
$typens = 'xsd';
}
return array($typens, $type);
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/WSDL.php | PHP | asf20 | 88,088 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: Value.php,v 1.1 2011/09/18 05:16:03 iling Exp $
//
require_once 'PayPal/SOAP/Base.php';
/**
* SOAP::Value
*
* This class converts values between PHP and SOAP.
*
* Originally based on SOAPx4 by Dietrich Ayala
* http://dietrich.ganx4.com/soapx4
*
* @access public
* @package SOAP::Client
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
* @author Dietrich Ayala <dietrich@ganx4.com> Original Author
*/
class SOAP_Value
{
/**
*
*
* @var string
*/
var $value = null;
/**
*
* @var string
*/
var $name = '';
/**
*
* @var string
*/
var $type = '';
/**
* Namespace
*
* @var string
*/
var $namespace = '';
var $type_namespace = '';
var $attributes = array();
/**
*
* @var string
*/
var $arrayType = '';
var $options = array();
var $nqn;
var $tqn;
/**
* Constructor.
*
* @param string $name name of the soap-value {namespace}name
* @param mixed $type soap value {namespace}type, if not set an automatic
* @param mixed $value value to set
* @param array $attributes (optional) Attributes.
*/
function SOAP_Value($name = '', $type = false, $value = null, $attributes = array())
{
// Detect type if not passed.
$this->nqn =& new QName($name);
$this->name = $this->nqn->name;
$this->namespace = $this->nqn->namespace;
$this->tqn =& new QName($type);
$this->type = $this->tqn->name;
$this->type_prefix = $this->tqn->ns;
$this->type_namespace = $this->tqn->namespace;
$this->value =& $value;
$this->attributes = $attributes;
}
/**
* Serialize.
*
* @param SOAP_Base &$serializer A SOAP_Base instance or subclass to serialize with.
*
* @return string XML representation of $this.
*/
function serialize(&$serializer)
{
return $serializer->_serializeValue($this->value, $this->name, $this->type, $this->namespace, $this->type_namespace, $this->options, $this->attributes, $this->arrayType);
}
}
/**
* SOAP::Header
*
* This class converts values between PHP and SOAP. It is a simple
* wrapper around SOAP_Value, adding support for SOAP actor and
* mustunderstand parameters.
*
* Originally based on SOAPx4 by Dietrich Ayala
* http://dietrich.ganx4.com/soapx4
*
* @access public
* @package SOAP::Header
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
* @author Dietrich Ayala <dietrich@ganx4.com> Original Author
*/
class SOAP_Header extends SOAP_Value
{
/**
* Constructor
*
* @param string $name name of the soap-value {namespace}name
* @param mixed $type soap value {namespace}type, if not set an automatic
* @param mixed $value value to set
* @param integer $mustunderstand Zero or one.
* @param mixed $attributes (optional) Attributes.
*/
function SOAP_Header($name = '', $type, $value,
$mustunderstand = 0,
$attributes = array())
{
if (!is_array($attributes)) {
$actor = $attributes;
$attributes = array();
}
parent::SOAP_Value($name, $type, $value, $attributes);
if (isset($actor)) {
$this->attributes['SOAP-ENV:actor'] = $actor;
} elseif (!isset($this->attributes['SOAP-ENV:actor'])) {
$this->attributes['SOAP-ENV:actor'] = 'http://schemas.xmlsoap.org/soap/actor/next';
}
$this->attributes['SOAP-ENV:mustUnderstand'] = (int)$mustunderstand;
}
}
/**
* SOAP::Attachment
* this class converts values between PHP and SOAP
* it handles Mime attachements per W3C Note on Soap Attachements at
* http://www.w3.org/TR/SOAP-attachments
*
*
* @access public
* @package SOAP::Attachment
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
*/
class SOAP_Attachment extends SOAP_Value
{
/**
* Constructor
*
* @param string name of the soap-value <value_name>
* @param mixed soap header value
* @param string namespace
*/
function SOAP_Attachment($name = '', $type = 'application/octet-stream',
$filename, $file = null)
{
global $SOAP_options;
if (!isset($SOAP_options['Mime'])) {
return PEAR::raiseError('Mail_mime is not installed, unable to support SOAP Attachements');
}
parent::SOAP_Value($name, null, null);
$filedata = ($file === null) ? $this->_file2str($filename) : $file;
$filename = basename($filename);
if (PEAR::isError($filedata)) {
return $filedata;
}
$cid = md5(uniqid(time()));
$this->attributes['href'] = 'cid:'.$cid;
$this->options['attachment'] = array(
'body' => $filedata,
'disposition' => $filename,
'content_type' => $type,
'encoding' => 'base64',
'cid' => $cid
);
}
/**
* Returns the contents of the given file name as string
* @param string $file_name
* @return string
* @acces private
*/
function &_file2str($file_name)
{
if (!is_readable($file_name)) {
return PEAR::raiseError('File is not readable ' . $file_name);
}
if (!$fd = fopen($file_name, 'rb')) {
return PEAR::raiseError('Could not open ' . $file_name);
}
$cont = fread($fd, filesize($file_name));
fclose($fd);
return $cont;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Value.php | PHP | asf20 | 7,309 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: dateTime.php,v 1.1 2011/09/18 05:16:13 iling Exp $
//
class SOAP_Type_dateTime
{
var $ereg_iso8601 = '(-?[0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]*)?(Z|[+\-][0-9]{4}|[+\-][0-9]{2}:[0-9]{2})?';
#"(-?[0-9]{4})-". // centuries & years CCYY-
#"([0-9]{2})-". // months MM-
#"([0-9]{2})". // days DD
#"T". // separator T
#"([0-9]{2}):". // hours hh:
#"([0-9]{2}):". // minutes mm:
#"([0-9]{2})(\.[0-9]*)?". // seconds ss.ss...
#"(Z|[+\-][0-9]{4}|[+\-][0-9]{2}:[0-9]{2})?"; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's
# if no 8th reg (Z) assumes UTC
var $timestamp = -1;
function SOAP_Type_dateTime($date = -1)
{
if ($date == -1) $date = time();
if (gettype($date) == 'integer') {
$this->timestamp = $date;
} else {
$this->timestamp = $this->toUnixtime($date);
}
}
function toSOAP($date = NULL)
{
return $this->toUTC($date);
}
function toString($timestamp = 0)
{
if (!$timestamp) $timestamp = $this->timestamp;
if ($timestamp < 0) return 0;
return date('Y-m-d\TH:i:sO',$timestamp);
}
function _split($datestr)
{
if (!$datestr)
$datestr = $this->toString();
else if (gettype($datestr) == 'integer')
$datestr = $this->toString($datestr);
if (ereg($this->ereg_iso8601,$datestr,$regs)) {
if ($regs[8] != '' && $regs[8] != 'Z') {
$op = substr($regs[8],0,1);
$h = substr($regs[8],1,2);
if (strstr($regs[8],':')) {
$m = substr($regs[8],4,2);
} else {
$m = substr($regs[8],3,2);
}
if ($op == '+') {
$regs[4] = $regs[4] - $h;
if ($regs[4] < 0) $regs[4] += 24;
$regs[5] = $regs[5] - $m;
if ($regs[5] < 0) $regs[5] += 60;
} else {
$regs[4] = $regs[4] + $h;
if ($regs[4] > 23) $regs[4] -= 24;
$regs[5] = $regs[5] + $m;
if ($regs[5] > 59) $regs[5] -= 60;
}
}
return $regs;
}
return FALSE;
}
function toUTC($datestr = NULL)
{
$regs = $this->_split($datestr);
if ($regs) {
return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]);
}
return '';
}
function toUnixtime($datestr = NULL)
{
$regs = $this->_split($datestr);
if ($regs) {
return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z");
}
return -1;
}
function compare($date1, $date2 = NULL)
{
if ($date2 === null) {
$date2 = $date1;
$date1 = $this->timestamp;
}
if (!is_numeric($date1))
$date1 = $this->toUnixtime($date1);
if (!is_numeric($date2))
$date2 = $this->toUnixtime($date2);
if ($date1 != -1 && $date2 != -1) return $date1 - $date2;
return -1;
}
function _test($orig = '2001-04-25T09:31:41-0700')
{
$utc = $this->toUTC($orig);
$ts1 = $this->toUnixtime($orig);
$ts2 = $this->toUnixtime($utc);
$b1 = $this->toString($ts1);
$b2 = $this->toString($ts2);
print "orig: $orig\n";
print "orig toUTC: $utc\n";
print "orig ts: $ts1\n";
print "utc ts: $ts2\n";
print "orig ts back: $b1\n";
print "utc ts back: $b2\n";
if ($b1 != $orig || $b2 != $orig) {
echo "Error in iso8601 conversions\n";
} else {
echo "dateTime OK\n";
}
}
}
# these should all match
#$d = new SOAP_Type_dateTime();
#echo $d->compare("2001-04-25T20:31:41Z","2001-04-25T20:31:41Z")."\n";
#echo $d->compare("2001-04-25T20:31:41Z","2001-04-25T12:31:41-0800")."\n";
#echo $d->compare("2001-04-25T20:31:41Z","2001-04-25T12:31:41-08:00")."\n";
?> | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Type/dateTime.php | PHP | asf20 | 5,624 |
<?php
/*
http://www.w3.org/TR/xmlschema-2/
[Definition:] duration represents a duration of time. The value space of
duration is a six-dimensional space where the coordinates designate the
Gregorian year, month, day, hour, minute, and second components
defined in 5.5.3.2 of [ISO 8601], respectively. These components are
ordered in their significance by their order of appearance i.e. as year,
month, day, hour, minute, and second.
3.2.6.1 Lexical representation
The lexical representation for duration is the [ISO 8601] extended
format PnYn MnDTnH nMnS, where nY represents the number of
years, nM the number of months, nD the number of days, 'T' is the
date/time separator, nH the number of hours, nM the number of
minutes and nS the number of seconds. The number of seconds
can include decimal digits to arbitrary precision.
The values of the Year, Month, Day, Hour and Minutes components
are not restricted but allow an arbitrary integer. Similarly, the
value of the Seconds component allows an arbitrary decimal.
Thus, the lexical representation of duration does not follow the
alternative format of 5.5.3.2.1 of [ISO 8601].
An optional preceding minus sign ('-') is allowed, to indicate a
negative duration. If the sign is omitted a positive duration is
indicated. See also ISO 8601 Date and Time Formats (D).
For example, to indicate a duration of 1 year, 2 months, 3 days,
10 hours, and 30 minutes, one would write: P1Y2M3DT10H30M.
One could also indicate a duration of minus 120 days as: -P120D.
Reduced precision and truncated representations of this format
are allowed provided they conform to the following:
If the number of years, months, days, hours, minutes, or seconds
in any expression equals zero, the number and its corresponding
designator *may* be omitted. However, at least one number and
its designator *must* be present.
The seconds part *may* have a decimal fraction.
The designator 'T' shall be absent if all of the time items are absent.
The designator 'P' must always be present.
For example, P1347Y, P1347M and P1Y2MT2H are all allowed; P0Y1347M
and P0Y1347M0D are allowed. P-1347M is not allowed although -P1347M
is allowed. P1Y2MT is not allowed.
*/
/* this is only an aproximation of duration, more work still to do.
see above schema url for more info on duration
TODO: figure out best aproximation for year and month conversion to seconds
*/
$ereg_duration = '(-)?P([0-9]+Y)?([0-9]+M)?([0-9]+D)?T?([0-9]+H)?([0-9]+M)?([0-9]+S)?';
class SOAP_Type_duration
{
// format PnYnMnDTnHnMnS
function unix_to_duration($seconds) {
return SOAP_Type_duration::getduration($seconds);
}
function mod($a, $b, &$d, &$r) {
$d = floor( $a / $b );
$r = $a % $b;
}
function getduration($seconds) {
$neg = '';
if ($seconds < 0) {
$neg = '-';
$seconds = $seconds * -1;
}
$_mi = 60;
$_h = $_mi * 60;
$_d = $_h * 24;
// XXX how do we properly handle month and year values?
$_m = $_d * 30;
$_y = $_d * 365;
SOAP_Type_duration::mod($seconds, $_y, $y, $seconds);
SOAP_Type_duration::mod($seconds, $_m, $m, $seconds);
SOAP_Type_duration::mod($seconds, $_d, $d, $seconds);
SOAP_Type_duration::mod($seconds, $_h, $h, $seconds);
SOAP_Type_duration::mod($seconds, $_mi, $mi, $s);
$duration = $neg.'P';
if ($y) $duration .= $y.'Y';
if ($m) $duration .= $m.'M';
if ($d) $duration .= $d.'D';
if ($h || $mi || $s) $duration .='T';
if ($h) $duration .= $h.'H';
if ($mi) $duration .= $mi.'M';
if ($s) $duration .= $s.'S';
if ($duration == 'P' || $duration == '-P') $duration = 'PT0S';
return $duration;
}
function mkduration($n, $Y, $Mo, $D, $H, $Mi, $S) {
$_mi = 60;
$_h = $_mi * 60;
$_d = $_h * 24;
// XXX how do we properly handle month and year values?
$_m = $_d * 30;
$_y = $_d * 365;
$sec = $Y * $_y + $Mo * $_m + $D * $_d + $H * $_h + $Mi * $_mi + $S;
if ($n == '-') $sec = $sec * -1;
return $sec;
}
function duration_to_unix($duration) {
global $ereg_duration;
if (ereg($ereg_duration,$duration,$regs)) {
return SOAP_Type_duration::mkduration($regs[1], $regs[2], $regs[3], $regs[4], $regs[5], $regs[6], $regs[7]);
}
return FALSE;
}
function is_duration($duration) {
global $ereg_duration;
return ereg($ereg_duration,$duration,$regs);
}
function _test($time) {
if (SOAP_Type_duration::is_duration($time)) {
$t = SOAP_Type_duration::duration_to_unix($time);
echo "Duration: $time is ".$t." seconds\n";
} else {
$t = SOAP_Type_duration::unix_to_duration($time);
echo "Seconds: $time is ".$t." duration\n";
}
return $t;
}
function add($d1, $d2) {
$s1 = SOAP_Type_duration::duration_to_unix($d1);
$s2 = SOAP_Type_duration::duration_to_unix($d2);
return SOAP_Type_duration::unix_to_duration($s1 + $s2);
}
function subtract($d1, $d2) {
$s1 = SOAP_Type_duration::duration_to_unix($d1);
$s2 = SOAP_Type_duration::duration_to_unix($d2);
return SOAP_Type_duration::unix_to_duration($s1 - $s2);
}
}
/* tests */
$t = SOAP_Type_duration::_test('P1Y2M3DT10H30M');
SOAP_Type_duration::_test($t);
$t = SOAP_Type_duration::_test('-P120D');
SOAP_Type_duration::_test($t);
// duration since 1970
$t = SOAP_Type_duration::_test(time());
SOAP_Type_duration::_test($t);
print "Add should be PT0S: ".SOAP_Type_duration::add('-P120D','P4M')."\n";
print "Subtract should be PT0S: ".SOAP_Type_duration::subtract('P120D','P4M')."\n";
?> | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Type/duration.php | PHP | asf20 | 6,058 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: hexBinary.php,v 1.1 2011/09/18 05:16:13 iling Exp $
//
class SOAP_Type_hexBinary
{
function to_bin($value)
{
$len = strlen($value);
return pack('H' . $len, $value);
}
function to_hex($value)
{
return bin2hex($value);
}
function is_hexbin($value)
{
# first see if there are any invalid chars
$l = strlen($value);
if ($l < 1 || strspn($value, '0123456789ABCDEFabcdef') != $l) return FALSE;
$bin = SOAP_Type_hexBinary::to_bin($value);
$hex = SOAP_Type_hexBinary::to_hex($bin);
return strcasecmp($value, $hex) == 0;
}
}
?> | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Type/hexBinary.php | PHP | asf20 | 1,910 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: Base.php,v 1.1 2011/09/18 05:16:03 iling Exp $
//
/*
SOAP_OBJECT_STRUCT makes pear::soap use objects for soap structures
rather than arrays. This has been done to provide a closer match to php-soap.
If the old behaviour is needed, set to false. The old behaviour is deprecated.
*/
$GLOBALS['SOAP_OBJECT_STRUCT'] = true;
/*
SOAP_RAW_CONVERT makes pear::soap attempt to determine what SOAP type
a php string COULD be. This may result in slightly better interoperability when
you are not using WSDL, and are being lazy and not using SOAP_Value to define
types for your values.
*/
$GLOBALS['SOAP_RAW_CONVERT'] = false;
require_once 'PEAR.php';
require_once 'PayPal/SOAP/Type/dateTime.php';
require_once 'PayPal/SOAP/Type/hexBinary.php';
// optional features
$GLOBALS['SOAP_options'] = array();
@include_once 'Mail/mimePart.php';
@include_once 'Mail/mimeDecode.php';
if (class_exists('Mail_mimePart')) {
$GLOBALS['SOAP_options']['Mime'] = 1;
define('MAIL_MIMEPART_CRLF', "\r\n");
}
@include_once 'Net/DIME.php';
if (class_exists('Net_DIME_Message')) {
$GLOBALS['SOAP_options']['DIME'] = 1;
}
/**
* Enable debugging informations?
*
* @name $SOAP_DEBUG
* @global $GLOBALS['SOAP_DEBUG']
*/
$GLOBALS['SOAP_DEBUG'] = false;
if (!function_exists('version_compare') ||
version_compare(phpversion(), '4.1', '<')) {
die("requires PHP 4.1 or higher\n");
}
if (version_compare(phpversion(), '4.1', '>=') &&
version_compare(phpversion(), '4.2', '<')) {
define('FLOAT', 'double');
} else {
define('FLOAT', 'float');
}
if (!defined('INF')) {
define('INF', 1.8e307);
}
if (!defined('NAN')) {
define('NAN', 0.0);
}
define('SOAP_LIBRARY_VERSION', '0.8.0RC4');
define('SOAP_LIBRARY_NAME', 'PEAR-SOAP 0.8.0RC4-devel');
// set schema version
define('SOAP_XML_SCHEMA_VERSION', 'http://www.w3.org/2001/XMLSchema');
define('SOAP_XML_SCHEMA_INSTANCE', 'http://www.w3.org/2001/XMLSchema-instance');
define('SOAP_XML_SCHEMA_1999', 'http://www.w3.org/1999/XMLSchema');
define('SOAP_SCHEMA', 'http://schemas.xmlsoap.org/wsdl/soap/');
define('SOAP_SCHEMA_ENCODING', 'http://schemas.xmlsoap.org/soap/encoding/');
define('SOAP_ENVELOP', 'http://schemas.xmlsoap.org/soap/envelope/');
define('SCHEMA_DISCO', 'http://schemas.xmlsoap.org/disco/');
define('SCHEMA_DISCO_SCL', 'http://schemas.xmlsoap.org/disco/scl/');
define('SCHEMA_SOAP', 'http://schemas.xmlsoap.org/wsdl/soap/');
define('SCHEMA_SOAP_HTTP', 'http://schemas.xmlsoap.org/soap/http');
define('SCHEMA_WSDL_HTTP', 'http://schemas.xmlsoap.org/wsdl/http/');
define('SCHEMA_MIME', 'http://schemas.xmlsoap.org/wsdl/mime/');
define('SCHEMA_WSDL', 'http://schemas.xmlsoap.org/wsdl/');
define('SCHEMA_DIME', 'http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/');
define('SCHEMA_CONTENT', 'http://schemas.xmlsoap.org/ws/2002/04/content-type/');
define('SCHEMA_REF', 'http://schemas.xmlsoap.org/ws/2002/04/reference/');
define('SOAP_DEFAULT_ENCODING', 'UTF-8');
if (!function_exists('is_a'))
{
function is_a(&$object, $class_name)
{
if (strtolower(get_class($object)) == $class_name) {
return true;
}
return is_subclass_of($object, $class_name);
}
}
if (!class_exists('stdClass')) {
/* PHP5 doesn't define this? */
class stdClass {
function __constructor() {}
};
}
class SOAP_Base_Object extends PEAR
{
/**
* Store debugging information in $debug_data?
*
* @var boolean if true debugging informations will be store in $debug_data
* @see $debug_data, SOAP_Base
*/
var $_debug_flag = false;
/**
* String containing debugging informations if $debug_flag is set to true
*
* @var string debugging informations - mostyl error messages
* @see $debug_flag, SOAP_Base
* @access public
*/
var $_debug_data = '';
/**
* supported encodings, limited by XML extension
*/
var $_encodings = array('ISO-8859-1', 'US-ASCII', 'UTF-8');
/**
* Fault code
*
* @var string
*/
var $_myfaultcode = '';
/**
* Recent PEAR error object
*
* @var object PEAR Error
*/
var $fault = null;
/**
* Set to true if Array key should be used as tag name while serializing array datatype.
* @var Boolean
*/
var $USE_ARRAYKEY_AS_TAGNAME = false;
/**
* Set to true if out tag to be supressed while serializing array datatype.
* @var Boolean
*/
var $SUPRESS_OUTTAG_FOR_ARRAY = false;
/**
* Set of elements for which out tag should be supressed while serializing array datatype.
* @var Array
*/
var $OUTTAG_SUPRESS_ELEMENTS = array();
/**
* Constructor
*
* @param string error code
* @see $debug_data, _debug()
*/
function SOAP_Base_Object($faultcode = 'Client')
{
$this->_myfaultcode = $faultcode;
$this->_debug_flag = $GLOBALS['SOAP_DEBUG'];
parent::PEAR('SOAP_Fault');
}
/**
* Raise a soap error
*
* Please referr to the SOAP definition for an impression of what a certain parameter
* stands for.
*
* Use $debug_flag to store errors to the member variable $debug_data
*
* @param string error message
* @param string detailed error message.
* @param string actor
* @param mixed
* @param mixed
* @param mixed
* @param boolean
* @see $debug_flag, $debug_data
*/
function &_raiseSoapFault($str, $detail = '', $actorURI = '', $code = null, $mode = null, $options = null, $skipmsg = false)
{
// Pass through previous faults.
$is_instance = isset($this);
if (is_object($str)) {
$fault =& $str;
} else {
if (!$code) {
$code = $is_instance?$this->_myfaultcode:'Client';
}
$fault =& new SOAP_Fault($str,
$code,
$actorURI,
$detail,
$mode,
$options);
}
if ($is_instance) {
$this->fault =& $fault;
}
return $fault;
}
function __isfault()
{
return $this->fault != null;
}
function &__getfault()
{
return $this->fault;
}
/**
* maintains a string of debug data.
*
* @param debugging message - sometimes an error message
*/
function _debug($string)
{
if ($this->_debug_flag) {
$this->_debug_data .= get_class($this) . ': ' . preg_replace("/>/", ">\r\n", $string) . "\n";
}
}
}
/**
* SOAP_Base
* Common base class of all Soap lclasses
*
* @access public
* @package SOAP::Client
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
*/
class SOAP_Base extends SOAP_Base_Object
{
var $_XMLSchema = array('http://www.w3.org/2001/XMLSchema', 'http://www.w3.org/1999/XMLSchema');
var $_XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema';
// load types into typemap array
var $_typemap = array(
'http://www.w3.org/2001/XMLSchema' => array(
'string' => 'string',
'boolean' => 'boolean',
'float' => FLOAT,
'double' => FLOAT,
'decimal' => FLOAT,
'duration' => 'integer',
'dateTime' => 'string',
'time' => 'string',
'date' => 'string',
'gYearMonth' => 'integer',
'gYear' => 'integer',
'gMonthDay' => 'integer',
'gDay' => 'integer',
'gMonth' => 'integer',
'hexBinary' => 'string',
'base64Binary' => 'string',
// derived datatypes
'normalizedString' => 'string',
'token' => 'string',
'language' => 'string',
'NMTOKEN' => 'string',
'NMTOKENS' => 'string',
'Name' => 'string',
'NCName' => 'string',
'ID' => 'string',
'IDREF' => 'string',
'IDREFS' => 'string',
'ENTITY' => 'string',
'ENTITIES' => 'string',
'integer' => 'integer',
'nonPositiveInteger' => 'integer',
'negativeInteger' => 'integer',
'long' => 'integer',
'int' => 'integer',
'short' => 'integer',
'byte' => 'string',
'nonNegativeInteger' => 'integer',
'unsignedLong' => 'integer',
'unsignedInt' => 'integer',
'unsignedShort' => 'integer',
'unsignedByte' => 'integer',
'positiveInteger' => 'integer',
'anyType' => 'string',
'anyURI' => 'string',
'QName' => 'string'
),
'http://www.w3.org/1999/XMLSchema' => array(
'i4' => 'integer',
'int' => 'integer',
'boolean' => 'boolean',
'string' => 'string',
'double' => FLOAT,
'float' => FLOAT,
'dateTime' => 'string',
'timeInstant' => 'string',
'base64Binary' => 'string',
'base64' => 'string',
'ur-type' => 'string'
),
'http://schemas.xmlsoap.org/soap/encoding/' => array(
'base64' => 'string',
'array' => 'array',
'Array' => 'array',
'Struct' => 'array')
);
/**
* Default class name to use for decoded response objects.
*/
var $_defaultObjectClassname = 'stdClass';
// Load namespace uris into an array of uri => prefix
var $_namespaces;
var $_namespace;
var $_xmlEntities = array('&' => '&', '<' => '<', '>' => '>', "'" => ''', '"' => '"');
var $_doconversion = false;
var $__attachments = array();
var $_wsdl = null;
/**
* section5
*
* @var boolean defines if we use section 5 encoding, or false if this is literal
*/
var $_section5 = true;
// handle type to class mapping
var $_auto_translation = false;
var $_type_translation = array();
/**
* Constructor
*
* @param string error code
* @see $debug_data, _debug()
*/
function SOAP_Base($faultcode = 'Client')
{
parent::SOAP_Base_Object($faultcode);
$this->_resetNamespaces();
}
function _resetNamespaces()
{
$this->_namespaces = array(
'http://schemas.xmlsoap.org/soap/envelope/' => 'SOAP-ENV',
'http://www.w3.org/2001/XMLSchema' => 'xsd',
'http://www.w3.org/2001/XMLSchema-instance' => 'xsi',
'http://schemas.xmlsoap.org/soap/encoding/' => 'SOAP-ENC');
}
/**
* _setSchemaVersion
*
* sets the schema version used in the soap message
*
* @param string (see globals.php)
*
* @access private
*/
function _setSchemaVersion($schemaVersion)
{
if (!in_array($schemaVersion, $this->_XMLSchema)) {
return $this->_raiseSoapFault("unsuported XMLSchema $schemaVersion");
}
$this->_XMLSchemaVersion = $schemaVersion;
$tmpNS = array_flip($this->_namespaces);
$tmpNS['xsd'] = $this->_XMLSchemaVersion;
$tmpNS['xsi'] = $this->_XMLSchemaVersion. '-instance';
$this->_namespaces = array_flip($tmpNS);
}
function _getNamespacePrefix($ns)
{
if ($this->_namespace && $ns == $this->_namespace) {
return '';
}
if (isset($this->_namespaces[$ns])) {
return $this->_namespaces[$ns];
}
$prefix = 'ns' . count($this->_namespaces);
$this->_namespaces[$ns] = $prefix;
return $prefix;
}
function _getNamespaceForPrefix($prefix)
{
$flipped = array_flip($this->_namespaces);
if (isset($flipped[$prefix])) {
return $flipped[$prefix];
}
return null;
}
function _isSoapValue(&$value)
{
return is_object($value) && is_a($value, 'soap_value');
}
function _serializeValue(&$value, $name = '', $type = false, $elNamespace = null,
$typeNamespace = null, $options = array(), $attributes = array(), $artype = '')
{
$namespaces = array();
$arrayType = $array_depth = $xmlout_value = null;
$typePrefix = $elPrefix = $xmlout_offset = $xmlout_arrayType = $xmlout_type = $xmlns = '';
$ptype = $array_type_ns = '';
$isArray = false;
if (!$name || is_numeric($name)) {
$name = 'item';
}
if ($this->_wsdl) {
list($ptype, $arrayType, $array_type_ns, $array_depth)
= $this->_wsdl->getSchemaType($type, $name, $typeNamespace);
}
if (!$arrayType) {
$arrayType = $artype;
}
if (!$ptype) {
$ptype = $this->_getType($value);
}
if (!$type) {
$type = $ptype;
}
if (strcasecmp($ptype, 'Struct') == 0 || strcasecmp($type, 'Struct') == 0) {
// struct
$vars = null;
if (is_object($value)) {
$vars = get_object_vars($value);
} else {
$vars = &$value;
}
if (is_array($vars)) {
foreach (array_keys($vars) as $k) {
// Hide private vars.
if ($k[0] == '_') continue;
if (is_object($vars[$k])) {
if (is_a($vars[$k], 'soap_value')) {
$xmlout_value .= $vars[$k]->serialize($this);
} else {
// XXX get the members and serialize them instead
// converting to an array is more overhead than we
// should really do.
$dvar = get_object_vars($vars[$k]);
if($this->USE_ARRAYKEY_AS_TAGNAME && in_array(substr($k,0,strlen($k)-2), $this->OUTTAG_SUPRESS_ELEMENTS)) {
$isArray = true;
$xmlout_value .= $this->_serializeValue( $dvar, substr($k,0,strlen($k)-2), false, $this->_section5 ? null : $elNamespace);
}
else {
$xmlout_value .= $this->_serializeValue( $dvar, $k, false, $this->_section5 ? null : $elNamespace);
}
}
} else {
$xmlout_value .= $this->_serializeValue($vars[$k], $k, false, $this->_section5 ? null : $elNamespace);
}
}
}
} elseif (strcasecmp($ptype, 'Array') == 0 || strcasecmp($type, 'Array') == 0) {
// Array.
$typeNamespace = SOAP_SCHEMA_ENCODING;
$orig_type = $type;
$type = 'Array';
$numtypes = 0;
// XXX this will be slow on larger arrays. Basically, it
// flattens arrays to allow us to serialize
// multi-dimensional arrays. We only do this if arrayType
// is set, which will typically only happen if we are
// using WSDL
if (isset($options['flatten']) || ($arrayType && (strchr($arrayType, ',') || strstr($arrayType, '][')))) {
$numtypes = $this->_multiArrayType($value, $arrayType, $ar_size, $xmlout_value);
}
$array_type = $array_type_prefix = '';
if ($numtypes != 1) {
$arrayTypeQName =& new QName($arrayType);
$arrayType = $arrayTypeQName->name;
$array_types = array();
$array_val = null;
// Serialize each array element.
$ar_size = count($value);
foreach ($value as $array_val) {
if ($this->_isSoapValue($array_val)) {
$array_type = $array_val->type;
$array_types[$array_type] = 1;
$array_type_ns = $array_val->type_namespace;
$xmlout_value .= $this->_serializeValue($array_val, $array_val->name, $array_type, $array_type_ns);
} else {
$array_type = $this->_getType($array_val);
$array_types[$array_type] = 1;
$xmlout_value .= $this->_serializeValue($array_val, 'item', $array_type, $this->_section5 ? null : $elNamespace);
}
}
$xmlout_offset = " SOAP-ENC:offset=\"[0]\"";
if (!$arrayType) {
$numtypes = count($array_types);
if ($numtypes == 1) {
$arrayType = $array_type;
}
// Using anyType is more interoperable.
if ($array_type == 'Struct') {
$array_type = '';
} elseif ($array_type == 'Array') {
$arrayType = 'anyType';
$array_type_prefix = 'xsd';
} else {
if (!$arrayType) {
$arrayType = $array_type;
}
}
}
}
if (!$arrayType || $numtypes > 1) {
$arrayType = 'xsd:anyType'; // should reference what schema we're using
} else {
if ($array_type_ns) {
$array_type_prefix = $this->_getNamespacePrefix($array_type_ns);
} elseif (isset($this->_typemap[$this->_XMLSchemaVersion][$arrayType])) {
$array_type_prefix = $this->_namespaces[$this->_XMLSchemaVersion];
}
if ($array_type_prefix)
$arrayType = $array_type_prefix. ':' .$arrayType;
}
$xmlout_arrayType = " SOAP-ENC:arrayType=\"" . $arrayType;
if ($array_depth != null) {
for ($i = 0; $i < $array_depth; $i++) {
$xmlout_arrayType .= '[]';
}
}
$xmlout_arrayType .= "[$ar_size]\"";
} elseif ($this->_isSoapValue($value)) {
$xmlout_value =& $value->serialize($this);
} elseif ($type == 'string') {
$xmlout_value = htmlspecialchars($value);
} elseif ($type == 'rawstring') {
$xmlout_value =& $value;
} elseif ($type == 'boolean') {
$xmlout_value = $value?'true':'false';
} else {
$xmlout_value =& $value;
}
// Add namespaces.
if ($elNamespace) {
$elPrefix = $this->_getNamespacePrefix($elNamespace);
if ($elPrefix) {
$xmlout_name = "$elPrefix:$name";
} else {
$xmlout_name = $name;
}
} else {
$xmlout_name = $name;
}
if ($typeNamespace) {
$typePrefix = $this->_getNamespacePrefix($typeNamespace);
if ($typePrefix) {
$xmlout_type = "$typePrefix:$type";
} else {
$xmlout_type = $type;
}
} elseif ($type && isset($this->_typemap[$this->_XMLSchemaVersion][$type])) {
$typePrefix = $this->_namespaces[$this->_XMLSchemaVersion];
if ($typePrefix) {
$xmlout_type = "$typePrefix:$type";
} else {
$xmlout_type = $type;
}
}
// Handle additional attributes.
$xml_attr = '';
if (count($attributes)) {
foreach ($attributes as $k => $v) {
$kqn =& new QName($k);
$vqn =& new QName($v);
$xml_attr .= ' ' . $kqn->fqn() . '="' . $vqn->fqn() . '"';
}
}
// Store the attachement for mime encoding.
if (isset($options['attachment'])) {
$this->__attachments[] = $options['attachment'];
}
if($this->SUPRESS_OUTTAG_FOR_ARRAY && (strcasecmp($ptype, 'Struct') == 0 || strcasecmp($type, 'Struct') == 0)) {
if ($isArray) {
$xml = "\r\n" . $xmlout_value;
}
else {
if ($this->_section5) {
if ($xmlout_type) {
$xmlout_type = " xsi:type=\"$xmlout_type\"";
}
if (is_null($xmlout_value)) {
$xml = "\r\n<$xmlout_name$xmlout_type$xmlns$xmlout_arrayType$xml_attr xsi:nil=\"true\"/>";
} else {
$xml = "\r\n<$xmlout_name$xmlout_type$xmlns$xmlout_arrayType$xmlout_offset$xml_attr>" .
$xmlout_value . "</$xmlout_name>";
}
} else {
if (is_null($xmlout_value)) {
$xml = "\r\n<$xmlout_name$xmlns$xml_attr/>";
} else {
$xml = "\r\n<$xmlout_name$xmlns$xml_attr>" .
$xmlout_value . "</$xmlout_name>";
}
}
}
}
else
{
if ($this->_section5) {
if ($xmlout_type) {
$xmlout_type = " xsi:type=\"$xmlout_type\"";
}
if (is_null($xmlout_value)) {
$xml = "\r\n<$xmlout_name$xmlout_type$xmlns$xmlout_arrayType$xml_attr xsi:nil=\"true\"/>";
} else {
$xml = "\r\n<$xmlout_name$xmlout_type$xmlns$xmlout_arrayType$xmlout_offset$xml_attr>" .
$xmlout_value . "</$xmlout_name>";
}
} else {
if (is_null($xmlout_value)) {
$xml = "\r\n<$xmlout_name$xmlns$xml_attr/>";
} else {
$xml = "\r\n<$xmlout_name$xmlns$xml_attr>" .
$xmlout_value . "</$xmlout_name>";
}
}
}
return $xml;
}
/**
* SOAP::Value::_getType
*
* Convert a php type to a soap type.
*
* @param string &$value The value to inspect.
*
* @return string Soap type.
*
* @access private
*/
function _getType(&$value)
{
global $SOAP_OBJECT_STRUCT, $SOAP_RAW_CONVERT;
$type = gettype($value);
switch ($type) {
case 'object':
if (is_a($value, 'soap_value')) {
$type = $value->type;
} else {
$type = 'Struct';
}
break;
case 'array':
// XXX hashes always get done as structs by pear::soap
if ($this->_isHash($value)) {
$type = 'Struct';
} else {
$ar_size = count($value);
reset($value);
$key1 = key($value);
if ($ar_size > 0 && is_a($key1, 'soap_value')) {
// fixme for non-wsdl structs that are all the same type
$key2 = key($value);
if ($ar_size > 1 &&
$this->_isSoapValue($key1) &&
$this->_isSoapValue($key2) &&
$key1->name != $key2->name) {
// this is a struct, not an array
$type = 'Struct';
} else {
$type = 'Array';
}
} else {
$type = 'Array';
}
}
break;
case 'integer':
case 'long':
$type = 'int';
break;
case 'boolean':
break;
case 'double':
$type = 'float'; // double is deprecated in 4.2 and later
break;
case 'null':
$type = '';
break;
case 'string':
if ($SOAP_RAW_CONVERT) {
if (is_numeric($value)) {
if (strstr($value, '.')) {
$type = 'float';
} else {
$type = 'int';
}
} else {
if (SOAP_Type_hexBinary::is_hexbin($value)) {
$type = 'hexBinary';
} else {
if ($this->_isBase64($value)) {
$type = 'base64Binary';
} else {
$dt =& new SOAP_Type_dateTime($value);
if ($dt->toUnixtime() != -1) {
$type = 'dateTime';
}
}
}
}
}
break;
default:
break;
}
return $type;
}
function _multiArrayType(&$value, &$type, &$size, &$xml)
{
$sz = count($value);
if (is_array($value)) {
// Seems we have a multi dimensional array, figure it out
// if we do.
$c = count($value);
for ($i = 0; $i < $c; $i++) {
$this->_multiArrayType($value[$i], $type, $size, $xml);
}
if ($size) {
$size = $sz. ',' . $size;
} else {
$size = $sz;
}
return 1;
} else {
if (is_object($value)) {
$type = $value->type;
$xml .= $value->serialize($this);
} else {
$type = $this->_getType($value);
$xml .= $this->_serializeValue($value, 'item', $type);
}
}
$size = null;
return 1;
}
/**
*
* @param string
* @return boolean
*/
function _isBase64(&$value)
{
$l = strlen($value);
if ($l) {
return $value[$l - 1] == '=' && preg_match("/[A-Za-z=\/\+]+/", $value);
}
return false;
}
/**
*
* @param string
* @return boolean
*/
function _isBase64Type($type)
{
return $type == 'base64' || $type == 'base64Binary';
}
/**
*
* @param mixed
* @return boolean
*/
function _isHash(&$a)
{
// XXX I really dislike having to loop through this in PHP
// code, really large arrays will be slow. We need a C
// function to do this.
$names = array();
$it = 0;
foreach ($a as $k => $v) {
// Checking the type is faster than regexp.
$t = gettype($k);
if ($t != 'integer') {
return true;
} elseif ($this->_isSoapValue($v)) {
$names[$v->name] = 1;
}
// If someone has a large hash they should realy be
// defining the type.
if ($it++ > 10) {
return false;
}
}
return count($names)>1;
}
function &_un_htmlentities($string)
{
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
return strtr($string, $trans_tbl);
}
/**
*
* @param mixed
*/
function &_decode(&$soapval)
{
global $SOAP_OBJECT_STRUCT;
if (!$this->_isSoapValue($soapval)) {
return $soapval;
} elseif (is_array($soapval->value)) {
if ($SOAP_OBJECT_STRUCT && $soapval->type != 'Array') {
$classname = $this->_defaultObjectClassname;
if (isset($this->_type_translation[$soapval->tqn->fqn()])) {
// This will force an error in php if the class
// does not exist.
$classname = $this->_type_translation[$soapval->tqn->fqn()];
} elseif (isset($this->_type_translation[$soapval->type])) {
// This will force an error in php if the class
// does not exist.
$classname = $this->_type_translation[$soapval->type];
} elseif ($this->_auto_translation) {
if (class_exists($soapval->type)) {
$classname = $soapval->type;
} elseif ($this->_wsdl) {
$t = $this->_wsdl->getComplexTypeNameForElement($soapval->name, $soapval->namespace);
if ($t && class_exists($t)) {
$classname = $t;
}
}
}
$return =& new $classname;
} else {
$return = array();
}
$counter = 1;
$isstruct = !$SOAP_OBJECT_STRUCT || !is_array($return);
foreach ($soapval->value as $item) {
if (is_object($return)) {
if ($this->_wsdl) {
// Get this child's WSDL information.
// /$soapval->ns/$soapval->type/$item->ns/$item->name
$child_type = $this->_wsdl->getComplexTypeChildType(
$soapval->namespace,
$soapval->name,
$item->namespace,
$item->name);
if ($child_type) {
$item->type = $child_type;
}
}
if (!$isstruct || $item->type == 'Array') {
if (isset($return->{$item->name}) &&
is_object($return->{$item->name})) {
$return->{$item->name} =& $this->_decode($item);
} elseif (isset($return->{$item->name}) &&
is_array($return->{$item->name})) {
$return->{$item->name}[] =& $this->_decode($item);
} elseif (is_array($return)) {
$return[] =& $this->_decode($item);
} else {
$return->{$item->name} =& $this->_decode($item);
}
} elseif (isset($return->{$item->name})) {
$isstruct = false;
if (count(get_object_vars($return)) == 1) {
$d =& $this->_decode($item);
$return = array($return->{$item->name}, $d);
} else {
$d =& $this->_decode($item);
$return->{$item->name} = array($return->{$item->name}, $d);
}
} else {
$return->{$item->name} =& $this->_decode($item);
}
// Set the attributes as members in the class.
if (method_exists($return, '__set_attribute')) {
foreach ($soapval->attributes as $key => $value) {
call_user_func_array(array(&$return, '__set_attribute'), array($key, $value));
}
}
} else {
if ($soapval->arrayType && $this->_isSoapValue($item)) {
if ($this->_isBase64Type($item->type) && !$this->_isBase64Type($soapval->arrayType)) {
// Decode the value if we're losing the
// base64 type information.
$item->value = base64_decode($item->value);
}
$item->type = $soapval->arrayType;
}
if (!$isstruct) {
$return[] =& $this->_decode($item);
} elseif (isset($return[$item->name])) {
$isstruct = false;
$d =& $this->_decode($item);
$return = array($return[$item->name], $d);
} else {
$return[$item->name] =& $this->_decode($item);
}
}
}
return $return;
}
if ($soapval->type == 'boolean') {
if ($soapval->value != '0' && strcasecmp($soapval->value, 'false') != 0) {
$soapval->value = true;
} else {
$soapval->value = false;
}
} elseif ($soapval->type && isset($this->_typemap[SOAP_XML_SCHEMA_VERSION][$soapval->type])) {
// If we can, set variable type.
settype($soapval->value, $this->_typemap[SOAP_XML_SCHEMA_VERSION][$soapval->type]);
}
if ($this->_isBase64Type($soapval->type)) {
return base64_decode($soapval->value);
} else {
return $soapval->value;
}
}
/**
* Creates the soap envelope with the soap envelop data.
*
* @param string $payload soap data (in xml)
* @return associative array (headers,body)
* @access private
*/
function &_makeEnvelope(&$method, &$headers, $encoding = SOAP_DEFAULT_ENCODING, $options = array())
{
$smsg = $header_xml = $ns_string = '';
if ($headers) {
$c = count($headers);
for ($i = 0; $i < $c; $i++) {
$header_xml .= $headers[$i]->serialize($this);
}
$header_xml = "<SOAP-ENV:Header>\r\n$header_xml\r\n</SOAP-ENV:Header>\r\n";
}
if (!isset($options['input']) || $options['input'] == 'parse') {
if (is_array($method)) {
$c = count($method);
for ($i = 0; $i < $c; $i++) {
$smsg .= $method[$i]->serialize($this);
}
} else {
$smsg =& $method->serialize($this);
}
} else {
$smsg =& $method;
}
$body = "<SOAP-ENV:Body>\r\n" . $smsg . "\r\n</SOAP-ENV:Body>\r\n";
foreach ($this->_namespaces as $k => $v) {
$ns_string .= " xmlns:$v=\"$k\"\r\n";
}
if ($this->_namespace) {
$ns_string .= " xmlns=\"{$this->_namespace}\"\r\n";
}
/* if use='literal', we do not put in the encodingStyle. This is denoted by
$this->_section5 being false.
XXX use can be defined at a more granular level than we are dealing with
here, so this does not work for all services.
*/
$xml = "<?xml version=\"1.0\" encoding=\"$encoding\"?>\r\n\r\n".
"<SOAP-ENV:Envelope $ns_string".
($this->_section5 ? ' SOAP-ENV:encodingStyle="' . SOAP_SCHEMA_ENCODING . '"' : '').
">\r\n".
"$header_xml$body</SOAP-ENV:Envelope>\r\n";
return $xml;
}
function &_makeMimeMessage(&$xml, $encoding = SOAP_DEFAULT_ENCODING)
{
global $SOAP_options;
if (!isset($SOAP_options['Mime'])) {
return $this->_raiseSoapFault('Mime is not installed');
}
// encode any attachments
// see http://www.w3.org/TR/SOAP-attachments
// now we have to mime encode the message
$params = array('content_type' => 'multipart/related; type=text/xml');
$msg =& new Mail_mimePart('', $params);
// add the xml part
$params['content_type'] = 'text/xml';
$params['charset'] = $encoding;
$params['encoding'] = 'base64';
$msg->addSubPart($xml, $params);
// add the attachements
$c = count($this->__attachments);
for ($i = 0; $i < $c; $i++) {
$attachment =& $this->__attachments[$i];
$msg->addSubPart($attachment['body'], $attachment);
}
return $msg->encode();
}
// XXX this needs to be used from the Transport system
function &_makeDIMEMessage(&$xml)
{
global $SOAP_options;
if (!isset($SOAP_options['DIME'])) {
return $this->_raiseSoapFault('DIME is not installed');
}
// encode any attachments
// see http://search.ietf.org/internet-drafts/draft-nielsen-dime-soap-00.txt
// now we have to DIME encode the message
$dime =& new Net_DIME_Message();
$msg =& $dime->encodeData($xml,SOAP_ENVELOP,null,NET_DIME_TYPE_URI);
// add the attachements
$c = count($this->__attachments);
for ($i = 0; $i < $c; $i++) {
$attachment =& $this->__attachments[$i];
$msg .= $dime->encodeData($attachment['body'], $attachment['content_type'], $attachment['cid'],NET_DIME_TYPE_MEDIA);
}
$msg .= $dime->endMessage();
return $msg;
}
function _decodeMimeMessage(&$data, &$headers, &$attachments)
{
global $SOAP_options;
if (!isset($SOAP_options['Mime'])) {
$this->_raiseSoapFault('Mime Unsupported, install PEAR::Mail::Mime', '', '', 'Server');
return;
}
$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
// XXX lame thing to have to do for decoding
$decoder =& new Mail_mimeDecode($data);
$structure = $decoder->decode($params);
if (isset($structure->body)) {
$data = $structure->body;
$headers = $structure->headers;
return;
} elseif (isset($structure->parts)) {
$data = $structure->parts[0]->body;
$headers = array_merge($structure->headers, $structure->parts[0]->headers);
if (count($structure->parts) > 1) {
$mime_parts = array_splice($structure->parts,1);
// prepare the parts for the soap parser
$c = count($mime_parts);
for ($i = 0; $i < $c; $i++) {
$p =& $mime_parts[$i];
if (isset($p->headers['content-location'])) {
// XXX TODO: modify location per SwA note section 3
// http://www.w3.org/TR/SOAP-attachments
$attachments[$p->headers['content-location']] = $p->body;
} else {
$cid = 'cid:' . substr($p->headers['content-id'], 1, strlen($p->headers['content-id']) - 2);
$attachments[$cid] = $p->body;
}
}
}
return;
}
$this->_raiseSoapFault('Mime parsing error', '', '', 'Server');
}
function _decodeDIMEMessage(&$data, &$headers, &$attachments)
{
global $SOAP_options;
if (!isset($SOAP_options['DIME'])) {
$this->_raiseSoapFault('DIME Unsupported, install PEAR::Net::DIME', '', '', 'Server');
return;
}
// XXX this SHOULD be moved to the transport layer, e.g. PHP itself
// should handle parsing DIME ;)
$dime =& new Net_DIME_Message();
$err = $dime->decodeData($data);
if (PEAR::isError($err)) {
$this->_raiseSoapFault('Failed to decode the DIME message!', '', '', 'Server');
return;
}
if (strcasecmp($dime->parts[0]['type'], SOAP_ENVELOP) != 0) {
$this->_raiseSoapFault('DIME record 1 is not a SOAP envelop!', '', '', 'Server');
return;
}
$data = $dime->parts[0]['data'];
// fake it for now
$headers['content-type'] = 'text/xml';
$c = count($dime->parts);
for ($i = 0; $i < $c; $i++) {
$part =& $dime->parts[$i];
// XXX we need to handle URI's better.
$id = strncmp($part['id'], 'cid:', 4) ? 'cid:' . $part['id'] : $part['id'];
$attachments[$id] = $part['data'];
}
}
function __set_type_translation($type, $class = null)
{
$tq =& new QName($type);
if (!$class) {
$class = $tq->name;
}
$this->_type_translation[$type]=$class;
}
}
/**
* Class used to handle QNAME values in XML.
*
* @access public
* @package SOAP::Client
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
*/
class QName
{
var $name = '';
var $ns = '';
var $namespace='';
function QName($name, $namespace = '')
{
if ($name && $name[0] == '{') {
preg_match('/\{(.*?)\}(.*)/', $name, $m);
$this->name = $m[2];
$this->namespace = $m[1];
} elseif (substr_count($name, ':') == 1) {
$s = explode(':', $name);
$s = array_reverse($s);
$this->name = $s[0];
$this->ns = $s[1];
$this->namespace = $namespace;
} else {
$this->name = $name;
$this->namespace = $namespace;
}
// a little more magic than should be in a qname.
$p = strpos($this->name, '[');
if ($p) {
// XXX need to re-examine this logic later
// chop off []
$this->arraySize = explode(',', substr($this->name, $p + 1, strlen($this->name) - $p - 2));
$this->arrayInfo = substr($this->name, $p);
$this->name = substr($this->name, 0, $p);
}
}
function fqn()
{
if ($this->namespace) {
return '{' . $this->namespace . '}' . $this->name;
} elseif ($this->ns) {
return $this->ns . ':' . $this->name;
}
return $this->name;
}
} | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Base.php | PHP | asf20 | 44,360 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: Parser.php,v 1.1 2011/09/18 05:16:03 iling Exp $
//
require_once 'PayPal/SOAP/Base.php';
require_once 'PayPal/SOAP/Value.php';
/**
* SOAP Parser
*
* This class is used by SOAP::Message and SOAP::Server to parse soap
* packets. Originally based on SOAPx4 by Dietrich Ayala
* http://dietrich.ganx4.com/soapx4
*
* @access public
* @package SOAP::Parser
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
* @author Dietrich Ayala <dietrich@ganx4.com> Original Author
*/
class SOAP_Parser extends SOAP_Base
{
var $status = '';
var $position = 0;
var $pos_stat = 0;
var $depth = 0;
var $default_namespace = '';
var $message = array();
var $depth_array = array();
var $previous_element = '';
var $soapresponse = null;
var $soapheaders = null;
var $parent = 0;
var $root_struct_name = array();
var $header_struct_name = array();
var $curent_root_struct_name = '';
var $entities = array ( '&' => '&', '<' => '<', '>' => '>', "'" => ''', '"' => '"' );
var $root_struct = array();
var $header_struct = array();
var $curent_root_struct = 0;
var $references = array();
var $need_references = array();
var $XMLSchemaVersion;
var $bodyDepth; // used to handle non-root elements before root body element
/**
* SOAP_Parser constructor
*
* @param string xml content
* @param string xml character encoding, defaults to 'UTF-8'
*/
function SOAP_Parser(&$xml, $encoding = SOAP_DEFAULT_ENCODING, $attachments = null)
{
parent::SOAP_Base('Parser');
$this->_setSchemaVersion(SOAP_XML_SCHEMA_VERSION);
$this->attachments = $attachments;
// Check the xml tag for encoding.
if (preg_match('/<\?xml[^>]+encoding\s*?=\s*?(\'([^\']*)\'|"([^"]*)")[^>]*?[\?]>/', $xml, $m)) {
$encoding = strtoupper($m[2] ? $m[2] : $m[3]);
}
// Determines where in the message we are
// (envelope,header,body,method). Check whether content has
// been read.
if (!empty($xml)) {
// Prepare the xml parser.
$parser = xml_parser_create($encoding);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_set_object($parser, $this);
xml_set_element_handler($parser, 'startElement', 'endElement');
xml_set_character_data_handler($parser, 'characterData');
// Some lame soap implementations add null bytes at the
// end of the soap stream, and expat choaks on that.
if ($xml[strlen($xml) - 1] == 0) {
$xml = trim($xml);
}
// Parse the XML file.
if (!xml_parse($parser, $xml, true)) {
$err = sprintf('XML error on line %d col %d byte %d %s',
xml_get_current_line_number($parser),
xml_get_current_column_number($parser),
xml_get_current_byte_index($parser),
xml_error_string(xml_get_error_code($parser)));
$this->_raiseSoapFault($err,htmlspecialchars($xml));
}
xml_parser_free($parser);
}
}
/**
* domulti
* recurse to build a multi-dim array, used by buildResponse
*
* @access private
*/
function domulti($d, &$ar, &$r, &$v, $ad=0)
{
if ($d) {
$this->domulti($d-1, $ar, $r[$ar[$ad]], $v, $ad+1);
} else {
$r = $v;
}
}
/**
* buildResponse
* loop through msg, building response structures
*
* @param int position
* @return SOAP_Value
* @access private
*/
function &buildResponse($pos)
{
$response = null;
if (isset($this->message[$pos]['children'])) {
$children = explode('|', $this->message[$pos]['children']);
foreach ($children as $c => $child_pos) {
if ($this->message[$child_pos]['type'] != null) {
$response[] =& $this->buildResponse($child_pos);
}
}
if (array_key_exists('arraySize', $this->message[$pos])) {
$ardepth = count($this->message[$pos]['arraySize']);
if ($ardepth > 1) {
$ar = array_pad(array(), $ardepth, 0);
if (array_key_exists('arrayOffset', $this->message[$pos])) {
for ($i = 0; $i < $ardepth; $i++) {
$ar[$i] += $this->message[$pos]['arrayOffset'][$i];
}
}
$elc = count($response);
for ($i = 0; $i < $elc; $i++) {
// recurse to build a multi-dimensional array
$this->domulti($ardepth, $ar, $newresp, $response[$i]);
// increment our array pointers
$ad = $ardepth - 1;
$ar[$ad]++;
while ($ad > 0 && $ar[$ad] >= $this->message[$pos]['arraySize'][$ad]) {
$ar[$ad] = 0;
$ad--;
$ar[$ad]++;
}
}
$response = $newresp;
} elseif (isset($this->message[$pos]['arrayOffset']) &&
$this->message[$pos]['arrayOffset'][0] > 0) {
// check for padding
$pad = $this->message[$pos]['arrayOffset'][0] + count($response) * -1;
$response = array_pad($response, $pad, null);
}
}
}
// Build attributes.
$attrs = array();
foreach ($this->message[$pos]['attrs'] as $atn => $atv) {
if (!strstr($atn, 'xmlns') &&
!strpos($atn, ':')) {
$attrs[$atn] = $atv;
}
}
// Add current node's value.
if ($response) {
$nqn =& new Qname($this->message[$pos]['name'], $this->message[$pos]['namespace']);
$tqn =& new Qname($this->message[$pos]['type'], $this->message[$pos]['type_namespace']);
$response =& new SOAP_Value($nqn->fqn(), $tqn->fqn(), $response, $attrs);
if (isset($this->message[$pos]['arrayType'])) {
$response->arrayType = $this->message[$pos]['arrayType'];
}
} else {
$nqn =& new Qname($this->message[$pos]['name'], $this->message[$pos]['namespace']);
$tqn =& new Qname($this->message[$pos]['type'], $this->message[$pos]['type_namespace']);
$response =& new SOAP_Value($nqn->fqn(), $tqn->fqn(), $this->message[$pos]['cdata'], $attrs);
}
// handle header attribute that we need
if (array_key_exists('actor', $this->message[$pos])) {
$response->actor = $this->message[$pos]['actor'];
}
if (array_key_exists('mustUnderstand', $this->message[$pos])) {
$response->mustunderstand = $this->message[$pos]['mustUnderstand'];
}
return $response;
}
/**
* startElement
* start-element handler used with xml parser
*
* @access private
*/
function startElement($parser, $name, $attrs)
{
// position in a total number of elements, starting from 0
// update class level pos
$pos = $this->position++;
// and set mine
$this->message[$pos] = array();
$this->message[$pos]['type'] = '';
$this->message[$pos]['type_namespace'] = '';
$this->message[$pos]['cdata'] = '';
$this->message[$pos]['pos'] = $pos;
$this->message[$pos]['id'] = '';
// parent/child/depth determinations
// depth = how many levels removed from root?
// set mine as current global depth and increment global depth value
$this->message[$pos]['depth'] = $this->depth++;
// else add self as child to whoever the current parent is
if ($pos != 0) {
if (isset($this->message[$this->parent]['children']))
$this->message[$this->parent]['children'] .= "|$pos";
else
$this->message[$this->parent]['children'] = $pos;
}
// set my parent
$this->message[$pos]['parent'] = $this->parent;
// set self as current value for this depth
$this->depth_array[$this->depth] = $pos;
// set self as current parent
$this->parent = $pos;
$qname =& new QName($name);
// set status
if (strcasecmp('envelope', $qname->name) == 0) {
$this->status = 'envelope';
} elseif (strcasecmp('header', $qname->name) == 0) {
$this->status = 'header';
$this->header_struct_name[] = $this->curent_root_struct_name = $qname->name;
$this->header_struct[] = $this->curent_root_struct = $pos;
$this->message[$pos]['type'] = 'Struct';
} elseif (strcasecmp('body', $qname->name) == 0) {
$this->status = 'body';
$this->bodyDepth = $this->depth;
// Set method
} elseif ($this->status == 'body') {
// Is this element allowed to be a root?
// XXX this needs to be optimized, we loop through attrs twice now.
$can_root = $this->depth == $this->bodyDepth + 1;
if ($can_root) {
foreach ($attrs as $key => $value) {
if (stristr($key, ':root') && !$value) {
$can_root = FALSE;
}
}
}
if ($can_root) {
$this->status = 'method';
$this->root_struct_name[] = $this->curent_root_struct_name = $qname->name;
$this->root_struct[] = $this->curent_root_struct = $pos;
$this->message[$pos]['type'] = 'Struct';
}
}
// Set my status.
$this->message[$pos]['status'] = $this->status;
// Set name.
$this->message[$pos]['name'] = htmlspecialchars($qname->name);
// Set attributes.
$this->message[$pos]['attrs'] = $attrs;
// Loop through attributes, logging ns and type declarations.
foreach ($attrs as $key => $value) {
// If ns declarations, add to class level array of valid
// namespaces.
$kqn =& new QName($key);
if ($kqn->ns == 'xmlns') {
$prefix = $kqn->name;
if (in_array($value, $this->_XMLSchema)) {
$this->_setSchemaVersion($value);
}
$this->_namespaces[$value] = $prefix;
// Set method namespace.
} elseif ($key == 'xmlns') {
$qname->ns = $this->_getNamespacePrefix($value);
$qname->namespace = $value;
} elseif ($kqn->name == 'actor') {
$this->message[$pos]['actor'] = $value;
} elseif ($kqn->name == 'mustUnderstand') {
$this->message[$pos]['mustUnderstand'] = $value;
// If it's a type declaration, set type.
} elseif ($kqn->name == 'type') {
$vqn =& new QName($value);
$this->message[$pos]['type'] = $vqn->name;
$this->message[$pos]['type_namespace'] = $this->_getNamespaceForPrefix($vqn->ns);
// Should do something here with the namespace of
// specified type?
} elseif ($kqn->name == 'arrayType') {
$vqn =& new QName($value);
$this->message[$pos]['type'] = 'Array';
if (isset($vqn->arraySize)) {
$this->message[$pos]['arraySize'] = $vqn->arraySize;
}
$this->message[$pos]['arrayType'] = $vqn->name;
} elseif ($kqn->name == 'offset') {
$this->message[$pos]['arrayOffset'] = split(',', substr($value, 1, strlen($value) - 2));
} elseif ($kqn->name == 'id') {
// Save id to reference array.
$this->references[$value] = $pos;
$this->message[$pos]['id'] = $value;
} elseif ($kqn->name == 'href') {
if ($value[0] == '#') {
$ref = substr($value, 1);
if (isset($this->references[$ref])) {
// cdata, type, inval.
$ref_pos = $this->references[$ref];
$this->message[$pos]['children'] = &$this->message[$ref_pos]['children'];
$this->message[$pos]['cdata'] = &$this->message[$ref_pos]['cdata'];
$this->message[$pos]['type'] = &$this->message[$ref_pos]['type'];
$this->message[$pos]['arraySize'] = &$this->message[$ref_pos]['arraySize'];
$this->message[$pos]['arrayType'] = &$this->message[$ref_pos]['arrayType'];
} else {
// Reverse reference, store in 'need reference'.
if (!isset($this->need_references[$ref])) {
$this->need_references[$ref] = array();
}
$this->need_references[$ref][] = $pos;
}
} elseif (isset($this->attachments[$value])) {
$this->message[$pos]['cdata'] = $this->attachments[$value];
}
}
}
// See if namespace is defined in tag.
if (array_key_exists('xmlns:' . $qname->ns, $attrs)) {
$namespace = $attrs['xmlns:' . $qname->ns];
} elseif ($qname->ns && !$qname->namespace) {
$namespace = $this->_getNamespaceForPrefix($qname->ns);
} else {
// Get namespace.
$namespace = $qname->namespace ? $qname->namespace : $this->default_namespace;
}
$this->message[$pos]['namespace'] = $namespace;
$this->default_namespace = $namespace;
}
/**
* endElement
* end-element handler used with xml parser
*
* @access private
*/
function endElement($parser, $name)
{
// Position of current element is equal to the last value left
// in depth_array for my depth.
$pos = $this->depth_array[$this->depth];
// Bring depth down a notch.
$this->depth--;
$qname =& new QName($name);
// Get type if not explicitly declared in an xsi:type attribute.
// XXX check on integrating wsdl validation here
if ($this->message[$pos]['type'] == '') {
if (isset($this->message[$pos]['children'])) {
/* this is slow, need to look at some faster method
$children = explode('|', $this->message[$pos]['children']);
if (count($children) > 2 &&
$this->message[$children[1]]['name'] == $this->message[$children[2]]['name']) {
$this->message[$pos]['type'] = 'Array';
} else {
$this->message[$pos]['type'] = 'Struct';
}*/
$this->message[$pos]['type'] = 'Struct';
} else {
$parent = $this->message[$pos]['parent'];
if ($this->message[$parent]['type'] == 'Array' &&
array_key_exists('arrayType', $this->message[$parent])) {
$this->message[$pos]['type'] = $this->message[$parent]['arrayType'];
} else {
$this->message[$pos]['type'] = 'string';
}
}
}
// If tag we are currently closing is the method wrapper.
if ($pos == $this->curent_root_struct) {
$this->status = 'body';
} elseif ($qname->name == 'Body' || $qname->name == 'Header') {
$this->status = 'envelope';
}
// Set parent back to my parent.
$this->parent = $this->message[$pos]['parent'];
// Handle any reverse references now.
$idref = $this->message[$pos]['id'];
if ($idref != '' && array_key_exists($idref, $this->need_references)) {
foreach ($this->need_references[$idref] as $ref_pos) {
// XXX is this stuff there already?
$this->message[$ref_pos]['children'] = &$this->message[$pos]['children'];
$this->message[$ref_pos]['cdata'] = &$this->message[$pos]['cdata'];
$this->message[$ref_pos]['type'] = &$this->message[$pos]['type'];
$this->message[$ref_pos]['arraySize'] = &$this->message[$pos]['arraySize'];
$this->message[$ref_pos]['arrayType'] = &$this->message[$pos]['arrayType'];
}
}
}
/**
* characterData
* element content handler used with xml parser
*
* @access private
*/
function characterData($parser, $data)
{
$pos = $this->depth_array[$this->depth];
if (isset($this->message[$pos]['cdata'])) {
$this->message[$pos]['cdata'] .= $data;
} else {
$this->message[$pos]['cdata'] = $data;
}
}
/**
* getResponse
*
* returns an array of responses
* after parsing a soap message, use this to get the response
*
* @return array
* @access public
*/
function &getResponse()
{
if (isset($this->root_struct[0]) &&
$this->root_struct[0]) {
return $this->buildResponse($this->root_struct[0]);
}
return $this->_raiseSoapFault("couldn't build response");
}
/**
* getHeaders
*
* returns an array of header responses
* after parsing a soap message, use this to get the response
*
* @return array
* @access public
*/
function &getHeaders()
{
if (isset($this->header_struct[0]) &&
$this->header_struct[0]) {
return $this->buildResponse($this->header_struct[0]);
}
// We don't fault if there are no headers that can be handled
// by the app if necessary.
return null;
}
/**
* decodeEntities
*
* removes entities from text
*
* @param string
* @return string
* @access private
*/
function decodeEntities($text)
{
$trans_tbl = array_flip($this->entities);
return strtr($text, $trans_tbl);
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Parser.php | PHP | asf20 | 20,328 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> |
// +----------------------------------------------------------------------+
//
// $Id: HTTP.php,v 1.1 2011/09/18 05:16:13 iling Exp $
//
/**
* Needed Classes
*/
require_once 'PayPal/SOAP/Base.php';
require_once 'PayPal/SDKProxyProperties.php';
require_once 'PayPal/CallerServices.php';
require_once 'PayPal.php';
session_start();
/**
* HTTP Transport for SOAP
*
* @access public
* @package SOAP::Transport::HTTP
* @author Shane Caraveo <shane@php.net>
*/
class SOAP_Transport_HTTP extends SOAP_Base
{
/**
* Basic Auth string
*
* @var array
*/
var $headers = array();
/**
* Cookies
*
* @var array
*/
var $cookies;
/**
*
* @var int connection timeout in seconds - 0 = none
*/
var $timeout = 300;
/**
* Array containing urlparts - parse_url()
*
* @var mixed
*/
var $urlparts = NULL;
/**
* Connection endpoint - URL
*
* @var string
*/
var $url = '';
/**
* Incoming payload
*
* @var string
*/
var $incoming_payload = '';
/**
* HTTP-Request User-Agent
*
* @var string
*/
var $_userAgent = SOAP_LIBRARY_NAME;
/**
* HTTP Encoding
*
* @var string
*/
var $encoding = SOAP_DEFAULT_ENCODING;
/**
* HTTP-Response Content-Type encoding
*
* we assume UTF-8 if no encoding is set
* @var string
*/
var $result_encoding = 'UTF-8';
/**
* HTTP-Response Content-Type
*/
var $result_content_type;
var $result_headers = array();
var $result_cookies = array();
/**
* SOAP_Transport_HTTP Constructor
*
* @param string $URL http url to soap endpoint
*
* @access public
* @param string $URI
* @param string $encoding encoding to use
*/
function SOAP_Transport_HTTP($URL, $encoding = SOAP_DEFAULT_ENCODING)
{
parent::SOAP_Base('HTTP');
$this->urlparts = @parse_url($URL);
$this->url = $URL;
$this->encoding = $encoding;
}
/**
* send and receive soap data
*
* @param string outgoing post data
* @param array options
*
* @return string|fault response
* @access public
*/
function &send(&$msg, $options = null)
{
if (!$this->_validateUrl()) {
return $this->fault;
}
if (isset($options['timeout']))
$this->timeout = (int)$options['timeout'];
if (strcasecmp($this->urlparts['scheme'], 'HTTP') == 0) {
return $this->_sendHTTP($msg, $options);
} else if (strcasecmp($this->urlparts['scheme'], 'HTTPS') == 0) {
return $this->_sendHTTPS($msg, $options);
}
return $this->_raiseSoapFault('Invalid url scheme '.$this->url);
}
/**
* set data for http authentication
* creates Authorization header
*
* @param string $username username
* @param string $password response data, minus http headers
*
* @return none
* @access public
*/
function setCredentials($username, $password)
{
$this->headers['Authorization'] = 'Basic ' . base64_encode($username . ':' . $password);
}
/**
* Add a cookie
*
* @access public
* @param string $name cookie name
* @param mixed $value cookie value
* @return void
*/
function addCookie($name, $value)
{
$this->cookies[$name]=$value;
}
// private methods
/**
* Generates the correct headers for the cookies
*
* @access private
* @return void
*/
function _genCookieHeader()
{
foreach ($this->cookies as $name=>$value) {
$cookies = (isset($cookies) ? $cookies. '; ' : '') .
urlencode($name) . '=' . urlencode($value);
}
return $cookies;
}
/**
* validate url data passed to constructor
*
* @access private
* @return boolean
*/
function _validateUrl()
{
if ( ! is_array($this->urlparts) ) {
$this->_raiseSoapFault("Unable to parse URL " . $this->url);
return false;
}
if (!isset($this->urlparts['host'])) {
$this->_raiseSoapFault("No host in URL " . $this->url);
return false;
}
if (!isset($this->urlparts['port'])) {
if (strcasecmp($this->urlparts['scheme'], 'HTTP') == 0)
$this->urlparts['port'] = 80;
else if (strcasecmp($this->urlparts['scheme'], 'HTTPS') == 0)
$this->urlparts['port'] = 443;
}
if (isset($this->urlparts['user'])) {
$this->setCredentials(urldecode($this->urlparts['user']),
urldecode($this->urlparts['pass']));
}
if (!isset($this->urlparts['path']) || !$this->urlparts['path'])
$this->urlparts['path'] = '/';
return true;
}
/**
* Finds out what is the encoding.
*
* Sets the object property accordingly.
*
* @access private
* @param array $headers headers
* @return void
*/
function _parseEncoding($headers)
{
$h = stristr($headers, 'Content-Type');
preg_match_all('/^Content-Type:\s*(.*)$/im', $h, $ct, PREG_SET_ORDER);
$n = count($ct);
$ct = $ct[$n - 1];
$this->result_content_type = str_replace("\r", '', $ct[1]);
if (preg_match('/(.*?)(?:;\s?charset=)(.*)/i', $this->result_content_type, $m)) {
// strip the string of \r
$this->result_content_type = $m[1];
if (count($m) > 2) {
$enc = strtoupper(str_replace('"', '', $m[2]));
if (in_array($enc, $this->_encodings)) {
$this->result_encoding = $enc;
}
}
}
// deal with broken servers that don't set content type on faults
if (!$this->result_content_type) $this->result_content_type = 'text/xml';
}
/**
* Parses the headers
*
* @param array $headers the headers
* @return void
*/
function _parseHeaders($headers)
{
/* largely borrowed from HTTP_Request */
$this->result_headers = array();
$headers = split("\r?\n", $headers);
foreach ($headers as $value) {
if (strpos($value,':') === false) {
$this->result_headers[0]=$value;
continue;
}
list($name,$value) = split(':',$value);
$headername = strtolower($name);
$headervalue = trim($value);
$this->result_headers[$headername]=$headervalue;
if ($headername == 'set-cookie') {
// Parse a SetCookie header to fill _cookies array
$cookie = array(
'expires' => null,
'domain' => $this->urlparts['host'],
'path' => null,
'secure' => false
);
// Only a name=value pair
if (!strpos($headervalue, ';')) {
list($cookie['name'], $cookie['value']) = array_map('trim', explode('=', $headervalue));
$cookie['name'] = urldecode($cookie['name']);
$cookie['value'] = urldecode($cookie['value']);
// Some optional parameters are supplied
} else {
$elements = explode(';', $headervalue);
list($cookie['name'], $cookie['value']) = array_map('trim', explode('=', $elements[0]));
$cookie['name'] = urldecode($cookie['name']);
$cookie['value'] = urldecode($cookie['value']);
for ($i = 1; $i < count($elements);$i++) {
list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
if ('secure' == $elName) {
$cookie['secure'] = true;
} elseif ('expires' == $elName) {
$cookie['expires'] = str_replace('"', '', $elValue);
} elseif ('path' == $elName OR 'domain' == $elName) {
$cookie[$elName] = urldecode($elValue);
} else {
$cookie[$elName] = $elValue;
}
}
}
$this->result_cookies[] = $cookie;
}
}
}
/**
* Remove http headers from response
*
* @return boolean
* @access private
*/
function _parseResponse()
{
if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $this->incoming_payload, $match)) {
#$this->response = preg_replace("/[\r|\n]/", '', $match[2]);
// find the response error, some servers response with 500 for soap faults
//Check if proxy headers are found
//If found, ignore those headers
if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $match[2], $match1))
{
if($match1[2] != '')
{
$match[1] = $match1[1];
$match[2] = $match1[2];
}
}
$this->response =& $match[2];
// find the response error, some servers response with 500 for soap faults
$this->_parseHeaders($match[1]);
list($protocol, $code, $msg) = sscanf($this->result_headers[0], '%s %s %s');
unset($this->result_headers[0]);
switch($code) {
case 100: // Continue
$this->incoming_payload = $match[2];
return $this->_parseResponse();
case 400:
$this->_raiseSoapFault("HTTP Response $code Bad Request");
return false;
break;
case 401:
$this->_raiseSoapFault("HTTP Response $code Authentication Failed");
return false;
break;
case 403:
$this->_raiseSoapFault("HTTP Response $code Forbidden");
return false;
break;
case 404:
$this->_raiseSoapFault("HTTP Response $code Not Found");
return false;
break;
case 407:
$this->_raiseSoapFault("HTTP Response $code Proxy Authentication Required");
return false;
break;
case 408:
$this->_raiseSoapFault("HTTP Response $code Request Timeout");
return false;
break;
case 410:
$this->_raiseSoapFault("HTTP Response $code Gone");
return false;
break;
default:
if ($code >= 400 && $code < 500) {
$this->_raiseSoapFault("HTTP Response $code Not Found, Server message: $msg");
return false;
}
}
$this->_parseEncoding($match[1]);
if ($this->result_content_type == 'application/dime') {
// XXX quick hack insertion of DIME
if (PEAR::isError($this->_decodeDIMEMessage($this->response,$this->headers,$this->attachments))) {
// _decodeDIMEMessage already raised $this->fault
return false;
}
$this->result_content_type = $this->headers['content-type'];
} else if (stristr($this->result_content_type,'multipart/related')) {
$this->response = $this->incoming_payload;
if (PEAR::isError($this->_decodeMimeMessage($this->response,$this->headers,$this->attachments))) {
// _decodeMimeMessage already raised $this->fault
return false;
}
} else if ($this->result_content_type != 'text/xml') {
$this->_raiseSoapFault($this->response);
return false;
}
// if no content, return false
return strlen($this->response) > 0;
}
$this->_raiseSoapFault('Invalid HTTP Response');
return false;
}
/**
* Create http request, including headers, for outgoing request
*
* @param string &$msg outgoing SOAP package
* @param $options
* @return string outgoing_payload
* @access private
*/
function &_getRequest(&$msg, $options)
{
$action = isset($options['soapaction'])?$options['soapaction']:'';
$fullpath = $this->urlparts['path'].
(isset($this->urlparts['query'])?'?'.$this->urlparts['query']:'').
(isset($this->urlparts['fragment'])?'#'.$this->urlparts['fragment']:'');
if (isset($options['proxy_host'])) {
$fullpath = 'http://' . $this->urlparts['host'] . ':' . $this->urlparts['port'] . $fullpath;
}
if (isset($options['proxy_user'])) {
$this->headers['Proxy-Authorization'] = 'Basic ' . base64_encode($options['proxy_user'].":".$options['proxy_pass']);
}
if (isset($options['user'])) {
$this->setCredentials($options['user'], $options['pass']);
}
$this->headers['User-Agent'] = $this->_userAgent;
$this->headers['Host'] = $this->urlparts['host'];
$this->headers['Content-Type'] = "text/xml; charset=$this->encoding";
$this->headers['Content-Length'] = strlen($msg);
$this->headers['SOAPAction'] = "\"$action\"";
if (isset($options['headers'])) {
$this->headers = array_merge($this->headers, $options['headers']);
}
$this->cookies = array();
if (!isset($options['nocookies']) || !$options['nocookies']) {
// add the cookies we got from the last request
if (isset($this->result_cookies)) {
foreach ($this->result_cookies as $cookie) {
if ($cookie['domain'] == $this->urlparts['host'])
$this->cookies[$cookie['name']]=$cookie['value'];
}
}
}
// add cookies the user wants to set
if (isset($options['cookies'])) {
foreach ($options['cookies'] as $cookie) {
if ($cookie['domain'] == $this->urlparts['host'])
$this->cookies[$cookie['name']]=$cookie['value'];
}
}
if (count($this->cookies)) {
$this->headers['Cookie'] = $this->_genCookieHeader();
}
$headers = '';
foreach ($this->headers as $k => $v) {
$headers .= "$k: $v\r\n";
}
$this->outgoing_payload =
"POST $fullpath HTTP/1.0\r\n".
$headers."\r\n".
$msg;
return $this->outgoing_payload;
}
/**
* Send outgoing request, and read/parse response
*
* @param string &$msg outgoing SOAP package
* @param string $action SOAP Action
* @return string &$response response data, minus http headers
* @access private
*/
function &_sendHTTP(&$msg, $options)
{
$this->incoming_payload = '';
$this->_getRequest($msg, $options);
$host = $this->urlparts['host'];
$port = $this->urlparts['port'];
if (isset($options['proxy_host'])) {
$host = $options['proxy_host'];
$port = isset($options['proxy_port']) ? $options['proxy_port'] : 8080;
}
// send
if ($this->timeout > 0) {
$fp = @fsockopen($host, $port, $this->errno, $this->errmsg, $this->timeout);
} else {
$fp = @fsockopen($host, $port, $this->errno, $this->errmsg);
}
if (!$fp) {
return $this->_raiseSoapFault("Connect Error to $host:$port");
}
if ($this->timeout > 0) {
// some builds of php do not support this, silence
// the warning
@socket_set_timeout($fp, $this->timeout);
}
if (!fputs($fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
return $this->_raiseSoapFault("Error POSTing Data to $host");
}
// get reponse
// XXX time consumer
do {
$data = fread($fp, 4096);
$_tmp_status = socket_get_status($fp);
if ($_tmp_status['timed_out']) {
return $this->_raiseSoapFault("Timed out read from $host");
} else {
$this->incoming_payload .= $data;
}
} while (!$_tmp_status['eof']);
fclose($fp);
if (!$this->_parseResponse()) {
return $this->fault;
}
return $this->response;
}
/**
* Send outgoing request, and read/parse response, via HTTPS
*
* @param string &$msg outgoing SOAP package
* @param string $action SOAP Action
* @return string &$response response data, minus http headers
* @access private
*/
function &_sendHTTPS(&$msg, $options)
{
global $authstringvar;
/* NOTE This function uses the CURL functions
* Your php must be compiled with CURL
*/
//adding proxy supprt for HTTPS connections.
//if USE_PROXY set to TRUE in SDKProxyProperties.php(php-sdk\lib\PayPal),
//then only proxy is setted.
if(USE_PROXY){
$options['proxy_host'] = PROXY_HOST;
$options['proxy_port']= PROXY_PORT;
$options['proxy_user'] = PROXY_USER;
$options['proxy_pass']= PROXY_PASSWORD;
}
if (!extension_loaded('curl')) {
return $this->_raiseSoapFault('CURL Extension is required for HTTPS');
}
$ch = curl_init();
if (isset($options['proxy_host'])) {
// $options['http_proxy'] == 'hostname:port'
$host = $options['proxy_host'];
$port = isset($options['proxy_port']) ? $options['proxy_port'] : 8080;
curl_setopt($ch, CURLOPT_PROXY, $host . ":" . $port);
}
if (isset($options['proxy_user'])) {
// $options['http_proxy_userpw'] == 'username:password'
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $options['proxy_user'] . ':' . $options['proxy_pass']);
}
if (isset($options['user'])) {
curl_setopt($ch, CURLOPT_USERPWD, $options['user'] . ':' . $options['pass']);
}
if (!isset($options['soapaction'])) {
$options['soapaction'] = '';
}
$tst1= $authstringvar;
//send permission credential as http headers
// $tmp=$profile->_authSignature;
// $authstring=$this->buildAuthString($profile->_authToken,$this->_profile->_authSignature,$this->_profile->_authTimestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER , array('Content-Type: text/xml;charset=' . $this->encoding, 'SOAPAction: "'.$options['soapaction'].'"',$authstringvar));
curl_setopt($ch, CURLOPT_USERAGENT , $this->_userAgent);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if ($this->timeout) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); //times out after 4s
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
if (defined('CURLOPT_HTTP_VERSION')) {
curl_setopt($ch, CURLOPT_HTTP_VERSION, 1);
}
if (isset($options['curl'])) {
foreach ($options['curl'] as $key => $val) {
curl_setopt($ch, $key, $val);
}
}
// Save the outgoing XML. This doesn't quite match _sendHTTP
// as CURL generates the headers, but having the XML is
// usually the most important part for tracing/debugging.
$this->outgoing_payload = $msg;
$this->incoming_payload = curl_exec($ch);
if (!$this->incoming_payload) {
$m = 'curl_exec error ' . curl_errno($ch) . ' ' . curl_error($ch);
curl_close($ch);
return $this->_raiseSoapFault($m);
}
curl_close($ch);
if (!$this->_parseResponse()) {
return $this->fault;
}
return $this->response;
}
function buildAuthString($auth_token,$auth_signature,$auth_timestamp)
{
$authString="token=".$auth_token.",signature=".$auth_signature.",timestamp=".$auth_timestamp ;
return $authString;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Transport/HTTP.php | PHP | asf20 | 22,806 |
<?php
function underscore_replace($soap_data){
$replacement = array('cpp_header_image' => 'cpp-header-image');
foreach ($replacement as $key => $value) {
$soap_data = str_replace($key,$value,$soap_data);
}
return $soap_data;
}
?>
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/PatternReplace.php | PHP | asf20 | 251 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: Transport.php,v 1.1 2011/09/18 05:16:04 iling Exp $
//
require_once 'PayPal/SOAP/Base.php';
/**
* SOAP Transport Layer
*
* This layer can use different protocols dependant on the endpoint url provided
* no knowlege of the SOAP protocol is available at this level
* no knowlege of the transport protocols is available at this level
*
* @access public
* @package SOAP::Transport
* @author Shane Caraveo <shane@php.net>
*/
class SOAP_Transport
{
function &getTransport($url, $encoding = SOAP_DEFAULT_ENCODING)
{
$urlparts = @parse_url($url);
if (!$urlparts['scheme']) {
return SOAP_Base_Object::_raiseSoapFault("Invalid transport URI: $url");
}
if (strcasecmp($urlparts['scheme'], 'mailto') == 0) {
$transport_type = 'SMTP';
} elseif (strcasecmp($urlparts['scheme'], 'https') == 0) {
$transport_type = 'HTTP';
} else {
/* handle other transport types */
$transport_type = strtoupper($urlparts['scheme']);
}
$transport_include = 'PayPal/SOAP/Transport/' . $transport_type . '.php';
$res = @include_once($transport_include);
if (!$res && !in_array($transport_include, get_included_files())) {
return SOAP_Base_Object::_raiseSoapFault("No Transport for {$urlparts['scheme']}");
}
$transport_class = "SOAP_Transport_$transport_type";
if (!class_exists($transport_class)) {
return SOAP_Base_Object::_raiseSoapFault("No Transport class $transport_class");
}
$t =& new $transport_class($url, $encoding);
return $t;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Transport.php | PHP | asf20 | 2,956 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: Client.php,v 1.1 2011/09/18 05:16:03 iling Exp $
//
require_once 'PayPal/SOAP/Value.php';
require_once 'PayPal/SOAP/Base.php';
require_once 'PayPal/SOAP/Transport.php';
require_once 'PayPal/SOAP/WSDL.php';
require_once 'PayPal/SOAP/Fault.php';
require_once 'PayPal/SOAP/Parser.php';
require_once 'PayPal/SOAP/PatternReplace.php';
// Arnaud: the following code was taken from DataObject
// and adapted to suit
// this will be horrifically slow!!!!
// NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer
// these two are BC/FC handlers for call in PHP4/5
if (!class_exists('SOAP_Client_Overload')) {
if (substr(phpversion(), 0, 1) == 5) {
class SOAP_Client_Overload extends SOAP_Base
{
function __call($method, $args)
{
$return = null;
$this->_call($method, $args, $return);
return $return;
}
}
} else {
if (!function_exists('clone')) {
eval('function clone($t) { return $t; }');
}
eval('
class SOAP_Client_Overload extends SOAP_Base
{
function __call($method, $args, &$return)
{
return $this->_call($method, $args, $return);
}
}');
}
}
/**
* SOAP Client Class
*
* This class is the main interface for making soap requests.
*
* basic usage:
* $soapclient = new SOAP_Client( string path [ , boolean wsdl] );
* echo $soapclient->call( string methodname [ , array parameters] );
*
* Originally based on SOAPx4 by Dietrich Ayala
* http://dietrich.ganx4.com/soapx4
*
* @access public
* @package SOAP::Client
* @author Shane Caraveo <shane@php.net> Conversion to PEAR and updates
* @author Stig Bakken <ssb@fast.no> Conversion to PEAR
* @author Dietrich Ayala <dietrich@ganx4.com> Original Author
*/
class SOAP_Client extends SOAP_Client_Overload
{
/**
* Communication endpoint.
*
* Currently the following transport formats are supported:
* - HTTP
* - SMTP
*
* Example endpoints:
* http://www.example.com/soap/server.php
* https://www.example.com/soap/server.php
* mailto:soap@example.com
*
* @var string
* @see SOAP_Client()
*/
var $_endpoint = '';
/**
* portname
*
* @var string contains the SOAP PORT name that is used by the client
*/
var $_portName = '';
/**
* Endpoint type
*
* @var string e.g. wdsl
*/
var $__endpointType = '';
/**
* wire
*
* @var string contains outoing and incoming data stream for debugging.
*/
var $xml; // contains the received xml
var $wire;
var $__last_request = null;
var $__last_response = null;
/**
* Options
*
* @var array
*/
var $__options = array('trace'=>0);
/**
* encoding
*
* @var string Contains the character encoding used for XML parser, etc.
*/
var $_encoding = SOAP_DEFAULT_ENCODING;
/**
* headersOut
*
* @var array contains an array of SOAP_Headers that we are sending
*/
var $headersOut = null;
/**
* headersOut
*
* @var array contains an array headers we recieved back in the response
*/
var $headersIn = null;
/**
* __proxy_params
*
* @var array contains options for HTTP_Request class (see HTTP/Request.php)
*/
var $__proxy_params = array();
var $_soap_transport = null;
/**
* SOAP_Client constructor
*
* @param string endpoint (URL)
* @param boolean wsdl (true if endpoint is a wsdl file)
* @param string portName
* @param array contains options for HTTP_Request class (see HTTP/Request.php)
* @access public
*/
function SOAP_Client($endpoint, $wsdl = false, $portName = false, $proxy_params=array())
{
parent::SOAP_Base('Client');
$this->_endpoint = $endpoint;
$this->_portName = $portName;
$this->__proxy_params = $proxy_params;
$wsdl = $wsdl ? $wsdl : strcasecmp('wsdl', substr($endpoint, strlen($endpoint) - 4)) == 0;
// make values
if ($wsdl) {
$this->__endpointType = 'wsdl';
// instantiate wsdl class
$this->_wsdl =& new SOAP_WSDL($this->_endpoint, $this->__proxy_params);
if ($this->_wsdl->fault) {
$this->_raiseSoapFault($this->_wsdl->fault);
}
}
}
function _reset()
{
$this->xml = null;
$this->wire = null;
$this->__last_request = null;
$this->__last_response = null;
$this->headersIn = null;
$this->headersOut = null;
}
/**
* setEncoding
*
* set the character encoding, limited to 'UTF-8', 'US_ASCII' and 'ISO-8859-1'
*
* @param string encoding
* @return mixed returns null or SOAP_Fault
* @access public
*/
function setEncoding($encoding)
{
if (in_array($encoding, $this->_encodings)) {
$this->_encoding = $encoding;
return null;
}
return $this->_raiseSoapFault('Invalid Encoding');
}
/**
* addHeader
*
* To add headers to the envelop, you use this function, sending it a
* SOAP_Header class instance.
*
* @param SOAP_Header a soap value to send as a header
* @access public
*/
function addHeader(&$soap_value)
{
# add a new header to the message
if (is_a($soap_value,'soap_header')) {
$this->headersOut[] =& $soap_value;
} else if (gettype($soap_value) == 'array') {
// name, value, namespace, mustunderstand, actor
$this->headersOut[] =& new SOAP_Header($soap_value[0], null, $soap_value[1], $soap_value[2], $soap_value[3]);;
} else {
$this->_raiseSoapFault("Don't understand the header info you provided. Must be array or SOAP_Header.");
}
}
/**
* SOAP_Client::call
*
* the namespace parameter is overloaded to accept an array of
* options that can contain data necessary for various transports
* if it is used as an array, it MAY contain a namespace value and a
* soapaction value. If it is overloaded, the soapaction parameter is
* ignored and MUST be placed in the options array. This is done
* to provide backwards compatibility with current clients, but
* may be removed in the future.
*
* @param string method
* @param array params
* @param array options (hash with namespace, soapaction, timeout, from, subject, etc.)
*
* The options parameter can have a variety of values added. The currently supported
* values are:
* namespace
* soapaction
* timeout (http socket timeout)
* from (smtp)
* transfer-encoding (smtp, sets the Content-Transfer-Encoding header)
* subject (smtp, subject header)
* headers (smtp, array-hash of extra smtp headers)
*
* @return array of results
* @access public
*/
function &call($method, &$params, $namespace = false, $soapAction = false)
{
$this->headersIn = null;
$this->__last_request = null;
$this->__last_response = null;
$this->wire = null;
$this->xml = null;
$soap_data =& $this->__generate($method, $params, $namespace, $soapAction);
if (PEAR::isError($soap_data)) {
return $this->_raiseSoapFault($soap_data);
}
// __generate may have changed the endpoint if the wsdl has more
// than one service, so we need to see if we need to generate
// a new transport to hook to a different URI. Since the transport
// protocol can also change, we need to get an entirely new object,
// though this could probably be optimized.
if (!$this->_soap_transport || $this->_endpoint != $this->_soap_transport->url) {
$this->_soap_transport =& SOAP_Transport::getTransport($this->_endpoint);
if (PEAR::isError($this->_soap_transport)) {
$fault =& $this->_soap_transport;
$this->_soap_transport = null;
return $this->_raiseSoapFault($fault);
}
}
$this->_soap_transport->encoding = $this->_encoding;
// Send the message.
$transport_options = array_merge_recursive($this->__proxy_params, $this->__options);
// This is to replace "_" by "-" since wsdl has "-" and not "_" (see NOTE in Readme.html)
if(file_exists(dirname(__FILE__) . '/PatternReplace.php')){
$soap_data = underscore_replace($soap_data);
}
$this->xml =& $this->_soap_transport->send($soap_data, $transport_options);
// Save the wire information for debugging.
if ($this->__options['trace'] > 0) {
$this->__last_request =& $this->_soap_transport->outgoing_payload;
$this->__last_response =& $this->_soap_transport->incoming_payload;
$this->wire =& $this->__get_wire();
}
if ($this->_soap_transport->fault) {
return $this->_raiseSoapFault($this->xml);
}
$this->__attachments =& $this->_soap_transport->attachments;
$this->__result_encoding = $this->_soap_transport->result_encoding;
if (isset($this->__options['result']) && $this->__options['result'] != 'parse') {
return $this->xml;
}
return $this->__parse($this->xml, $this->__result_encoding, $this->__attachments);
}
/**
* Sets option to use with the transports layers.
*
* An example of such use is
* $soapclient->setOpt('curl', CURLOPT_VERBOSE, 1)
* to pass a specific option to when using an SSL connection.
*
* @access public
* @param string $category category to which the option applies
* @param string $option option name
* @param string $value option value
* @return void
*/
function setOpt($category, $option, $value = null)
{
if (!is_null($value)) {
if (!isset($this->__options[$category])) {
$this->__options[$category] = array();
}
$this->__options[$category][$option] = $value;
} else {
$this->__options[$category] = $option;
}
}
/**
* Overload extension support
* if the overload extension is loaded, you can call the client class
* with a soap method name
* $soap = new SOAP_Client(....);
* $value = $soap->getStockQuote('MSFT');
*
* @param string method
* @param array args
* @param string retur_value
*
* @return boolean
* @access public
*/
function _call($method, $args, &$return_value)
{
// XXX overloading lowercases the method name, we
// need to look into the wsdl and try to find
// the correct method name to get the correct
// case for the call.
if ($this->_wsdl) {
$this->_wsdl->matchMethod($method);
}
$return_value =& $this->call($method, $args);
return true;
}
function &__getlastrequest()
{
return $this->__last_request;
}
function &__getlastresponse()
{
return $this->__last_response;
}
function __use($use)
{
$this->__options['use'] = $use;
}
function __style($style)
{
$this->__options['style'] = $style;
}
function __trace($level)
{
$this->__options['trace'] = $level;
}
function &__generate($method, &$params, $namespace = false, $soapAction = false)
{
$this->fault = null;
$this->__options['input']='parse';
$this->__options['result']='parse';
$this->__options['parameters'] = false;
if ($params && gettype($params) != 'array') {
$params = array($params);
}
if (gettype($namespace) == 'array') {
foreach ($namespace as $optname => $opt) {
$this->__options[strtolower($optname)] = $opt;
}
if (isset($this->__options['namespace'])) {
$namespace = $this->__options['namespace'];
} else {
$namespace = false;
}
} else {
// we'll place soapaction into our array for usage in the transport
$this->__options['soapaction'] = $soapAction;
$this->__options['namespace'] = $namespace;
}
if ($this->__endpointType == 'wsdl') {
$this->_setSchemaVersion($this->_wsdl->xsd);
// get portName
if (!$this->_portName) {
$this->_portName = $this->_wsdl->getPortName($method);
}
if (PEAR::isError($this->_portName)) {
return $this->_raiseSoapFault($this->_portName);
}
// get endpoint
$this->_endpoint = $this->_wsdl->getEndpoint($this->_portName);
if (PEAR::isError($this->_endpoint)) {
return $this->_raiseSoapFault($this->_endpoint);
}
// get operation data
$opData = $this->_wsdl->getOperationData($this->_portName, $method);
if (PEAR::isError($opData)) {
return $this->_raiseSoapFault($opData);
}
$namespace = $opData['namespace'];
$this->__options['style'] = $opData['style'];
$this->__options['use'] = $opData['input']['use'];
$this->__options['soapaction'] = $opData['soapAction'];
// set input params
if ($this->__options['input'] == 'parse') {
$this->__options['parameters'] = $opData['parameters'];
$nparams = array();
if (isset($opData['input']['parts']) && count($opData['input']['parts']) > 0) {
$i = 0;
reset($params);
foreach ($opData['input']['parts'] as $name => $part) {
$xmlns = '';
$attrs = array();
// is the name actually a complex type?
if (isset($part['element'])) {
$xmlns = $this->_wsdl->namespaces[$part['namespace']];
$part = $this->_wsdl->elements[$part['namespace']][$part['type']];
$name = $part['name'];
}
if (array_key_exists($name, $params) ||
$this->_wsdl->getDataHandler($name, $part['namespace'])) {
$nparams[$name] =& $params[$name];
} else {
// we now force an associative array for
// parameters if using wsdl.
return $this->_raiseSoapFault("The named parameter $name is not in the call parameters.");
}
if (gettype($nparams[$name]) != 'object' ||
!is_a($nparams[$name],'soap_value')) {
// type is a qname likely, split it apart, and get the type namespace from wsdl
$qname =& new QName($part['type']);
if ($qname->ns) {
$type_namespace = $this->_wsdl->namespaces[$qname->ns];
} else if (isset($part['namespace'])) {
$type_namespace = $this->_wsdl->namespaces[$part['namespace']];
} else {
$type_namespace = null;
}
$qname->namespace = $type_namespace;
$type = $qname->name;
$pqname = $name;
if ($xmlns) {
$pqname = '{' . $xmlns . '}' . $name;
}
$nparams[$name] =& new SOAP_Value($pqname, $qname->fqn(), $nparams[$name], $attrs);
} else {
// wsdl fixups to the soap value.
}
}
}
$params =& $nparams;
unset($nparams);
}
} else {
$this->_setSchemaVersion(SOAP_XML_SCHEMA_VERSION);
}
// serialize the message.
$this->_section5 = (isset($this->__options['use']) && $this->__options['use'] == 'literal');
if (!isset($this->__options['style']) || $this->__options['style'] == 'rpc') {
$this->__options['style'] = 'rpc';
$this->docparams = true;
$mqname =& new QName($method, $namespace);
$methodValue =& new SOAP_Value($mqname->fqn(), 'Struct', $params);
$soap_msg =& $this->_makeEnvelope($methodValue, $this->headersOut, $this->_encoding, $this->__options);
} else {
if (!$params) {
$mqname =& new QName($method, $namespace);
$mynull = null;
$params =& new SOAP_Value($mqname->fqn(), 'Struct', $mynull);
} elseif ($this->__options['input'] == 'parse') {
if (is_array($params)) {
$nparams = array();
$keys = array_keys($params);
foreach ($keys as $k) {
if (gettype($params[$k]) != 'object') {
$nparams[] =& new SOAP_Value($k, false, $params[$k]);
} else {
$nparams[] =& $params[$k];
}
}
$params =& $nparams;
}
if ($this->__options['parameters']) {
$mqname =& new QName($method, $namespace);
$params =& new SOAP_Value($mqname->fqn(), 'Struct', $params);
}
}
$soap_msg =& $this->_makeEnvelope($params, $this->headersOut, $this->_encoding, $this->__options);
}
unset($this->headersOut);
if (PEAR::isError($soap_msg)) {
return $this->_raiseSoapFault($soap_msg);
}
// handle Mime or DIME encoding
// XXX DIME Encoding should move to the transport, do it here for now
// and for ease of getting it done
if (count($this->__attachments)) {
if ((isset($this->__options['attachments']) && $this->__options['attachments'] == 'Mime') || isset($this->__options['Mime'])) {
$soap_msg =& $this->_makeMimeMessage($soap_msg, $this->_encoding);
} else {
// default is dime
$soap_msg =& $this->_makeDIMEMessage($soap_msg, $this->_encoding);
$this->__options['headers']['Content-Type'] = 'application/dime';
}
if (PEAR::isError($soap_msg)) {
return $this->_raiseSoapFault($soap_msg);
}
}
// instantiate client
if (is_array($soap_msg)) {
$soap_data =& $soap_msg['body'];
if (count($soap_msg['headers'])) {
if (isset($this->__options['headers'])) {
$this->__options['headers'] = array_merge($this->__options['headers'], $soap_msg['headers']);
} else {
$this->__options['headers'] = $soap_msg['headers'];
}
}
} else {
$soap_data =& $soap_msg;
}
return $soap_data;
}
function &__parse(&$response, $encoding, &$attachments)
{
// parse the response
$response =& new SOAP_Parser($response, $encoding, $attachments);
if ($response->fault) {
return $this->_raiseSoapFault($response->fault);
}
// return array of parameters
$return =& $response->getResponse();
$headers =& $response->getHeaders();
if ($headers) {
$this->headersIn =& $this->__decodeResponse($headers, false);
}
return $this->__decodeResponse($return);
}
function &__decodeResponse(&$response, $shift = true)
{
if (!$response) {
return null;
}
// Check for valid response.
if (PEAR::isError($response)) {
return $this->_raiseSoapFault($response);
} elseif (!is_a($response, 'soap_value')) {
return $this->_raiseSoapFault("didn't get SOAP_Value object back from client");
}
// Decode to native php datatype.
$returnArray =& $this->_decode($response);
// Fault?
if (PEAR::isError($returnArray)) {
return $this->_raiseSoapFault($returnArray);
}
if (is_object($returnArray) && strcasecmp(get_class($returnArray),'stdClass') == 0) {
$returnArray = get_object_vars($returnArray);
}
if (is_array($returnArray)) {
if (isset($returnArray['faultcode']) || isset($returnArray['SOAP-ENV:faultcode'])) {
$faultcode = $faultstring = $faultdetail = $faultactor = '';
foreach ($returnArray as $k => $v) {
if (stristr($k, 'faultcode')) $faultcode = $v;
if (stristr($k, 'faultstring')) $faultstring = $v;
if (stristr($k, 'detail')) $faultdetail = $v;
if (stristr($k, 'faultactor')) $faultactor = $v;
}
return $this->_raiseSoapFault($faultstring, $faultdetail, $faultactor, $faultcode);
}
// Return array of return values.
if ($shift && count($returnArray) == 1) {
return array_shift($returnArray);
}
return $returnArray;
}
return $returnArray;
}
function __get_wire()
{
if ($this->__options['trace'] > 0 && ($this->__last_request || $this->__last_response)) {
return "OUTGOING:\n\n".
$this->__last_request.
"\n\nINCOMING\n\n".
preg_replace("/></",">\r\n<", $this->__last_response);
}
return null;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Client.php | PHP | asf20 | 24,320 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Dmitri Vinogradov <dimitri@vinogradov.de> |
// +----------------------------------------------------------------------+
//
// $Id: Disco.php,v 1.1 2011/09/18 05:16:03 iling Exp $
require_once 'PayPal/SOAP/Base.php';
class SOAP_DISCO_Server extends SOAP_Base_Object
{
var $namespaces = array(SCHEMA_WSDL => 'wsdl', SCHEMA_SOAP => 'soap');
var $import_ns = array();
var $wsdl = '';
var $disco = '';
var $_wsdl = array();
var $_disco = array();
var $_service_name = '';
var $_service_ns = '';
var $_service_desc = '';
var $_portname = '';
var $_bindingname = '';
var $soap_server = NULL;
function SOAP_DISCO_Server($soap_server, $service_name, $service_desc = '', $import_ns = null)
{
parent::SOAP_Base_Object('Server');
if ( !is_object($soap_server)
|| !get_class($soap_server) == 'soap_server') return;
$this->_service_name = $service_name;
$this->_service_ns = "urn:$service_name";
$this->_service_desc = $service_desc;
$this->import_ns = isset($import_ns) ? $import_ns : $this->import_ns;
$this->soap_server = $soap_server;
$this->host = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'localhost';
}
function getDISCO()
{
$this->_generate_DISCO();
return $this->disco;
}
function getWSDL()
{
$this->_generate_WSDL();
return $this->wsdl;
}
function _generate_DISCO()
{
# DISCO
$this->_disco['disco:discovery']['attr']['xmlns:disco'] = SCHEMA_DISCO;
$this->_disco['disco:discovery']['attr']['xmlns:scl'] = SCHEMA_DISCO_SCL;
$this->_disco['disco:discovery']['scl:contractRef']['attr']['ref'] =
(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS']=='on')
? 'https://' . $this->host . $_SERVER['PHP_SELF'] . '?wsdl'
: 'http://' . $this->host . $_SERVER['PHP_SELF'] . '?wsdl';
# generate disco xml
$this->_generate_DISCO_XML($this->_disco);
}
function _generate_WSDL()
{
# WSDL
if (is_array($this->soap_server->_namespaces)) {
# need to get: typens, xsd & SOAP-ENC
$flipped = array_flip($this->soap_server->_namespaces);
$this->namespaces[$this->_service_ns] = 'tns';
$this->namespaces[$flipped['xsd']] = 'xsd';
$this->namespaces[$flipped['SOAP-ENC']] = 'SOAP-ENC';
}
# DEFINITIONS
$this->_wsdl['definitions']['attr']['name'] = $this->_service_name;
$this->_wsdl['definitions']['attr']['targetNamespace'] = $this->_service_ns;
foreach ($this->namespaces as $ns => $prefix) {
$this->_wsdl['definitions']['attr']['xmlns:' . $prefix] = $ns;
}
$this->_wsdl['definitions']['attr']['xmlns'] = SCHEMA_WSDL;
# import namespaces
# seems to not work yet: wsdl.exe fom .NET cant handle imported complete wsdl-definitions
#
if (count($this->import_ns)>0) {
$i = 0;
foreach ($this->import_ns as $_ns => $_location) {
$this->_wsdl['definitions']['import'][$i]['attr']['location'] = $_location;
$this->_wsdl['definitions']['import'][$i]['attr']['namespace'] = $_ns;
$i++;
}
}
$this->_wsdl['definitions']['types']['attr']['xmlns']='http://schemas.xmlsoap.org/wsdl/';
$this->_wsdl['definitions']['types']['schema']=array();
# PORTTYPE-NAME
$this->_portname = $this->_service_name . 'Port';
$this->_wsdl['definitions']['portType']['attr']['name'] = $this->_portname;
# BINDING-NAME
$this->_bindingname = $this->_service_name . 'Binding';
$this->_wsdl['definitions']['binding']['attr']['name'] = $this->_bindingname;
$this->_wsdl['definitions']['binding']['attr']['type'] = 'tns:' . $this->_portname;
$this->_wsdl['definitions']['binding']['soap:binding']['attr']['style'] = 'rpc';
$this->_wsdl['definitions']['binding']['soap:binding']['attr']['transport'] = SCHEMA_SOAP_HTTP;
# SERVICE
$this->_wsdl['definitions']['service']['attr']['name'] = $this->_service_name . 'Service';
$this->_wsdl['definitions']['service']['documentation']['attr'] = '';
$this->_wsdl['definitions']['service']['documentation'] = htmlentities($this->_service_desc);
$this->_wsdl['definitions']['service']['port']['attr']['name'] = $this->_portname;
$this->_wsdl['definitions']['service']['port']['attr']['binding'] = 'tns:' . $this->_bindingname;
$this->_wsdl['definitions']['service']['port']['soap:address']['attr']['location'] =
(array_key_exists('HTTPS',$_SERVER) && $_SERVER['HTTPS']=='on')
? 'https://' . $this->host . $_SERVER['PHP_SELF']
: 'http://' . $this->host . $_SERVER['PHP_SELF'];
#
$dispatch_keys = array_keys($this->soap_server->dispatch_objects);
$dc = count($dispatch_keys);
for ($di=0; $di < $dc; $di++) {
$namespace = $dispatch_keys[$di];
$namespace_objects =& $this->soap_server->dispatch_objects[$namespace];
$oc = count($namespace_objects);
for ($oi = 0; $oi < $oc; $oi++) {
$object = $namespace_objects[$oi];
# types definitions
$this->addSchemaFromMap($object->__typedef);
# MESSAGES
$this->addMethodsFromMap($object->__dispatch_map,$namespace,get_class($object));
}
}
if (isset($server->dispatch_map))
$this->addMethodsFromMap($server->dispatch_map,$namespace);
# generate wsdl
$this->_generate_WSDL_XML($this->_wsdl);
}
function &_getSchema($namespace) {
# SCHEMA
$c = count($this->_wsdl['definitions']['types']['schema']);
for($i = 0; $i < $c; $i++) {
if ($this->_wsdl['definitions']['types']['schema'][$i]['attr']['targetNamespace'] == $namespace)
return $this->_wsdl['definitions']['types']['schema'][$i];
}
# don't have this namespace
$schema = array();
$schema['attr'] = array();
$schema['complexType'] = array();
$schema['attr']['xmlns'] = array_search('xsd',$this->namespaces);
$schema['attr']['targetNamespace'] = $namespace;
$this->_wsdl['definitions']['types']['schema'][] =& $schema;
return $schema;
}
function addSchemaFromMap(&$map) {
if (!$map) return;
foreach ($map as $_type_name => $_type_def) {
list($typens,$type) = $this->_getTypeNs($_type_name);
if ($typens == 'xsd') {
// cannot add to xsd, lets use method_namespace
$typens = 'tns';
}
$schema =& $this->_getSchema(array_search($typens,$this->namespaces));
if (!$this->_ifComplexTypeExists($schema['complexType'], $type)) {
$ctype =& $schema['complexType'][];
$ctype['attr']['name'] = $type;
foreach ($_type_def as $_varname => $_vartype) {
if (!is_int($_varname)) {
list($_vartypens,$_vartype) = $this->_getTypeNs($_vartype);
$ctype['all']['attr'] = '';
$el =& $ctype['all']['element'][];
$el['attr']['name'] = $_varname;
$el['attr']['type'] = $_vartypens . ':' . $_vartype;
} else {
$ctype['complexContent']['attr'] = '';
$ctype['complexContent']['restriction']['attr']['base'] = 'SOAP-ENC:Array';
foreach ($_vartype as $array_var => $array_type) {
list($_vartypens,$_vartype) = $this->_getTypeNs($array_type);
$ctype['complexContent']['restriction']['attribute']['attr']['ref'] = 'SOAP-ENC:arrayType';
$ctype['complexContent']['restriction']['attribute']['attr']['wsdl:arrayType'] = $_vartypens . ':' . $_vartype . '[]';
}
}
}
}
}
}
function addMethodsFromMap(&$map, $namespace, $classname = null)
{
if (!$map) {
return;
}
foreach ($map as $method_name => $method_types) {
if (array_key_exists('namespace',$method_types)) {
$method_namespace = $method_types['namespace'];
} else {
$method_namespace = $namespace;
}
# INPUT
if (isset($method_types['in']) && is_array($method_types['in'])) {
$input_message =& $this->_wsdl['definitions']['message'][];
$input_message['attr']['name'] = $method_name . 'Request';
foreach ($method_types['in'] as $name => $type) {
list($typens,$type) = $this->_getTypeNs($type);
$part =& $input_message['part'][];
$part['attr']['name'] = $name;
$part['attr']['type'] = $typens . ':' . $type;
}
}
# OUTPUT
if (isset($method_types['out']) && is_array($method_types['out'])) {
$output_message =& $this->_wsdl['definitions']['message'][];
$output_message['attr']['name'] = $method_name . 'Response';
foreach ($method_types['out'] as $name => $type) {
list($typens,$type) = $this->_getTypeNs($type);
$part =& $output_message['part'][];
$part['attr']['name'] = $name;
$part['attr']['type'] = $typens . ':' . $type;
}
}
# PORTTYPES
$operation =& $this->_wsdl['definitions']['portType']['operation'][];
$operation['attr']['name'] = $method_name;
# INPUT
$operation['input']['attr']['message'] = 'tns:'
. $input_message['attr']['name'];
# OUTPUT
$operation['output']['attr']['message'] = 'tns:'
. $output_message['attr']['name'];
# BINDING
$binding =& $this->_wsdl['definitions']['binding']['operation'][];
$binding['attr']['name'] = $method_name;
$action = $method_namespace . '#' . ($classname?$classname . '#':'') . $method_name;
$binding['soap:operation']['attr']['soapAction'] = $action;
# INPUT
$binding['input']['attr'] = '';
$binding['input']['soap:body']['attr']['use'] = 'encoded';
$binding['input']['soap:body']['attr']['namespace'] = $method_namespace;
$binding['input']['soap:body']['attr']['encodingStyle'] = SOAP_SCHEMA_ENCODING;
# OUTPUT
$binding['output']['attr'] = '';
$binding['output']['soap:body']['attr']['use'] = 'encoded';
$binding['output']['soap:body']['attr']['namespace'] = $method_namespace;
$binding['output']['soap:body']['attr']['encodingStyle'] = SOAP_SCHEMA_ENCODING;
}
}
function _generate_DISCO_XML($disco_array) {
$disco = '<?xml version="1.0"?>';
foreach ($disco_array as $key => $val) {
$disco .= $this->_arrayToNode($key,$val);
}
$this->disco = $disco;
}
function _generate_WSDL_XML($wsdl_array) {
$wsdl = '<?xml version="1.0"?>';
foreach ($wsdl_array as $key => $val) {
$wsdl .= $this->_arrayToNode($key,$val);
}
$this->wsdl = $wsdl;
}
function _arrayToNode($node_name = '', $array) {
$return = '';
if (is_array($array)) {
# we have a node if there's key 'attr'
if (array_key_exists('attr',$array)) {
$return .= "<$node_name";
if (is_array($array['attr'])) {
foreach ($array['attr'] as $attr_name => $attr_value) {
$return .= " $attr_name=\"$attr_value\"";
}
}
# unset 'attr' and proceed other childs...
unset($array['attr']);
if (count($array) > 0) {
$i = 0;
foreach ($array as $child_node_name => $child_node_value) {
$return .= $i == 0 ? ">\n" : '';
$return .= $this->_arrayToNode($child_node_name,$child_node_value);
$i++;
}
$return .= "</$node_name>\n";
} else {
$return .= " />\n";
}
} else {
# we have no 'attr' key in array - so it's list of nodes with the same name ...
foreach ($array as $child_node_name => $child_node_value) {
$return .= $this->_arrayToNode($node_name,$child_node_value);
}
}
} else {
# $array is not an array
if ($array !='') {
# and its not empty
$return .= "<$node_name>$array</$node_name>\n";
} else {
# and its empty...
$return .= "<$node_name />\n";
}
}
return $return;
}
function _getTypeNs($type) {
preg_match_all("'\{(.*)\}'sm",$type,$m);
if (isset($m[1][0]) && $m[1][0] != '') {
if (!array_key_exists($m[1][0],$this->namespaces)) {
$ns_pref = 'ns' . count($this->namespaces);
$this->namespaces[$m[1][0]] = $ns_pref;
$this->_wsdl['definitions']['attr']['xmlns:' . $ns_pref] = $m[1][0];
}
$typens = $this->namespaces[$m[1][0]];
$type = ereg_replace($m[0][0],'',$type);
} else {
$typens = 'xsd';
}
return array($typens,$type);
}
function _ifComplexTypeExists($typesArray, $type_name) {
if (is_array($typesArray)) {
foreach ($typesArray as $index => $type_data) {
if ($typesArray[$index]['attr']['name'] == $type_name) {
return true;
}
}
}
return false;
}
}
?> | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Disco.php | PHP | asf20 | 16,022 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more |
// | Authors: Dietrich Ayala <dietrich@ganx4.com> Original Author |
// +----------------------------------------------------------------------+
//
// $Id: Fault.php,v 1.1 2011/09/18 05:16:04 iling Exp $
//
require_once('PEAR.php');
/**
* SOAP_Fault
* PEAR::Error wrapper used to match SOAP Faults to PEAR Errors
*
* @package SOAP
* @access public
* @author Shane Caraveo <Shane@Caraveo.com> Port to PEAR and more
* @author Dietrich Ayala <dietrich@ganx4.com> Original Author
*/
class SOAP_Fault extends PEAR_Error
{
/**
* Constructor
*
* @param string message string for fault
* @param mixed the faultcode
* @param mixed see PEAR::ERROR
* @param mixed see PEAR::ERROR
* @param array the userinfo array is used to pass in the
* SOAP actor and detail for the fault
*/
function SOAP_Fault($faultstring = 'unknown error', $faultcode = 'Client', $faultactor=NULL, $detail=NULL, $mode = null, $options = null)
{
parent::PEAR_Error($faultstring, $faultcode, $mode, $options, $detail);
if ($faultactor) $this->error_message_prefix = $faultactor;
}
/**
* message
*
* returns a SOAP_Message class that can be sent as a server response
*
* @return SOAP_Message
* @access public
*/
function message()
{
$msg =& new SOAP_Base();
$params = array();
$params[] =& new SOAP_Value('faultcode', 'QName', 'SOAP-ENV:'.$this->code);
$params[] =& new SOAP_Value('faultstring', 'string', $this->message);
$params[] =& new SOAP_Value('faultactor', 'anyURI', $this->error_message_prefix);
if (isset($this->backtrace)) {
$params[] =& new SOAP_Value('detail', 'string', $this->backtrace);
} else {
$params[] =& new SOAP_Value('detail', 'string', $this->userinfo);
}
$methodValue =& new SOAP_Value('{'.SOAP_ENVELOP.'}Fault', 'Struct', $params);
$headers = NULL;
return $msg->_makeEnvelope($methodValue, $headers);
}
/**
* getFault
*
* returns a simple native php array containing the fault data
*
* @return array
* @access public
*/
function getFault()
{
global $SOAP_OBJECT_STRUCT;
if ($SOAP_OBJECT_STRUCT) {
$fault =& new stdClass();
$fault->faultcode = $this->code;
$fault->faultstring = $this->message;
$fault->faultactor = $this->error_message_prefix;
$fault->detail = $this->userinfo;
return $fault;
}
return array(
'faultcode' => $this->code,
'faultstring' => $this->message,
'faultactor' => $this->error_message_prefix,
'detail' => $this->userinfo
);
}
/**
* getActor
*
* returns the SOAP actor for the fault
*
* @return string
* @access public
*/
function getActor()
{
return $this->error_message_prefix;
}
/**
* getDetail
*
* returns the fault detail
*
* @return string
* @access public
*/
function getDetail()
{
return $this->userinfo;
}
}
?> | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SOAP/Fault.php | PHP | asf20 | 4,531 |
<?php
/**
* @package PayPal
*
* $Id: Error.php,v 1.1 2011/09/18 05:16:15 iling Exp $
*/
/**
* Load parent class.
*/
require_once 'PEAR.php';
/**
* A standard PayPal Error object
*
* @package PayPal
*/
class PayPal_Error extends PEAR_Error {
/**
* Standard error constructor
*
* @param string The error message
* @param int An optional integer error code
*/
function PayPal_Error($message, $errorcode = null)
{
parent::PEAR_error($message, $errorcode);
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/Error.php | PHP | asf20 | 524 |
<?php
/****************************************************
SDKProxyProperties.php
This is the configuration file for the Proxy setup. This file
defines the parameters needed to make an API call through Proxy.
Called by HTTP.php.
****************************************************/
/**
USE_PROXY: Set this variable to TRUE to route all the API requests through proxy.
like define('USE_PROXY',TRUE);
*/
define('USE_PROXY',FALSE);
/**
PROXY_HOST: Set the host name or the IP address of proxy server.
PROXY_PORT: Set proxy port.
PROXY_USER: Set proxy user id (optional)
PROXY_PASSWORD: Set proxy password (optional)
PROXY_HOST,PROXY_PORT,PROXY_USER and PROXY_PASSWORD will be read only if USE_PROXY is set to TRUE
*/
define('PROXY_HOST', '127.0.0.1');
define('PROXY_PORT', '808');
define('PROXY_USER', 'test');
define('PROXY_PASSWORD', 'test');
?> | 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/SDKProxyProperties.php | PHP | asf20 | 878 |
<?php
/**
* File containing the API calling code. Partially generated from the
* WSDL - CallerServices.php.in contains the base file with a
* placeholder for generated functions and the WSDL version.
*
* @package PayPal
*/
/**
* Load files we depend on.
*/
require_once 'PayPal.php';
require_once 'PayPal/SOAP/Client.php';
require_once 'PayPal/Type/XSDSimpleType.php';
require_once 'Log.php';
/**
* The WSDL version the SDK is built against.
*/
define('PAYPAL_WSDL_VERSION', 65.1);
/**
* The WSDL version the SDK is built against.
*/
define('PAYPAL_WSDL_METHODS', 'a:53:{s:17:"RefundTransaction";a:2:{s:5:"param";s:28:"RefundTransactionRequestType";s:6:"result";s:29:"RefundTransactionResponseType";}s:14:"InitiateRecoup";a:2:{s:5:"param";s:25:"InitiateRecoupRequestType";s:6:"result";s:26:"InitiateRecoupResponseType";}s:14:"CompleteRecoup";a:2:{s:5:"param";s:25:"CompleteRecoupRequestType";s:6:"result";s:26:"CompleteRecoupResponseType";}s:12:"CancelRecoup";a:2:{s:5:"param";s:23:"CancelRecoupRequestType";s:6:"result";s:24:"CancelRecoupResponseType";}s:21:"GetTransactionDetails";a:2:{s:5:"param";s:32:"GetTransactionDetailsRequestType";s:6:"result";s:33:"GetTransactionDetailsResponseType";}s:14:"BMCreateButton";a:2:{s:5:"param";s:25:"BMCreateButtonRequestType";s:6:"result";s:26:"BMCreateButtonResponseType";}s:14:"BMUpdateButton";a:2:{s:5:"param";s:25:"BMUpdateButtonRequestType";s:6:"result";s:26:"BMUpdateButtonResponseType";}s:20:"BMManageButtonStatus";a:2:{s:5:"param";s:31:"BMManageButtonStatusRequestType";s:6:"result";s:32:"BMManageButtonStatusResponseType";}s:18:"BMGetButtonDetails";a:2:{s:5:"param";s:29:"BMGetButtonDetailsRequestType";s:6:"result";s:30:"BMGetButtonDetailsResponseType";}s:14:"BMSetInventory";a:2:{s:5:"param";s:25:"BMSetInventoryRequestType";s:6:"result";s:26:"BMSetInventoryResponseType";}s:14:"BMGetInventory";a:2:{s:5:"param";s:25:"BMGetInventoryRequestType";s:6:"result";s:26:"BMGetInventoryResponseType";}s:14:"BMButtonSearch";a:2:{s:5:"param";s:25:"BMButtonSearchRequestType";s:6:"result";s:26:"BMButtonSearchResponseType";}s:8:"BillUser";a:2:{s:5:"param";s:19:"BillUserRequestType";s:6:"result";s:20:"BillUserResponseType";}s:17:"TransactionSearch";a:2:{s:5:"param";s:28:"TransactionSearchRequestType";s:6:"result";s:29:"TransactionSearchResponseType";}s:7:"MassPay";a:2:{s:5:"param";s:18:"MassPayRequestType";s:6:"result";s:19:"MassPayResponseType";}s:19:"BillAgreementUpdate";a:2:{s:5:"param";s:19:"BAUpdateRequestType";s:6:"result";s:20:"BAUpdateResponseType";}s:13:"AddressVerify";a:2:{s:5:"param";s:24:"AddressVerifyRequestType";s:6:"result";s:25:"AddressVerifyResponseType";}s:13:"EnterBoarding";a:2:{s:5:"param";s:24:"EnterBoardingRequestType";s:6:"result";s:25:"EnterBoardingResponseType";}s:18:"GetBoardingDetails";a:2:{s:5:"param";s:29:"GetBoardingDetailsRequestType";s:6:"result";s:30:"GetBoardingDetailsResponseType";}s:19:"CreateMobilePayment";a:2:{s:5:"param";s:30:"CreateMobilePaymentRequestType";s:6:"result";s:31:"CreateMobilePaymentResponseType";}s:15:"GetMobileStatus";a:2:{s:5:"param";s:26:"GetMobileStatusRequestType";s:6:"result";s:27:"GetMobileStatusResponseType";}s:17:"SetMobileCheckout";a:2:{s:5:"param";s:28:"SetMobileCheckoutRequestType";s:6:"result";s:29:"SetMobileCheckoutResponseType";}s:23:"DoMobileCheckoutPayment";a:2:{s:5:"param";s:34:"DoMobileCheckoutPaymentRequestType";s:6:"result";s:35:"DoMobileCheckoutPaymentResponseType";}s:10:"GetBalance";a:2:{s:5:"param";s:21:"GetBalanceRequestType";s:6:"result";s:22:"GetBalanceResponseType";}s:13:"GetPalDetails";a:2:{s:5:"param";s:24:"GetPalDetailsRequestType";s:6:"result";s:25:"GetPalDetailsResponseType";}s:24:"DoExpressCheckoutPayment";a:2:{s:5:"param";s:35:"DoExpressCheckoutPaymentRequestType";s:6:"result";s:36:"DoExpressCheckoutPaymentResponseType";}s:28:"DoUATPExpressCheckoutPayment";a:2:{s:5:"param";s:39:"DoUATPExpressCheckoutPaymentRequestType";s:6:"result";s:40:"DoUATPExpressCheckoutPaymentResponseType";}s:16:"SetAuthFlowParam";a:2:{s:5:"param";s:27:"SetAuthFlowParamRequestType";s:6:"result";s:28:"SetAuthFlowParamResponseType";}s:14:"GetAuthDetails";a:2:{s:5:"param";s:25:"GetAuthDetailsRequestType";s:6:"result";s:26:"GetAuthDetailsResponseType";}s:20:"SetAccessPermissions";a:2:{s:5:"param";s:31:"SetAccessPermissionsRequestType";s:6:"result";s:32:"SetAccessPermissionsResponseType";}s:23:"UpdateAccessPermissions";a:2:{s:5:"param";s:34:"UpdateAccessPermissionsRequestType";s:6:"result";s:35:"UpdateAccessPermissionsResponseType";}s:26:"GetAccessPermissionDetails";a:2:{s:5:"param";s:37:"GetAccessPermissionDetailsRequestType";s:6:"result";s:38:"GetAccessPermissionDetailsResponseType";}s:22:"GetIncentiveEvaluation";a:2:{s:5:"param";s:33:"GetIncentiveEvaluationRequestType";s:6:"result";s:34:"GetIncentiveEvaluationResponseType";}s:18:"SetExpressCheckout";a:2:{s:5:"param";s:29:"SetExpressCheckoutRequestType";s:6:"result";s:30:"SetExpressCheckoutResponseType";}s:25:"GetExpressCheckoutDetails";a:2:{s:5:"param";s:36:"GetExpressCheckoutDetailsRequestType";s:6:"result";s:37:"GetExpressCheckoutDetailsResponseType";}s:15:"DoDirectPayment";a:2:{s:5:"param";s:26:"DoDirectPaymentRequestType";s:6:"result";s:27:"DoDirectPaymentResponseType";}s:30:"ManagePendingTransactionStatus";a:2:{s:5:"param";s:41:"ManagePendingTransactionStatusRequestType";s:6:"result";s:42:"ManagePendingTransactionStatusResponseType";}s:9:"DoCapture";a:2:{s:5:"param";s:20:"DoCaptureRequestType";s:6:"result";s:21:"DoCaptureResponseType";}s:17:"DoReauthorization";a:2:{s:5:"param";s:28:"DoReauthorizationRequestType";s:6:"result";s:29:"DoReauthorizationResponseType";}s:6:"DoVoid";a:2:{s:5:"param";s:17:"DoVoidRequestType";s:6:"result";s:18:"DoVoidResponseType";}s:15:"DoAuthorization";a:2:{s:5:"param";s:26:"DoAuthorizationRequestType";s:6:"result";s:27:"DoAuthorizationResponseType";}s:27:"SetCustomerBillingAgreement";a:2:{s:5:"param";s:38:"SetCustomerBillingAgreementRequestType";s:6:"result";s:39:"SetCustomerBillingAgreementResponseType";}s:34:"GetBillingAgreementCustomerDetails";a:2:{s:5:"param";s:45:"GetBillingAgreementCustomerDetailsRequestType";s:6:"result";s:46:"GetBillingAgreementCustomerDetailsResponseType";}s:22:"CreateBillingAgreement";a:2:{s:5:"param";s:33:"CreateBillingAgreementRequestType";s:6:"result";s:34:"CreateBillingAgreementResponseType";}s:22:"DoReferenceTransaction";a:2:{s:5:"param";s:33:"DoReferenceTransactionRequestType";s:6:"result";s:34:"DoReferenceTransactionResponseType";}s:21:"DoNonReferencedCredit";a:2:{s:5:"param";s:32:"DoNonReferencedCreditRequestType";s:6:"result";s:33:"DoNonReferencedCreditResponseType";}s:19:"DoUATPAuthorization";a:2:{s:5:"param";s:30:"DoUATPAuthorizationRequestType";s:6:"result";s:31:"DoUATPAuthorizationResponseType";}s:30:"CreateRecurringPaymentsProfile";a:2:{s:5:"param";s:41:"CreateRecurringPaymentsProfileRequestType";s:6:"result";s:42:"CreateRecurringPaymentsProfileResponseType";}s:34:"GetRecurringPaymentsProfileDetails";a:2:{s:5:"param";s:45:"GetRecurringPaymentsProfileDetailsRequestType";s:6:"result";s:46:"GetRecurringPaymentsProfileDetailsResponseType";}s:36:"ManageRecurringPaymentsProfileStatus";a:2:{s:5:"param";s:47:"ManageRecurringPaymentsProfileStatusRequestType";s:6:"result";s:48:"ManageRecurringPaymentsProfileStatusResponseType";}s:21:"BillOutstandingAmount";a:2:{s:5:"param";s:32:"BillOutstandingAmountRequestType";s:6:"result";s:33:"BillOutstandingAmountResponseType";}s:30:"UpdateRecurringPaymentsProfile";a:2:{s:5:"param";s:41:"UpdateRecurringPaymentsProfileRequestType";s:6:"result";s:42:"UpdateRecurringPaymentsProfileResponseType";}s:18:"ReverseTransaction";a:2:{s:5:"param";s:29:"ReverseTransactionRequestType";s:6:"result";s:30:"ReverseTransactionResponseType";}}');
/**
* Interface class that wraps all WSDL ports into a unified API for
* the user. Also handles PayPal-specific details like type handling,
* error handling, etc.
*
* @package PayPal
*/
class CallerServices extends SOAP_Client
{
/**
* The profile to use in API calls.
*
* @access protected
*
* @var APIProfile $_profile
*/
var $_profile;
/**
* The portType/environment -> endpoint map.
*
* @access protected
*
* @var array $_endpointMap
*/
var $_endpointMap;
/**
* What level should we log at? Valid levels are:
* PEAR_LOG_ERR - Log only severe errors.
* PEAR_LOG_INFO - (default) Date/time of operation, operation name, elapsed time, success or failure indication.
* PEAR_LOG_DEBUG - Full text of SOAP requests and responses and other debugging messages.
*
* See the PayPal SDK User Guide for more details on these log
* levels.
*
* @access protected
*
* @var integer $_logLevel
*/
var $_logLevel = PEAR_LOG_INFO;
/**
* If we're logging, what directory should we create log files in?
* Note that a log name coincides with a symlink, logging will
* *not* be done to avoid security problems. File names are
* <DateStamp>.PayPal.log.
*
* @access protected
*
* @var string $_logFile
*/
var $_logDir = '/tmp';
/**
* The PEAR Log object we use for logging.
*
* @access protected
*
* @var Log $_logger
*/
var $_logger;
/**
* Construct a new CallerServices object.
*
* @param APIProfile $profile The profile with the username, password,
* and any other information necessary to use
* the SDK.
*/
function CallerServices($profile)
{
// Initialize the SOAP Client.
parent::SOAP_Client(null);
// Store the API profile.
$this->setAPIProfile($profile);
// SSL CA certificate.
// $this->setOpt('curl', CURLOPT_CAINFO, dirname(__FILE__) . '/cert/api_cert_chain.crt');
// SSL Client certificate.
if (isset($profile->_certificateFile)) {
// Set options from the profile.
$this->setOpt('curl', CURLOPT_SSLCERT, $profile->getCertificateFile());
if ($profile->getCertificatePassword()) {
$this->setOpt('curl', CURLOPT_SSLCERTPASSWD, $profile->getCertificatePassword());
}
}
// Tracing.
$this->setOpt('trace', 1);
// Load the endpoint map.
include 'PayPal/wsdl/paypal-endpoints.php';
$this->_endpointMap = $PayPalEndpoints;
// Load SDK settings.
if (@include 'PayPal/conf/paypal-sdk.php') {
if (isset($__PP_CONFIG['log_level'])) {
$this->_logLevel = $__PP_CONFIG['log_level'];
}
if (isset($__PP_CONFIG['log_dir'])) {
$this->_logDir = $__PP_CONFIG['log_dir'];
}
}
}
/**
* Sets the WSDL endpoint based on $portType and on the environment
* set in the user's profile.
*
* @param string $portType The portType the current operation is part of.
* @param string $version The WSDL version being used.
*
* @return boolean | PayPal_Error An error if mapping can't be done, else true.
*/
function setEndpoint($portType, $version)
{
$version = (float)$version;
foreach ($this->_endpointMap as $range) {
if ($version >= $range['min'] &&
$version <= $range['max'] &&
isset($range['environments'][$this->_profile->getEnvironment()][$portType])) {
// Check 3-token auth
$signature = $this->_profile->getSignature();
if(isset($signature)) {
// TBD: Is this legit?
$three_token_port = $portType.'-threetoken';
$this->_endpoint = $range['environments'][$this->_profile->getEnvironment()][$three_token_port];
} else {
$this->_endpoint = $range['environments'][$this->_profile->getEnvironment()][$portType];
}
$this->getLogger();
$this->_logger->log('DEBUG setEndpoint: '.$this->_endpoint, PEAR_LOG_DEBUG);
return true;
}
}
return PayPal::raiseError("Invalid version/environment/portType combination.");
}
/**
* Take the decoded array from SOAP_Client::__call() and turn it
* into an object of the appropriate AbstractResponseType
* subclass.
*
* @param array $values The decoded SOAP response.
* @param string $type The type of the response object.
*
* @return AbstractResponseType The response object.
*/
function &getResponseObject($values, $type)
{
// Check for SOAP Faults.
if (PayPal::isError($values)) {
return $values;
}
// Check for already translated objects.
if (is_object($values) && strtolower(get_class($values)) != 'xsdsimpletype') {
return $values;
}
$object =& PayPal::getType($type);
if (PayPal::isError($object)) {
return $values;
}
foreach ($values as $name => $value) {
if (method_exists($object, 'set' . $name)) {
if (is_object($value)) {
if (strtolower(get_class($value)) == 'xsdsimpletype') {
$value =& $this->getResponseObject((array)$value, $object->_elements[$name]['type']);
}
} elseif (is_array($value)) {
$values = $value;
$value = array();
foreach ($values as $v) {
$value[] =& $this->getResponseObject($v, $object->_elements[$name]['type']);
}
}
call_user_func(array(&$object, 'set' . $name), $value);
}
}
return $object;
}
/**
* Use a given profile.
*
* @param APIProfile $profile The profile with the username, password,
* and any other information necessary to use
* the SDK.
*/
function setAPIProfile(&$profile)
{
$this->_profile = &$profile;
}
/**
* Get the current profile.
*
* @return APIProfile The current profile.
*/
function &getAPIProfile()
{
return $this->_profile;
}
/**
* Gets the PEAR Log object to use.
*
* @return Log A Log object, either provided by the user or
* created by this function.
*/
function &getLogger()
{
if (!$this->_logger) {
$file = $this->_logDir . '/' . date('Ymd') . '.PayPal.log';
if (is_link($file) || (file_exists($file) && !is_writable($file))) {
// Don't overwrite symlinks.
return PayPal::raiseError('bad logfile');
}
$this->_logger = &Log::singleton('file', $file, $this->_profile->getAPIUsername(), array('append' => true));
}
return $this->_logger;
}
/**
* Sets a custom PEAR Log object to use in logging.
*
* @param Log A PEAR Log instance.
*/
function setLogger(&$logger)
{
if (is_a($logger, 'Log')) {
$this->_logger =& $logger;
}
}
/**
* Override SOAP_Client::call() to always add our security header
* first.
*/
function buildAuthString($auth_token,$auth_signature,$auth_timestamp)
{
$authString="token=".$auth_token.",signature=".$auth_signature.",timestamp=".$auth_timestamp ;
$authString="X-PP-AUTHORIZATION: ".$authString;
return $authString;
}
function &call($method, &$params, $namespace = false, $soapAction = false)
{
// Create the empty security header if using permissioning, pass the auth token, auth signature, auth timestamp as httpheader
if(!empty($this->_profile->_authSignature))
{
global $authstringvar;
$authstringvar = CallerServices::buildAuthString($this->_profile->_authToken,$this->_profile->_authSignature,$this->_profile->_authTimestamp);
$_SESSION['authstr']=$authstringvar;
$this->addHeader($rc = new SOAP_Header('RequesterCredentials', 'struct', array(
new SOAP_Value('{urn:ebay:apis:eBLBaseComponents}Credentials', 'struct',
$tmp,
array('xmlns:ebl' => 'urn:ebay:apis:eBLBaseComponents'))),
1, array('xmlns' => 'urn:ebay:api:PayPalAPI')));
}
// Create the security header if not using permissioning
else {
$this->addHeader($rc = new SOAP_Header('RequesterCredentials', 'struct', array(
new SOAP_Value('{urn:ebay:apis:eBLBaseComponents}Credentials', 'struct',
array(new SOAP_Value('{urn:ebay:apis:eBLBaseComponents}Username', '', $this->_profile->getAPIUsername()),
new SOAP_Value('{urn:ebay:apis:eBLBaseComponents}Password', '', $this->_profile->getAPIPassword()),
new SOAP_Value('{urn:ebay:apis:eBLBaseComponents}Signature', '', $this->_profile->getSignature()),
new SOAP_Value('{urn:ebay:apis:eBLBaseComponents}Subject', '', $this->_profile->getSubject())),
array('xmlns:ebl' => 'urn:ebay:apis:eBLBaseComponents'))),
1, array('xmlns' => 'urn:ebay:api:PayPalAPI')));
}
return parent::call($method, $params, $namespace, $soapAction);
}
/**
* Override some of the default SOAP:: package _decode behavior to
* handle simpleTypes and complexTypes with simpleContent.
*/
function &_decode(&$soapval)
{
if (count($soapval->attributes)) {
$attributes = $soapval->attributes;
}
$object =& PayPal::getType($soapval->type);
if (PayPal::isError($object)) {
return parent::_decode($soapval);
}
$this->_type_translation[$soapval->type] = $soapval->type;
$result =& parent::_decode($soapval);
if (!is_a($result, 'XSDType') && is_a($object, 'XSDSimpleType')) {
$object->setval($result);
if (isset($attributes)) {
foreach ($attributes as $aname => $attribute) {
$object->setattr($aname, $attribute);
}
}
$result =& $object;
}
return $result;
}
/**
* Log the current transaction depending on the current log level.
*
* @access protected
*
* @param string $operation The operation called.
* @param integer $elapsed Microseconds taken.
* @param object $response The response object.
*/
function _logTransaction($operation, $elapsed, $response)
{
$logger =& $this->getLogger();
if (PayPal::isError($logger)) {
return $logger;
}
switch ($this->_logLevel) {
case PEAR_LOG_DEBUG:
$logger->log('Request XML: ' . $this->_sanitizeLog($this->__last_request), PEAR_LOG_DEBUG);
$logger->log('Response XML: ' . $this->_sanitizeLog($this->__last_response), PEAR_LOG_DEBUG);
case PEAR_LOG_INFO:
$ack = is_object($response) && method_exists($response, 'getAck') ? ', Ack: ' . $response->getAck() : '';
$logger->log($operation . ', Elapsed: ' . $elapsed . 'ms' . $ack, PEAR_LOG_INFO);
case PEAR_LOG_ERR:
if (PayPal::isError($response)) {
$logger->log($response, PEAR_LOG_ERR);
}
}
}
/**
* Strip sensitive information (API passwords and credit card
* numbers) from raw XML requests/responses.
*
* @access protected
*
* @param string $xml The XML to sanitize.
*
* @return string The sanitized XML.
*/
function _sanitizeLog($xml)
{
return preg_replace(array('/<(.*?Password.*?)>(.*?)<\/(.*?Password)>/i',
'/<(.*CreditCardNumber.*)>(.*?)<\/(.*CreditCardNumber)>/i',
'/<(.*Signature.*)>(.*?)<\/(.*Signature)>/i'),
'<\1>***</\3>',
$xml);
}
/**
* Return the current time including microseconds.
*
* @access protected
*
* @return integer Current time with microseconds.
*/
function _getMicroseconds()
{
list($ms, $s) = explode(' ', microtime());
return floor($ms * 1000) + 1000 * $s;
}
/**
* Return the difference between now and $start in microseconds.
*
* @access protected
*
* @param integer $start Start time including microseconds.
*
* @return integer Number of microseconds elapsed since $start
*/
function _getElapsed($start)
{
return $this->_getMicroseconds() - $start;
}
function &RefundTransaction($RefundTransactionReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($RefundTransactionReq, 'XSDSimpleType')) {
if ($RefundTransactionReq->getVersion() == '') {
$RefundTransactionReq->setVersion(PAYPAL_WSDL_VERSION);
}
$RefundTransactionReq = $RefundTransactionReq->getSoapValue('RefundTransactionRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('RefundTransaction', $this->_getElapsed($start), $res);
return $res;
}
// RefundTransactionReq is a ComplexType, refer to the WSDL for more info.
$RefundTransactionReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$RefundTransactionReq =& new SOAP_Value('RefundTransactionReq', false, $RefundTransactionReq, $RefundTransactionReq_attr);
$result = $this->call('RefundTransaction',
$v = array("RefundTransactionReq" => $RefundTransactionReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'RefundTransactionResponseType');
$this->_logTransaction('RefundTransaction', $this->_getElapsed($start), $response);
return $response;
}
function &InitiateRecoup($InitiateRecoupReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($InitiateRecoupReq, 'XSDSimpleType')) {
if ($InitiateRecoupReq->getVersion() == '') {
$InitiateRecoupReq->setVersion(PAYPAL_WSDL_VERSION);
}
$InitiateRecoupReq = $InitiateRecoupReq->getSoapValue('InitiateRecoupRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('InitiateRecoup', $this->_getElapsed($start), $res);
return $res;
}
// InitiateRecoupReq is a ComplexType, refer to the WSDL for more info.
$InitiateRecoupReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$InitiateRecoupReq =& new SOAP_Value('InitiateRecoupReq', false, $InitiateRecoupReq, $InitiateRecoupReq_attr);
$result = $this->call('InitiateRecoup',
$v = array("InitiateRecoupReq" => $InitiateRecoupReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'InitiateRecoupResponseType');
$this->_logTransaction('InitiateRecoup', $this->_getElapsed($start), $response);
return $response;
}
function &CompleteRecoup($CompleteRecoupReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($CompleteRecoupReq, 'XSDSimpleType')) {
if ($CompleteRecoupReq->getVersion() == '') {
$CompleteRecoupReq->setVersion(PAYPAL_WSDL_VERSION);
}
$CompleteRecoupReq = $CompleteRecoupReq->getSoapValue('CompleteRecoupRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('CompleteRecoup', $this->_getElapsed($start), $res);
return $res;
}
// CompleteRecoupReq is a ComplexType, refer to the WSDL for more info.
$CompleteRecoupReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$CompleteRecoupReq =& new SOAP_Value('CompleteRecoupReq', false, $CompleteRecoupReq, $CompleteRecoupReq_attr);
$result = $this->call('CompleteRecoup',
$v = array("CompleteRecoupReq" => $CompleteRecoupReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'CompleteRecoupResponseType');
$this->_logTransaction('CompleteRecoup', $this->_getElapsed($start), $response);
return $response;
}
function &CancelRecoup($CancelRecoupReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($CancelRecoupReq, 'XSDSimpleType')) {
if ($CancelRecoupReq->getVersion() == '') {
$CancelRecoupReq->setVersion(PAYPAL_WSDL_VERSION);
}
$CancelRecoupReq = $CancelRecoupReq->getSoapValue('CancelRecoupRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('CancelRecoup', $this->_getElapsed($start), $res);
return $res;
}
// CancelRecoupReq is a ComplexType, refer to the WSDL for more info.
$CancelRecoupReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$CancelRecoupReq =& new SOAP_Value('CancelRecoupReq', false, $CancelRecoupReq, $CancelRecoupReq_attr);
$result = $this->call('CancelRecoup',
$v = array("CancelRecoupReq" => $CancelRecoupReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'CancelRecoupResponseType');
$this->_logTransaction('CancelRecoup', $this->_getElapsed($start), $response);
return $response;
}
function &GetTransactionDetails($GetTransactionDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetTransactionDetailsReq, 'XSDSimpleType')) {
if ($GetTransactionDetailsReq->getVersion() == '') {
$GetTransactionDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetTransactionDetailsReq = $GetTransactionDetailsReq->getSoapValue('GetTransactionDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetTransactionDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetTransactionDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetTransactionDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetTransactionDetailsReq =& new SOAP_Value('GetTransactionDetailsReq', false, $GetTransactionDetailsReq, $GetTransactionDetailsReq_attr);
$result = $this->call('GetTransactionDetails',
$v = array("GetTransactionDetailsReq" => $GetTransactionDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetTransactionDetailsResponseType');
$this->_logTransaction('GetTransactionDetails', $this->_getElapsed($start), $response);
return $response;
}
function &BMCreateButton($BMCreateButtonReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMCreateButtonReq, 'XSDSimpleType')) {
if ($BMCreateButtonReq->getVersion() == '') {
$BMCreateButtonReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMCreateButtonReq = $BMCreateButtonReq->getSoapValue('BMCreateButtonRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMCreateButton', $this->_getElapsed($start), $res);
return $res;
}
// BMCreateButtonReq is a ComplexType, refer to the WSDL for more info.
$BMCreateButtonReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMCreateButtonReq =& new SOAP_Value('BMCreateButtonReq', false, $BMCreateButtonReq, $BMCreateButtonReq_attr);
$result = $this->call('BMCreateButton',
$v = array("BMCreateButtonReq" => $BMCreateButtonReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMCreateButtonResponseType');
$this->_logTransaction('BMCreateButton', $this->_getElapsed($start), $response);
return $response;
}
function &BMUpdateButton($BMUpdateButtonReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMUpdateButtonReq, 'XSDSimpleType')) {
if ($BMUpdateButtonReq->getVersion() == '') {
$BMUpdateButtonReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMUpdateButtonReq = $BMUpdateButtonReq->getSoapValue('BMUpdateButtonRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMUpdateButton', $this->_getElapsed($start), $res);
return $res;
}
// BMUpdateButtonReq is a ComplexType, refer to the WSDL for more info.
$BMUpdateButtonReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMUpdateButtonReq =& new SOAP_Value('BMUpdateButtonReq', false, $BMUpdateButtonReq, $BMUpdateButtonReq_attr);
$result = $this->call('BMUpdateButton',
$v = array("BMUpdateButtonReq" => $BMUpdateButtonReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMUpdateButtonResponseType');
$this->_logTransaction('BMUpdateButton', $this->_getElapsed($start), $response);
return $response;
}
function &BMManageButtonStatus($BMManageButtonStatusReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMManageButtonStatusReq, 'XSDSimpleType')) {
if ($BMManageButtonStatusReq->getVersion() == '') {
$BMManageButtonStatusReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMManageButtonStatusReq = $BMManageButtonStatusReq->getSoapValue('BMManageButtonStatusRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMManageButtonStatus', $this->_getElapsed($start), $res);
return $res;
}
// BMManageButtonStatusReq is a ComplexType, refer to the WSDL for more info.
$BMManageButtonStatusReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMManageButtonStatusReq =& new SOAP_Value('BMManageButtonStatusReq', false, $BMManageButtonStatusReq, $BMManageButtonStatusReq_attr);
$result = $this->call('BMManageButtonStatus',
$v = array("BMManageButtonStatusReq" => $BMManageButtonStatusReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMManageButtonStatusResponseType');
$this->_logTransaction('BMManageButtonStatus', $this->_getElapsed($start), $response);
return $response;
}
function &BMGetButtonDetails($BMGetButtonDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMGetButtonDetailsReq, 'XSDSimpleType')) {
if ($BMGetButtonDetailsReq->getVersion() == '') {
$BMGetButtonDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMGetButtonDetailsReq = $BMGetButtonDetailsReq->getSoapValue('BMGetButtonDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMGetButtonDetails', $this->_getElapsed($start), $res);
return $res;
}
// BMGetButtonDetailsReq is a ComplexType, refer to the WSDL for more info.
$BMGetButtonDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMGetButtonDetailsReq =& new SOAP_Value('BMGetButtonDetailsReq', false, $BMGetButtonDetailsReq, $BMGetButtonDetailsReq_attr);
$result = $this->call('BMGetButtonDetails',
$v = array("BMGetButtonDetailsReq" => $BMGetButtonDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMGetButtonDetailsResponseType');
$this->_logTransaction('BMGetButtonDetails', $this->_getElapsed($start), $response);
return $response;
}
function &BMSetInventory($BMSetInventoryReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMSetInventoryReq, 'XSDSimpleType')) {
if ($BMSetInventoryReq->getVersion() == '') {
$BMSetInventoryReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMSetInventoryReq = $BMSetInventoryReq->getSoapValue('BMSetInventoryRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMSetInventory', $this->_getElapsed($start), $res);
return $res;
}
// BMSetInventoryReq is a ComplexType, refer to the WSDL for more info.
$BMSetInventoryReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMSetInventoryReq =& new SOAP_Value('BMSetInventoryReq', false, $BMSetInventoryReq, $BMSetInventoryReq_attr);
$result = $this->call('BMSetInventory',
$v = array("BMSetInventoryReq" => $BMSetInventoryReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMSetInventoryResponseType');
$this->_logTransaction('BMSetInventory', $this->_getElapsed($start), $response);
return $response;
}
function &BMGetInventory($BMGetInventoryReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMGetInventoryReq, 'XSDSimpleType')) {
if ($BMGetInventoryReq->getVersion() == '') {
$BMGetInventoryReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMGetInventoryReq = $BMGetInventoryReq->getSoapValue('BMGetInventoryRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMGetInventory', $this->_getElapsed($start), $res);
return $res;
}
// BMGetInventoryReq is a ComplexType, refer to the WSDL for more info.
$BMGetInventoryReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMGetInventoryReq =& new SOAP_Value('BMGetInventoryReq', false, $BMGetInventoryReq, $BMGetInventoryReq_attr);
$result = $this->call('BMGetInventory',
$v = array("BMGetInventoryReq" => $BMGetInventoryReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMGetInventoryResponseType');
$this->_logTransaction('BMGetInventory', $this->_getElapsed($start), $response);
return $response;
}
function &BMButtonSearch($BMButtonSearchReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BMButtonSearchReq, 'XSDSimpleType')) {
if ($BMButtonSearchReq->getVersion() == '') {
$BMButtonSearchReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BMButtonSearchReq = $BMButtonSearchReq->getSoapValue('BMButtonSearchRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BMButtonSearch', $this->_getElapsed($start), $res);
return $res;
}
// BMButtonSearchReq is a ComplexType, refer to the WSDL for more info.
$BMButtonSearchReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BMButtonSearchReq =& new SOAP_Value('BMButtonSearchReq', false, $BMButtonSearchReq, $BMButtonSearchReq_attr);
$result = $this->call('BMButtonSearch',
$v = array("BMButtonSearchReq" => $BMButtonSearchReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BMButtonSearchResponseType');
$this->_logTransaction('BMButtonSearch', $this->_getElapsed($start), $response);
return $response;
}
function &BillUser($BillUserReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BillUserReq, 'XSDSimpleType')) {
if ($BillUserReq->getVersion() == '') {
$BillUserReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BillUserReq = $BillUserReq->getSoapValue('BillUserRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BillUser', $this->_getElapsed($start), $res);
return $res;
}
// BillUserReq is a ComplexType, refer to the WSDL for more info.
$BillUserReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BillUserReq =& new SOAP_Value('BillUserReq', false, $BillUserReq, $BillUserReq_attr);
$result = $this->call('BillUser',
$v = array("BillUserReq" => $BillUserReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BillUserResponseType');
$this->_logTransaction('BillUser', $this->_getElapsed($start), $response);
return $response;
}
function &TransactionSearch($TransactionSearchReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($TransactionSearchReq, 'XSDSimpleType')) {
if ($TransactionSearchReq->getVersion() == '') {
$TransactionSearchReq->setVersion(PAYPAL_WSDL_VERSION);
}
$TransactionSearchReq = $TransactionSearchReq->getSoapValue('TransactionSearchRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('TransactionSearch', $this->_getElapsed($start), $res);
return $res;
}
// TransactionSearchReq is a ComplexType, refer to the WSDL for more info.
$TransactionSearchReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$TransactionSearchReq =& new SOAP_Value('TransactionSearchReq', false, $TransactionSearchReq, $TransactionSearchReq_attr);
$result = $this->call('TransactionSearch',
$v = array("TransactionSearchReq" => $TransactionSearchReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'TransactionSearchResponseType');
$this->_logTransaction('TransactionSearch', $this->_getElapsed($start), $response);
return $response;
}
function &MassPay($MassPayReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($MassPayReq, 'XSDSimpleType')) {
if ($MassPayReq->getVersion() == '') {
$MassPayReq->setVersion(PAYPAL_WSDL_VERSION);
}
$MassPayReq = $MassPayReq->getSoapValue('MassPayRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('MassPay', $this->_getElapsed($start), $res);
return $res;
}
// MassPayReq is a ComplexType, refer to the WSDL for more info.
$MassPayReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$MassPayReq =& new SOAP_Value('MassPayReq', false, $MassPayReq, $MassPayReq_attr);
$result = $this->call('MassPay',
$v = array("MassPayReq" => $MassPayReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'MassPayResponseType');
$this->_logTransaction('MassPay', $this->_getElapsed($start), $response);
return $response;
}
function &BillAgreementUpdate($BillAgreementUpdateReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BillAgreementUpdateReq, 'XSDSimpleType')) {
if ($BillAgreementUpdateReq->getVersion() == '') {
$BillAgreementUpdateReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BillAgreementUpdateReq = $BillAgreementUpdateReq->getSoapValue('BAUpdateRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BillAgreementUpdate', $this->_getElapsed($start), $res);
return $res;
}
// BillAgreementUpdateReq is a ComplexType, refer to the WSDL for more info.
$BillAgreementUpdateReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BillAgreementUpdateReq =& new SOAP_Value('BillAgreementUpdateReq', false, $BillAgreementUpdateReq, $BillAgreementUpdateReq_attr);
$result = $this->call('BillAgreementUpdate',
$v = array("BillAgreementUpdateReq" => $BillAgreementUpdateReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BAUpdateResponseType');
$this->_logTransaction('BillAgreementUpdate', $this->_getElapsed($start), $response);
return $response;
}
function &AddressVerify($AddressVerifyReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($AddressVerifyReq, 'XSDSimpleType')) {
if ($AddressVerifyReq->getVersion() == '') {
$AddressVerifyReq->setVersion(PAYPAL_WSDL_VERSION);
}
$AddressVerifyReq = $AddressVerifyReq->getSoapValue('AddressVerifyRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('AddressVerify', $this->_getElapsed($start), $res);
return $res;
}
// AddressVerifyReq is a ComplexType, refer to the WSDL for more info.
$AddressVerifyReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$AddressVerifyReq =& new SOAP_Value('AddressVerifyReq', false, $AddressVerifyReq, $AddressVerifyReq_attr);
$result = $this->call('AddressVerify',
$v = array("AddressVerifyReq" => $AddressVerifyReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'AddressVerifyResponseType');
$this->_logTransaction('AddressVerify', $this->_getElapsed($start), $response);
return $response;
}
function &EnterBoarding($EnterBoardingReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($EnterBoardingReq, 'XSDSimpleType')) {
if ($EnterBoardingReq->getVersion() == '') {
$EnterBoardingReq->setVersion(PAYPAL_WSDL_VERSION);
}
$EnterBoardingReq = $EnterBoardingReq->getSoapValue('EnterBoardingRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('EnterBoarding', $this->_getElapsed($start), $res);
return $res;
}
// EnterBoardingReq is a ComplexType, refer to the WSDL for more info.
$EnterBoardingReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$EnterBoardingReq =& new SOAP_Value('EnterBoardingReq', false, $EnterBoardingReq, $EnterBoardingReq_attr);
$result = $this->call('EnterBoarding',
$v = array("EnterBoardingReq" => $EnterBoardingReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'EnterBoardingResponseType');
$this->_logTransaction('EnterBoarding', $this->_getElapsed($start), $response);
return $response;
}
function &GetBoardingDetails($GetBoardingDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetBoardingDetailsReq, 'XSDSimpleType')) {
if ($GetBoardingDetailsReq->getVersion() == '') {
$GetBoardingDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetBoardingDetailsReq = $GetBoardingDetailsReq->getSoapValue('GetBoardingDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetBoardingDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetBoardingDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetBoardingDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetBoardingDetailsReq =& new SOAP_Value('GetBoardingDetailsReq', false, $GetBoardingDetailsReq, $GetBoardingDetailsReq_attr);
$result = $this->call('GetBoardingDetails',
$v = array("GetBoardingDetailsReq" => $GetBoardingDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetBoardingDetailsResponseType');
$this->_logTransaction('GetBoardingDetails', $this->_getElapsed($start), $response);
return $response;
}
function &CreateMobilePayment($CreateMobilePaymentReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($CreateMobilePaymentReq, 'XSDSimpleType')) {
if ($CreateMobilePaymentReq->getVersion() == '') {
$CreateMobilePaymentReq->setVersion(PAYPAL_WSDL_VERSION);
}
$CreateMobilePaymentReq = $CreateMobilePaymentReq->getSoapValue('CreateMobilePaymentRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('CreateMobilePayment', $this->_getElapsed($start), $res);
return $res;
}
// CreateMobilePaymentReq is a ComplexType, refer to the WSDL for more info.
$CreateMobilePaymentReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$CreateMobilePaymentReq =& new SOAP_Value('CreateMobilePaymentReq', false, $CreateMobilePaymentReq, $CreateMobilePaymentReq_attr);
$result = $this->call('CreateMobilePayment',
$v = array("CreateMobilePaymentReq" => $CreateMobilePaymentReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'CreateMobilePaymentResponseType');
$this->_logTransaction('CreateMobilePayment', $this->_getElapsed($start), $response);
return $response;
}
function &GetMobileStatus($GetMobileStatusReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetMobileStatusReq, 'XSDSimpleType')) {
if ($GetMobileStatusReq->getVersion() == '') {
$GetMobileStatusReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetMobileStatusReq = $GetMobileStatusReq->getSoapValue('GetMobileStatusRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetMobileStatus', $this->_getElapsed($start), $res);
return $res;
}
// GetMobileStatusReq is a ComplexType, refer to the WSDL for more info.
$GetMobileStatusReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetMobileStatusReq =& new SOAP_Value('GetMobileStatusReq', false, $GetMobileStatusReq, $GetMobileStatusReq_attr);
$result = $this->call('GetMobileStatus',
$v = array("GetMobileStatusReq" => $GetMobileStatusReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetMobileStatusResponseType');
$this->_logTransaction('GetMobileStatus', $this->_getElapsed($start), $response);
return $response;
}
function &SetMobileCheckout($SetMobileCheckoutReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($SetMobileCheckoutReq, 'XSDSimpleType')) {
if ($SetMobileCheckoutReq->getVersion() == '') {
$SetMobileCheckoutReq->setVersion(PAYPAL_WSDL_VERSION);
}
$SetMobileCheckoutReq = $SetMobileCheckoutReq->getSoapValue('SetMobileCheckoutRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('SetMobileCheckout', $this->_getElapsed($start), $res);
return $res;
}
// SetMobileCheckoutReq is a ComplexType, refer to the WSDL for more info.
$SetMobileCheckoutReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$SetMobileCheckoutReq =& new SOAP_Value('SetMobileCheckoutReq', false, $SetMobileCheckoutReq, $SetMobileCheckoutReq_attr);
$result = $this->call('SetMobileCheckout',
$v = array("SetMobileCheckoutReq" => $SetMobileCheckoutReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'SetMobileCheckoutResponseType');
$this->_logTransaction('SetMobileCheckout', $this->_getElapsed($start), $response);
return $response;
}
function &DoMobileCheckoutPayment($DoMobileCheckoutPaymentReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoMobileCheckoutPaymentReq, 'XSDSimpleType')) {
if ($DoMobileCheckoutPaymentReq->getVersion() == '') {
$DoMobileCheckoutPaymentReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoMobileCheckoutPaymentReq = $DoMobileCheckoutPaymentReq->getSoapValue('DoMobileCheckoutPaymentRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoMobileCheckoutPayment', $this->_getElapsed($start), $res);
return $res;
}
// DoMobileCheckoutPaymentReq is a ComplexType, refer to the WSDL for more info.
$DoMobileCheckoutPaymentReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoMobileCheckoutPaymentReq =& new SOAP_Value('DoMobileCheckoutPaymentReq', false, $DoMobileCheckoutPaymentReq, $DoMobileCheckoutPaymentReq_attr);
$result = $this->call('DoMobileCheckoutPayment',
$v = array("DoMobileCheckoutPaymentReq" => $DoMobileCheckoutPaymentReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoMobileCheckoutPaymentResponseType');
$this->_logTransaction('DoMobileCheckoutPayment', $this->_getElapsed($start), $response);
return $response;
}
function &GetBalance($GetBalanceReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetBalanceReq, 'XSDSimpleType')) {
if ($GetBalanceReq->getVersion() == '') {
$GetBalanceReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetBalanceReq = $GetBalanceReq->getSoapValue('GetBalanceRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetBalance', $this->_getElapsed($start), $res);
return $res;
}
// GetBalanceReq is a ComplexType, refer to the WSDL for more info.
$GetBalanceReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetBalanceReq =& new SOAP_Value('GetBalanceReq', false, $GetBalanceReq, $GetBalanceReq_attr);
$result = $this->call('GetBalance',
$v = array("GetBalanceReq" => $GetBalanceReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetBalanceResponseType');
$this->_logTransaction('GetBalance', $this->_getElapsed($start), $response);
return $response;
}
function &GetPalDetails($GetPalDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetPalDetailsReq, 'XSDSimpleType')) {
if ($GetPalDetailsReq->getVersion() == '') {
$GetPalDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetPalDetailsReq = $GetPalDetailsReq->getSoapValue('GetPalDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPI', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetPalDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetPalDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetPalDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetPalDetailsReq =& new SOAP_Value('GetPalDetailsReq', false, $GetPalDetailsReq, $GetPalDetailsReq_attr);
$result = $this->call('GetPalDetails',
$v = array("GetPalDetailsReq" => $GetPalDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetPalDetailsResponseType');
$this->_logTransaction('GetPalDetails', $this->_getElapsed($start), $response);
return $response;
}
function &DoExpressCheckoutPayment($DoExpressCheckoutPaymentReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoExpressCheckoutPaymentReq, 'XSDSimpleType')) {
if ($DoExpressCheckoutPaymentReq->getVersion() == '') {
$DoExpressCheckoutPaymentReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoExpressCheckoutPaymentReq = $DoExpressCheckoutPaymentReq->getSoapValue('DoExpressCheckoutPaymentRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoExpressCheckoutPayment', $this->_getElapsed($start), $res);
return $res;
}
// DoExpressCheckoutPaymentReq is a ComplexType, refer to the WSDL for more info.
$DoExpressCheckoutPaymentReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoExpressCheckoutPaymentReq =& new SOAP_Value('DoExpressCheckoutPaymentReq', false, $DoExpressCheckoutPaymentReq, $DoExpressCheckoutPaymentReq_attr);
$result = $this->call('DoExpressCheckoutPayment',
$v = array("DoExpressCheckoutPaymentReq" => $DoExpressCheckoutPaymentReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoExpressCheckoutPaymentResponseType');
$this->_logTransaction('DoExpressCheckoutPayment', $this->_getElapsed($start), $response);
return $response;
}
function &DoUATPExpressCheckoutPayment($DoUATPExpressCheckoutPaymentReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoUATPExpressCheckoutPaymentReq, 'XSDSimpleType')) {
if ($DoUATPExpressCheckoutPaymentReq->getVersion() == '') {
$DoUATPExpressCheckoutPaymentReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoUATPExpressCheckoutPaymentReq = $DoUATPExpressCheckoutPaymentReq->getSoapValue('DoUATPExpressCheckoutPaymentRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoUATPExpressCheckoutPayment', $this->_getElapsed($start), $res);
return $res;
}
// DoUATPExpressCheckoutPaymentReq is a ComplexType, refer to the WSDL for more info.
$DoUATPExpressCheckoutPaymentReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoUATPExpressCheckoutPaymentReq =& new SOAP_Value('DoUATPExpressCheckoutPaymentReq', false, $DoUATPExpressCheckoutPaymentReq, $DoUATPExpressCheckoutPaymentReq_attr);
$result = $this->call('DoUATPExpressCheckoutPayment',
$v = array("DoUATPExpressCheckoutPaymentReq" => $DoUATPExpressCheckoutPaymentReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoUATPExpressCheckoutPaymentResponseType');
$this->_logTransaction('DoUATPExpressCheckoutPayment', $this->_getElapsed($start), $response);
return $response;
}
function &SetAuthFlowParam($SetAuthFlowParamReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($SetAuthFlowParamReq, 'XSDSimpleType')) {
if ($SetAuthFlowParamReq->getVersion() == '') {
$SetAuthFlowParamReq->setVersion(PAYPAL_WSDL_VERSION);
}
$SetAuthFlowParamReq = $SetAuthFlowParamReq->getSoapValue('SetAuthFlowParamRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('SetAuthFlowParam', $this->_getElapsed($start), $res);
return $res;
}
// SetAuthFlowParamReq is a ComplexType, refer to the WSDL for more info.
$SetAuthFlowParamReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$SetAuthFlowParamReq =& new SOAP_Value('SetAuthFlowParamReq', false, $SetAuthFlowParamReq, $SetAuthFlowParamReq_attr);
$result = $this->call('SetAuthFlowParam',
$v = array("SetAuthFlowParamReq" => $SetAuthFlowParamReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'SetAuthFlowParamResponseType');
$this->_logTransaction('SetAuthFlowParam', $this->_getElapsed($start), $response);
return $response;
}
function &GetAuthDetails($GetAuthDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetAuthDetailsReq, 'XSDSimpleType')) {
if ($GetAuthDetailsReq->getVersion() == '') {
$GetAuthDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetAuthDetailsReq = $GetAuthDetailsReq->getSoapValue('GetAuthDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetAuthDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetAuthDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetAuthDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetAuthDetailsReq =& new SOAP_Value('GetAuthDetailsReq', false, $GetAuthDetailsReq, $GetAuthDetailsReq_attr);
$result = $this->call('GetAuthDetails',
$v = array("GetAuthDetailsReq" => $GetAuthDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetAuthDetailsResponseType');
$this->_logTransaction('GetAuthDetails', $this->_getElapsed($start), $response);
return $response;
}
function &SetAccessPermissions($SetAccessPermissionsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($SetAccessPermissionsReq, 'XSDSimpleType')) {
if ($SetAccessPermissionsReq->getVersion() == '') {
$SetAccessPermissionsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$SetAccessPermissionsReq = $SetAccessPermissionsReq->getSoapValue('SetAccessPermissionsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('SetAccessPermissions', $this->_getElapsed($start), $res);
return $res;
}
// SetAccessPermissionsReq is a ComplexType, refer to the WSDL for more info.
$SetAccessPermissionsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$SetAccessPermissionsReq =& new SOAP_Value('SetAccessPermissionsReq', false, $SetAccessPermissionsReq, $SetAccessPermissionsReq_attr);
$result = $this->call('SetAccessPermissions',
$v = array("SetAccessPermissionsReq" => $SetAccessPermissionsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'SetAccessPermissionsResponseType');
$this->_logTransaction('SetAccessPermissions', $this->_getElapsed($start), $response);
return $response;
}
function &UpdateAccessPermissions($UpdateAccessPermissionsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($UpdateAccessPermissionsReq, 'XSDSimpleType')) {
if ($UpdateAccessPermissionsReq->getVersion() == '') {
$UpdateAccessPermissionsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$UpdateAccessPermissionsReq = $UpdateAccessPermissionsReq->getSoapValue('UpdateAccessPermissionsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('UpdateAccessPermissions', $this->_getElapsed($start), $res);
return $res;
}
// UpdateAccessPermissionsReq is a ComplexType, refer to the WSDL for more info.
$UpdateAccessPermissionsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$UpdateAccessPermissionsReq =& new SOAP_Value('UpdateAccessPermissionsReq', false, $UpdateAccessPermissionsReq, $UpdateAccessPermissionsReq_attr);
$result = $this->call('UpdateAccessPermissions',
$v = array("UpdateAccessPermissionsReq" => $UpdateAccessPermissionsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'UpdateAccessPermissionsResponseType');
$this->_logTransaction('UpdateAccessPermissions', $this->_getElapsed($start), $response);
return $response;
}
function &GetAccessPermissionDetails($GetAccessPermissionDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetAccessPermissionDetailsReq, 'XSDSimpleType')) {
if ($GetAccessPermissionDetailsReq->getVersion() == '') {
$GetAccessPermissionDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetAccessPermissionDetailsReq = $GetAccessPermissionDetailsReq->getSoapValue('GetAccessPermissionDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetAccessPermissionDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetAccessPermissionDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetAccessPermissionDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetAccessPermissionDetailsReq =& new SOAP_Value('GetAccessPermissionDetailsReq', false, $GetAccessPermissionDetailsReq, $GetAccessPermissionDetailsReq_attr);
$result = $this->call('GetAccessPermissionDetails',
$v = array("GetAccessPermissionDetailsReq" => $GetAccessPermissionDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetAccessPermissionDetailsResponseType');
$this->_logTransaction('GetAccessPermissionDetails', $this->_getElapsed($start), $response);
return $response;
}
function &GetIncentiveEvaluation($GetIncentiveEvaluationReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetIncentiveEvaluationReq, 'XSDSimpleType')) {
if ($GetIncentiveEvaluationReq->getVersion() == '') {
$GetIncentiveEvaluationReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetIncentiveEvaluationReq = $GetIncentiveEvaluationReq->getSoapValue('GetIncentiveEvaluationRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetIncentiveEvaluation', $this->_getElapsed($start), $res);
return $res;
}
// GetIncentiveEvaluationReq is a ComplexType, refer to the WSDL for more info.
$GetIncentiveEvaluationReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetIncentiveEvaluationReq =& new SOAP_Value('GetIncentiveEvaluationReq', false, $GetIncentiveEvaluationReq, $GetIncentiveEvaluationReq_attr);
$result = $this->call('GetIncentiveEvaluation',
$v = array("GetIncentiveEvaluationReq" => $GetIncentiveEvaluationReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetIncentiveEvaluationResponseType');
$this->_logTransaction('GetIncentiveEvaluation', $this->_getElapsed($start), $response);
return $response;
}
function &SetExpressCheckout($SetExpressCheckoutReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($SetExpressCheckoutReq, 'XSDSimpleType')) {
if ($SetExpressCheckoutReq->getVersion() == '') {
$SetExpressCheckoutReq->setVersion(PAYPAL_WSDL_VERSION);
}
$SetExpressCheckoutReq = $SetExpressCheckoutReq->getSoapValue('SetExpressCheckoutRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('SetExpressCheckout', $this->_getElapsed($start), $res);
return $res;
}
// SetExpressCheckoutReq is a ComplexType, refer to the WSDL for more info.
$SetExpressCheckoutReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$SetExpressCheckoutReq =& new SOAP_Value('SetExpressCheckoutReq', false, $SetExpressCheckoutReq, $SetExpressCheckoutReq_attr);
$result = $this->call('SetExpressCheckout',
$v = array("SetExpressCheckoutReq" => $SetExpressCheckoutReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'SetExpressCheckoutResponseType');
$this->_logTransaction('SetExpressCheckout', $this->_getElapsed($start), $response);
return $response;
}
function &GetExpressCheckoutDetails($GetExpressCheckoutDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetExpressCheckoutDetailsReq, 'XSDSimpleType')) {
if ($GetExpressCheckoutDetailsReq->getVersion() == '') {
$GetExpressCheckoutDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetExpressCheckoutDetailsReq = $GetExpressCheckoutDetailsReq->getSoapValue('GetExpressCheckoutDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetExpressCheckoutDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetExpressCheckoutDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetExpressCheckoutDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetExpressCheckoutDetailsReq =& new SOAP_Value('GetExpressCheckoutDetailsReq', false, $GetExpressCheckoutDetailsReq, $GetExpressCheckoutDetailsReq_attr);
$result = $this->call('GetExpressCheckoutDetails',
$v = array("GetExpressCheckoutDetailsReq" => $GetExpressCheckoutDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetExpressCheckoutDetailsResponseType');
$this->_logTransaction('GetExpressCheckoutDetails', $this->_getElapsed($start), $response);
return $response;
}
function &DoDirectPayment($DoDirectPaymentReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoDirectPaymentReq, 'XSDSimpleType')) {
if ($DoDirectPaymentReq->getVersion() == '') {
$DoDirectPaymentReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoDirectPaymentReq = $DoDirectPaymentReq->getSoapValue('DoDirectPaymentRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoDirectPayment', $this->_getElapsed($start), $res);
return $res;
}
// DoDirectPaymentReq is a ComplexType, refer to the WSDL for more info.
$DoDirectPaymentReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoDirectPaymentReq =& new SOAP_Value('DoDirectPaymentReq', false, $DoDirectPaymentReq, $DoDirectPaymentReq_attr);
$result = $this->call('DoDirectPayment',
$v = array("DoDirectPaymentReq" => $DoDirectPaymentReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoDirectPaymentResponseType');
$this->_logTransaction('DoDirectPayment', $this->_getElapsed($start), $response);
return $response;
}
function &ManagePendingTransactionStatus($ManagePendingTransactionStatusReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($ManagePendingTransactionStatusReq, 'XSDSimpleType')) {
if ($ManagePendingTransactionStatusReq->getVersion() == '') {
$ManagePendingTransactionStatusReq->setVersion(PAYPAL_WSDL_VERSION);
}
$ManagePendingTransactionStatusReq = $ManagePendingTransactionStatusReq->getSoapValue('ManagePendingTransactionStatusRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('ManagePendingTransactionStatus', $this->_getElapsed($start), $res);
return $res;
}
// ManagePendingTransactionStatusReq is a ComplexType, refer to the WSDL for more info.
$ManagePendingTransactionStatusReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$ManagePendingTransactionStatusReq =& new SOAP_Value('ManagePendingTransactionStatusReq', false, $ManagePendingTransactionStatusReq, $ManagePendingTransactionStatusReq_attr);
$result = $this->call('ManagePendingTransactionStatus',
$v = array("ManagePendingTransactionStatusReq" => $ManagePendingTransactionStatusReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'ManagePendingTransactionStatusResponseType');
$this->_logTransaction('ManagePendingTransactionStatus', $this->_getElapsed($start), $response);
return $response;
}
function &DoCapture($DoCaptureReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoCaptureReq, 'XSDSimpleType')) {
if ($DoCaptureReq->getVersion() == '') {
$DoCaptureReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoCaptureReq = $DoCaptureReq->getSoapValue('DoCaptureRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoCapture', $this->_getElapsed($start), $res);
return $res;
}
// DoCaptureReq is a ComplexType, refer to the WSDL for more info.
$DoCaptureReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoCaptureReq =& new SOAP_Value('DoCaptureReq', false, $DoCaptureReq, $DoCaptureReq_attr);
$result = $this->call('DoCapture',
$v = array("DoCaptureReq" => $DoCaptureReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoCaptureResponseType');
$this->_logTransaction('DoCapture', $this->_getElapsed($start), $response);
return $response;
}
function &DoReauthorization($DoReauthorizationReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoReauthorizationReq, 'XSDSimpleType')) {
if ($DoReauthorizationReq->getVersion() == '') {
$DoReauthorizationReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoReauthorizationReq = $DoReauthorizationReq->getSoapValue('DoReauthorizationRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoReauthorization', $this->_getElapsed($start), $res);
return $res;
}
// DoReauthorizationReq is a ComplexType, refer to the WSDL for more info.
$DoReauthorizationReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoReauthorizationReq =& new SOAP_Value('DoReauthorizationReq', false, $DoReauthorizationReq, $DoReauthorizationReq_attr);
$result = $this->call('DoReauthorization',
$v = array("DoReauthorizationReq" => $DoReauthorizationReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoReauthorizationResponseType');
$this->_logTransaction('DoReauthorization', $this->_getElapsed($start), $response);
return $response;
}
function &DoVoid($DoVoidReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoVoidReq, 'XSDSimpleType')) {
if ($DoVoidReq->getVersion() == '') {
$DoVoidReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoVoidReq = $DoVoidReq->getSoapValue('DoVoidRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoVoid', $this->_getElapsed($start), $res);
return $res;
}
// DoVoidReq is a ComplexType, refer to the WSDL for more info.
$DoVoidReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoVoidReq =& new SOAP_Value('DoVoidReq', false, $DoVoidReq, $DoVoidReq_attr);
$result = $this->call('DoVoid',
$v = array("DoVoidReq" => $DoVoidReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoVoidResponseType');
$this->_logTransaction('DoVoid', $this->_getElapsed($start), $response);
return $response;
}
function &DoAuthorization($DoAuthorizationReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoAuthorizationReq, 'XSDSimpleType')) {
if ($DoAuthorizationReq->getVersion() == '') {
$DoAuthorizationReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoAuthorizationReq = $DoAuthorizationReq->getSoapValue('DoAuthorizationRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoAuthorization', $this->_getElapsed($start), $res);
return $res;
}
// DoAuthorizationReq is a ComplexType, refer to the WSDL for more info.
$DoAuthorizationReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoAuthorizationReq =& new SOAP_Value('DoAuthorizationReq', false, $DoAuthorizationReq, $DoAuthorizationReq_attr);
$result = $this->call('DoAuthorization',
$v = array("DoAuthorizationReq" => $DoAuthorizationReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoAuthorizationResponseType');
$this->_logTransaction('DoAuthorization', $this->_getElapsed($start), $response);
return $response;
}
function &SetCustomerBillingAgreement($SetCustomerBillingAgreementReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($SetCustomerBillingAgreementReq, 'XSDSimpleType')) {
if ($SetCustomerBillingAgreementReq->getVersion() == '') {
$SetCustomerBillingAgreementReq->setVersion(PAYPAL_WSDL_VERSION);
}
$SetCustomerBillingAgreementReq = $SetCustomerBillingAgreementReq->getSoapValue('SetCustomerBillingAgreementRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('SetCustomerBillingAgreement', $this->_getElapsed($start), $res);
return $res;
}
// SetCustomerBillingAgreementReq is a ComplexType, refer to the WSDL for more info.
$SetCustomerBillingAgreementReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$SetCustomerBillingAgreementReq =& new SOAP_Value('SetCustomerBillingAgreementReq', false, $SetCustomerBillingAgreementReq, $SetCustomerBillingAgreementReq_attr);
$result = $this->call('SetCustomerBillingAgreement',
$v = array("SetCustomerBillingAgreementReq" => $SetCustomerBillingAgreementReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'SetCustomerBillingAgreementResponseType');
$this->_logTransaction('SetCustomerBillingAgreement', $this->_getElapsed($start), $response);
return $response;
}
function &GetBillingAgreementCustomerDetails($GetBillingAgreementCustomerDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetBillingAgreementCustomerDetailsReq, 'XSDSimpleType')) {
if ($GetBillingAgreementCustomerDetailsReq->getVersion() == '') {
$GetBillingAgreementCustomerDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetBillingAgreementCustomerDetailsReq = $GetBillingAgreementCustomerDetailsReq->getSoapValue('GetBillingAgreementCustomerDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetBillingAgreementCustomerDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetBillingAgreementCustomerDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetBillingAgreementCustomerDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetBillingAgreementCustomerDetailsReq =& new SOAP_Value('GetBillingAgreementCustomerDetailsReq', false, $GetBillingAgreementCustomerDetailsReq, $GetBillingAgreementCustomerDetailsReq_attr);
$result = $this->call('GetBillingAgreementCustomerDetails',
$v = array("GetBillingAgreementCustomerDetailsReq" => $GetBillingAgreementCustomerDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetBillingAgreementCustomerDetailsResponseType');
$this->_logTransaction('GetBillingAgreementCustomerDetails', $this->_getElapsed($start), $response);
return $response;
}
function &CreateBillingAgreement($CreateBillingAgreementReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($CreateBillingAgreementReq, 'XSDSimpleType')) {
if ($CreateBillingAgreementReq->getVersion() == '') {
$CreateBillingAgreementReq->setVersion(PAYPAL_WSDL_VERSION);
}
$CreateBillingAgreementReq = $CreateBillingAgreementReq->getSoapValue('CreateBillingAgreementRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('CreateBillingAgreement', $this->_getElapsed($start), $res);
return $res;
}
// CreateBillingAgreementReq is a ComplexType, refer to the WSDL for more info.
$CreateBillingAgreementReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$CreateBillingAgreementReq =& new SOAP_Value('CreateBillingAgreementReq', false, $CreateBillingAgreementReq, $CreateBillingAgreementReq_attr);
$result = $this->call('CreateBillingAgreement',
$v = array("CreateBillingAgreementReq" => $CreateBillingAgreementReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'CreateBillingAgreementResponseType');
$this->_logTransaction('CreateBillingAgreement', $this->_getElapsed($start), $response);
return $response;
}
function &DoReferenceTransaction($DoReferenceTransactionReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoReferenceTransactionReq, 'XSDSimpleType')) {
if ($DoReferenceTransactionReq->getVersion() == '') {
$DoReferenceTransactionReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoReferenceTransactionReq = $DoReferenceTransactionReq->getSoapValue('DoReferenceTransactionRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoReferenceTransaction', $this->_getElapsed($start), $res);
return $res;
}
// DoReferenceTransactionReq is a ComplexType, refer to the WSDL for more info.
$DoReferenceTransactionReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoReferenceTransactionReq =& new SOAP_Value('DoReferenceTransactionReq', false, $DoReferenceTransactionReq, $DoReferenceTransactionReq_attr);
$result = $this->call('DoReferenceTransaction',
$v = array("DoReferenceTransactionReq" => $DoReferenceTransactionReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoReferenceTransactionResponseType');
$this->_logTransaction('DoReferenceTransaction', $this->_getElapsed($start), $response);
return $response;
}
function &DoNonReferencedCredit($DoNonReferencedCreditReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoNonReferencedCreditReq, 'XSDSimpleType')) {
if ($DoNonReferencedCreditReq->getVersion() == '') {
$DoNonReferencedCreditReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoNonReferencedCreditReq = $DoNonReferencedCreditReq->getSoapValue('DoNonReferencedCreditRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoNonReferencedCredit', $this->_getElapsed($start), $res);
return $res;
}
// DoNonReferencedCreditReq is a ComplexType, refer to the WSDL for more info.
$DoNonReferencedCreditReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoNonReferencedCreditReq =& new SOAP_Value('DoNonReferencedCreditReq', false, $DoNonReferencedCreditReq, $DoNonReferencedCreditReq_attr);
$result = $this->call('DoNonReferencedCredit',
$v = array("DoNonReferencedCreditReq" => $DoNonReferencedCreditReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoNonReferencedCreditResponseType');
$this->_logTransaction('DoNonReferencedCredit', $this->_getElapsed($start), $response);
return $response;
}
function &DoUATPAuthorization($DoUATPAuthorizationReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($DoUATPAuthorizationReq, 'XSDSimpleType')) {
if ($DoUATPAuthorizationReq->getVersion() == '') {
$DoUATPAuthorizationReq->setVersion(PAYPAL_WSDL_VERSION);
}
$DoUATPAuthorizationReq = $DoUATPAuthorizationReq->getSoapValue('DoUATPAuthorizationRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('DoUATPAuthorization', $this->_getElapsed($start), $res);
return $res;
}
// DoUATPAuthorizationReq is a ComplexType, refer to the WSDL for more info.
$DoUATPAuthorizationReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$DoUATPAuthorizationReq =& new SOAP_Value('DoUATPAuthorizationReq', false, $DoUATPAuthorizationReq, $DoUATPAuthorizationReq_attr);
$result = $this->call('DoUATPAuthorization',
$v = array("DoUATPAuthorizationReq" => $DoUATPAuthorizationReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'DoUATPAuthorizationResponseType');
$this->_logTransaction('DoUATPAuthorization', $this->_getElapsed($start), $response);
return $response;
}
function &CreateRecurringPaymentsProfile($CreateRecurringPaymentsProfileReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($CreateRecurringPaymentsProfileReq, 'XSDSimpleType')) {
if ($CreateRecurringPaymentsProfileReq->getVersion() == '') {
$CreateRecurringPaymentsProfileReq->setVersion(PAYPAL_WSDL_VERSION);
}
$CreateRecurringPaymentsProfileReq = $CreateRecurringPaymentsProfileReq->getSoapValue('CreateRecurringPaymentsProfileRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('CreateRecurringPaymentsProfile', $this->_getElapsed($start), $res);
return $res;
}
// CreateRecurringPaymentsProfileReq is a ComplexType, refer to the WSDL for more info.
$CreateRecurringPaymentsProfileReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$CreateRecurringPaymentsProfileReq =& new SOAP_Value('CreateRecurringPaymentsProfileReq', false, $CreateRecurringPaymentsProfileReq, $CreateRecurringPaymentsProfileReq_attr);
$result = $this->call('CreateRecurringPaymentsProfile',
$v = array("CreateRecurringPaymentsProfileReq" => $CreateRecurringPaymentsProfileReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'CreateRecurringPaymentsProfileResponseType');
$this->_logTransaction('CreateRecurringPaymentsProfile', $this->_getElapsed($start), $response);
return $response;
}
function &GetRecurringPaymentsProfileDetails($GetRecurringPaymentsProfileDetailsReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($GetRecurringPaymentsProfileDetailsReq, 'XSDSimpleType')) {
if ($GetRecurringPaymentsProfileDetailsReq->getVersion() == '') {
$GetRecurringPaymentsProfileDetailsReq->setVersion(PAYPAL_WSDL_VERSION);
}
$GetRecurringPaymentsProfileDetailsReq = $GetRecurringPaymentsProfileDetailsReq->getSoapValue('GetRecurringPaymentsProfileDetailsRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('GetRecurringPaymentsProfileDetails', $this->_getElapsed($start), $res);
return $res;
}
// GetRecurringPaymentsProfileDetailsReq is a ComplexType, refer to the WSDL for more info.
$GetRecurringPaymentsProfileDetailsReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$GetRecurringPaymentsProfileDetailsReq =& new SOAP_Value('GetRecurringPaymentsProfileDetailsReq', false, $GetRecurringPaymentsProfileDetailsReq, $GetRecurringPaymentsProfileDetailsReq_attr);
$result = $this->call('GetRecurringPaymentsProfileDetails',
$v = array("GetRecurringPaymentsProfileDetailsReq" => $GetRecurringPaymentsProfileDetailsReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'GetRecurringPaymentsProfileDetailsResponseType');
$this->_logTransaction('GetRecurringPaymentsProfileDetails', $this->_getElapsed($start), $response);
return $response;
}
function &ManageRecurringPaymentsProfileStatus($ManageRecurringPaymentsProfileStatusReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($ManageRecurringPaymentsProfileStatusReq, 'XSDSimpleType')) {
if ($ManageRecurringPaymentsProfileStatusReq->getVersion() == '') {
$ManageRecurringPaymentsProfileStatusReq->setVersion(PAYPAL_WSDL_VERSION);
}
$ManageRecurringPaymentsProfileStatusReq = $ManageRecurringPaymentsProfileStatusReq->getSoapValue('ManageRecurringPaymentsProfileStatusRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('ManageRecurringPaymentsProfileStatus', $this->_getElapsed($start), $res);
return $res;
}
// ManageRecurringPaymentsProfileStatusReq is a ComplexType, refer to the WSDL for more info.
$ManageRecurringPaymentsProfileStatusReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$ManageRecurringPaymentsProfileStatusReq =& new SOAP_Value('ManageRecurringPaymentsProfileStatusReq', false, $ManageRecurringPaymentsProfileStatusReq, $ManageRecurringPaymentsProfileStatusReq_attr);
$result = $this->call('ManageRecurringPaymentsProfileStatus',
$v = array("ManageRecurringPaymentsProfileStatusReq" => $ManageRecurringPaymentsProfileStatusReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'ManageRecurringPaymentsProfileStatusResponseType');
$this->_logTransaction('ManageRecurringPaymentsProfileStatus', $this->_getElapsed($start), $response);
return $response;
}
function &BillOutstandingAmount($BillOutstandingAmountReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($BillOutstandingAmountReq, 'XSDSimpleType')) {
if ($BillOutstandingAmountReq->getVersion() == '') {
$BillOutstandingAmountReq->setVersion(PAYPAL_WSDL_VERSION);
}
$BillOutstandingAmountReq = $BillOutstandingAmountReq->getSoapValue('BillOutstandingAmountRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('BillOutstandingAmount', $this->_getElapsed($start), $res);
return $res;
}
// BillOutstandingAmountReq is a ComplexType, refer to the WSDL for more info.
$BillOutstandingAmountReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$BillOutstandingAmountReq =& new SOAP_Value('BillOutstandingAmountReq', false, $BillOutstandingAmountReq, $BillOutstandingAmountReq_attr);
$result = $this->call('BillOutstandingAmount',
$v = array("BillOutstandingAmountReq" => $BillOutstandingAmountReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'BillOutstandingAmountResponseType');
$this->_logTransaction('BillOutstandingAmount', $this->_getElapsed($start), $response);
return $response;
}
function &UpdateRecurringPaymentsProfile($UpdateRecurringPaymentsProfileReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($UpdateRecurringPaymentsProfileReq, 'XSDSimpleType')) {
if ($UpdateRecurringPaymentsProfileReq->getVersion() == '') {
$UpdateRecurringPaymentsProfileReq->setVersion(PAYPAL_WSDL_VERSION);
}
$UpdateRecurringPaymentsProfileReq = $UpdateRecurringPaymentsProfileReq->getSoapValue('UpdateRecurringPaymentsProfileRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('UpdateRecurringPaymentsProfile', $this->_getElapsed($start), $res);
return $res;
}
// UpdateRecurringPaymentsProfileReq is a ComplexType, refer to the WSDL for more info.
$UpdateRecurringPaymentsProfileReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$UpdateRecurringPaymentsProfileReq =& new SOAP_Value('UpdateRecurringPaymentsProfileReq', false, $UpdateRecurringPaymentsProfileReq, $UpdateRecurringPaymentsProfileReq_attr);
$result = $this->call('UpdateRecurringPaymentsProfile',
$v = array("UpdateRecurringPaymentsProfileReq" => $UpdateRecurringPaymentsProfileReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'UpdateRecurringPaymentsProfileResponseType');
$this->_logTransaction('UpdateRecurringPaymentsProfile', $this->_getElapsed($start), $response);
return $response;
}
function &ReverseTransaction($ReverseTransactionReq)
{
$start = $this->_getMicroseconds();
// Handle type objects.
if (is_a($ReverseTransactionReq, 'XSDSimpleType')) {
if ($ReverseTransactionReq->getVersion() == '') {
$ReverseTransactionReq->setVersion(PAYPAL_WSDL_VERSION);
}
$ReverseTransactionReq = $ReverseTransactionReq->getSoapValue('ReverseTransactionRequest', 'urn:ebay:api:PayPalAPI');
}
// Make sure we can find a valid WSDL endpoint for this method.
$res = $this->setEndpoint('PayPalAPIAA', PAYPAL_WSDL_VERSION);
if (PayPal::isError($res)) {
$this->_logTransaction('ReverseTransaction', $this->_getElapsed($start), $res);
return $res;
}
// ReverseTransactionReq is a ComplexType, refer to the WSDL for more info.
$ReverseTransactionReq_attr['xmlns'] = 'urn:ebay:api:PayPalAPI';
$ReverseTransactionReq =& new SOAP_Value('ReverseTransactionReq', false, $ReverseTransactionReq, $ReverseTransactionReq_attr);
$result = $this->call('ReverseTransaction',
$v = array("ReverseTransactionReq" => $ReverseTransactionReq),
array('namespace' => 'urn:ebay:api:PayPalAPI',
'soapaction' => '',
'style' => 'document',
'use' => 'literal'));
$response = $this->getResponseObject($result, 'ReverseTransactionResponseType');
$this->_logTransaction('ReverseTransaction', $this->_getElapsed($start), $response);
return $response;
}
}
| 123gohelmetsv2 | trunk/lib/paypal-sdk/PayPal/CallerServices.php | PHP | asf20 | 111,995 |
<?php
/*
* Created on Dec 2, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
class CartProduct
{
private $id;
private $name;
private $price;
private $finalPrice;
private $model;
private $quantity;
private $imageFileName;
private $shippingTypeID;
private $attributelist = array();
public function CartProduct()
{
}
public function setAttribute($objAttribute)
{
$this->attributelist[$objAttribute->getID()] = $objAttribute;
}
public function getAttributeList()
{
return $this->attributelist;
}
public function setID($id)
{
$this->id = $id;
}
public function getID()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setPrice($price)
{
$this->price = $price;
}
public function getPrice()
{
return $this->price;
}
public function setFinalPrice($finalPrice)
{
$this->finalPrice = $finalPrice;
}
public function getFinalPrice()
{
return $this->finalPrice;
}
public function setQuantity($quantity)
{
$this->quantity = $quantity;
}
public function getQuantity()
{
return $this->quantity;
}
public function setModel($model)
{
$this->model = $model;
}
public function getModel()
{
return $this->model;
}
public function setImageFileName($imageFileName)
{
$this->imageFileName = $imageFileName;
}
public function getImageFileName()
{
return $this->imageFileName;
}
public function setShippingTypeID($shippingTypeID)
{
$this->shippingTypeID = $shippingTypeID;
}
public function getShippingTypeID()
{
return $this->shippingTypeID;
}
public function getAttributePrice()
{
$attributePrice = 0;
foreach($this->attributelist as $attribute){
$attributePrice += $attribute->getPrice();
}
return $attributePrice;
}
}
?>
| 123gohelmetsv2 | trunk/lib/orders/CartProduct.php | PHP | asf20 | 2,090 |
<?php
/*
* Created on Dec 2, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
class OrdersAccount
{
private $allTotal;
private $taxTotal;
private $shippingTotal;
private $saveOff;
private $productTotal;
public function setAllTotal($allTotal)
{
$this->allTotal = $allTotal;
}
public function getAllTotal()
{
return $this->allTotal;
}
public function setTaxTotal($taxTotal)
{
$this->taxTotal = $taxTotal;
}
public function getTaxTotal()
{
return $this->taxTotal;
}
public function setShippingTotal($shippingTotal)
{
$this->shippingTotal = $shippingTotal;
}
public function getShippingTotal()
{
return $this->shippingTotal;
}
public function setSaveOff($saveOff)
{
$this->saveOff = $saveOff;
}
public function getSaveOff()
{
return $this->saveOff;
}
public function setProductTotal($productTotal)
{
$this->productTotal = $productTotal;
}
public function getProductTotal()
{
return $this->productTotal;
}
}
?>
| 123gohelmetsv2 | trunk/lib/orders/OrdersAccount.php | PHP | asf20 | 1,132 |
<?php
/*
* Created on Dec 2, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
class CartProductAttribute
{
private $id; // value ID
private $key;
private $value;
private $price;
private $pricePrefix;
public function CartProductAttribute()
{
}
public function setID($id)
{
$this->id = $id;
}
public function getID()
{
return $this->id;
}
public function setKey($key)
{
$this->key = $key;
}
public function getKey()
{
return $this->key;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function setPrice($price)
{
$this->price = $price;
}
public function getPrice()
{
return $this->price;
}
}
?>
| 123gohelmetsv2 | trunk/lib/orders/CartProductAttribute.php | PHP | asf20 | 885 |
<?php
/*
* Created on Dec 2, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
include_once("CouponImpl.php"); //--> coupon impl
include_once("CouponCustomer.php");
include_once("CouponDomain.php"); //--> coupon domain
class Cart
{
const STATUS_LOOKED = 1;
const STATUS_CHANGED = 2;
private $status = 0;
private $productlist = array();
private $coupon;
public function Cart()
{
}
public function setStatus($status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
public function setCoupon($coupon)
{
$this->coupon = $coupon;
}
public function getCoupon()
{
return $this->coupon;
}
public function setProduct($objProduct)
{
$this->productlist[] = $objProduct;
}
public function removeProduct($productID)
{
unset($this->productlist[$productID]);
}
public function getProductList()
{
return $this->productlist;
}
public function getProduct($key)
{
return $this->productlist[$key];
}
public function getProductCount()
{
return count($this->productlist);
}
public function isExisted($key)
{
if(array_key_exists($key, $this->productlist))
return true;
else
return false;
}
public function getAmount()
{
$amount = $this->getTotal();
$saveDollar = $this->getSaveOff();
if($amount > $saveDollar)
$amount -= $saveDollar;
return $amount;
}
public function getTotal()
{
$amount = 0;
foreach($this->productlist as $product){
$amount += $product->getFinalPrice() * $product->getQuantity();
$amount += $product->getAttributePrice();
}
return $amount;
}
public function getSaveOff()
{
$saveDollar = 0;
if(is_object($this->coupon) && !$this->coupon->isExpire()){
$total = $this->getTotal();
if($this->coupon->isPercent()){
$percentOff = $this->coupon->getOffValue();
if($percentOff <= 100){
$saveDollar = round($total * ($percentOff / 100), 2);
}
}else if($this->coupon->isSaveOff()){
$saeDollar = $this->coupon->getOffValue();
}
}
$saveDollar = round($saveDollar / 100, 2);
return $saveDollar * 100;
}
}
?>
| 123gohelmetsv2 | trunk/lib/orders/Cart.php | PHP | asf20 | 2,353 |
<?php
/*
* Created on Dec 3, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
class OrdersInfo
{
const EXPRESS_CHECKOUT = "ExpressCheckout";
const DIRECT_PAYMENT = "DirectPayment";
const MONEY_ORDER = "moneyOrder";
private $customerAddress;
private $deliveryAddress;
private $billingAddress;
private $account;
private $email;
private $comments;
private $payment;
private $paymentMethod;
private $shippingTypeID;
public function OrdersInfo()
{
}
public function setComments($comments)
{
$this->comments = $comments;
}
public function getComments()
{
return $this->comments;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getEmail()
{
return $this->email;
}
public function setCustomerAddress($customerAddress)
{
$this->customerAddress = $customerAddress;
}
public function getCustomerAddress()
{
return $this->customerAddress;
}
public function setDeliveryAddress($deliveryAddress)
{
$this->deliveryAddress = $deliveryAddress;
}
public function getDeliveryAddress()
{
return $this->deliveryAddress;
}
public function setBillingAddress($billingAddress)
{
$this->billingAddress = $billingAddress;
}
public function getBillingAddress()
{
return $this->billingAddress;
}
public function setAccount($account)
{
$this->account = $account;
}
public function getAccount()
{
return $this->account;
}
public function setPayment($payment)
{
$this->payment = $payment;
}
public function getPayment()
{
return $this->payment;
}
public function setPaymentMethod($paymentMethod)
{
$this->paymentMethod = $paymentMethod;
}
public function getPaymentMethod()
{
return $this->paymentMethod;
}
public function setShippingTypeID($shippingTypeID)
{
$this->shippingTypeID = $shippingTypeID;
}
public function getShippingTypeID()
{
return $this->shippingTypeID;
}
}
?>
| 123gohelmetsv2 | trunk/lib/orders/OrdersInfo.php | PHP | asf20 | 2,145 |
<?php
/*
* Created on Sep 13, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
include_once("./configure/configure.php"); //--> global var
include_once("Smarty.class.php"); //--> out template
include_once("Common.php");
include_once("UploadFiles.php"); //--> UploadFiles
include_once("Strings.php"); //--> String utils
include_once("customerSession.inc.php");
include_once("Session.php"); //-- Session
include_once("orders/Cart.php"); //--> Cart
include_once("orders/CartProduct.php"); //--> Cart
include_once("orders/CartProductAttribute.php"); //--> Cart
$common = new Common();
$objStrings = new Strings();
$objCart = new Cart(); //--> Cart
$objSession = new Session(DB_TAG_SYSTEM, SESSION_TABLE_NAME); //-- session
session_start();
if($_SESSION['cart'])
$objCart = unserialize($_SESSION['cart']);
$isLogin = false;
if($objSession->exist()) {
$isLogin = true;
}
/*----- out html -----*/
$smarty = new Smarty(); //-- out template
$smarty->template_dir = TEMPLATE_DIR;
$smarty->compile_dir = COMPILE_DIR;
$smarty->cache_dir = CACHE_DIR;
$smarty->caching = CACHING;
$smarty->cache_lifetime = CACHE_LIFETIME;
$smarty->assign('HOME_URL', HOME_URL);
$smarty->assign('HOME_URL_HTTP', HOME_URL);
//$smarty->assign('HOME_URL_HTTP', HOME_URL_HTTP);
//$smarty->assign('HOME_URL_HTTPS', HOME_URL_HTTPS);
$smarty->assign('objCart', $objCart);
$smarty->assign('objStrings', $objStrings);
if(!$smarty->isCached('sizeChart.html')){
include_once("includeCategory.php"); //--> include category
include_once("includeSpec.php"); //--> include spec
$smarty->assign('HOME_URL', HOME_URL);
$smarty->assign('categorys', $categorys);
$smarty->assign('topCategory', $topCategory);
$smarty->assign('specProducts', $specProducts);
}
$smarty->assign('isLogin', $isLogin);
$smarty->display('sizeChart.html');
?>
| 123gohelmetsv2 | trunk/sizeChart.php | PHP | asf20 | 2,002 |
<?php
/*
* Created on Sep 13, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
include_once("./configure/configure.php"); //--> global var
include_once("Smarty.class.php"); //--> out template
include_once("Common.php");
include_once("UploadFiles.php"); //--> UploadFiles
include_once("Strings.php"); //--> String utils
include_once("customerSession.inc.php");
include_once("Session.php"); //-- Session
include_once("orders/Cart.php"); //--> Cart
include_once("orders/CartProduct.php"); //--> Cart
include_once("orders/CartProductAttribute.php"); //--> Cart
$common = new Common();
$objStrings = new Strings();
$objSession = new Session(DB_TAG_SYSTEM, SESSION_TABLE_NAME); //-- session
$objCart = new Cart(); //--> Cart
session_start();
if($_SESSION['cart'])
$objCart = unserialize($_SESSION['cart']);
$isLogin = false;
if($objSession->exist()) {
$isLogin = true;
}
if(isset($_GET['page']))
$page = $_GET['page'];
else
$page = 1;
/*----- out html -----*/
$smarty = new Smarty(); //-- out template
$smarty->template_dir = TEMPLATE_DIR;
$smarty->compile_dir = COMPILE_DIR;
$smarty->cache_dir = CACHE_DIR;
$smarty->caching = CACHING;
$smarty->cache_lifetime = CACHE_LIFETIME;
$smarty->assign('HOME_URL', HOME_URL);
$smarty->assign('HOME_URL_HTTP', HOME_URL);
$smarty->assign('objCart', $objCart);
$smarty->assign('objStrings', $objStrings);
if(!$smarty->isCached('specials.html', $page)){
include_once("includeCategory.php"); //--> include category
include_once("includeSpec.php"); //--> include spec
$products = array();
$allproducts = $common->listCustom(DB_TAG_PUBLIC, 'p.id, p.price, s.newPrice finalPrice, pd.name, pd.description', "products p, products_description pd, specials s WHERE p.id = s.productID AND p.status = 'normal' AND p.id = pd.productID AND pd.languageID = $LANGEUAGE_ID AND s.expireDate > NOW()", 'ORDER BY p.id', $page, 12);
foreach($allproducts as $key => $value){
$arrImages = $common->getHash(DB_TAG_PUBLIC, "SELECT u.id, u.extName FROM upload_files u, product_images p WHERE u.id = p.imageID AND p.productID = ".$value['id']." AND type = " . UploadFiles::TYPE_IMAGE . ' ORDER BY p.isMain LIMIT 1');
if(count($arrImages) > 0){
$value['imageid'] = key($arrImages);
$value['imageExt'] = $arrImages[$value['imageid']];
}
$products[] = $value;
}
$smarty->assign('categorys', $categorys);
$smarty->assign('topCategory', $topCategory);
$smarty->assign('specProducts', $specProducts);
$smarty->assign('products', $products);
$smarty->assign('pageList', $common->getPageList());
$smarty->assign('nextPage', $common->getNextPage());
$smarty->assign('prePage', $common->getPrePage());
$smarty->assign('pageCount', $common->getPageCount());
$smarty->assign('page', $common->getPage());
}
$smarty->assign('isLogin', $isLogin);
$smarty->display('specials.html', $page);
?>
| 123gohelmetsv2 | trunk/specials.php | PHP | asf20 | 3,059 |
<?php
/*
* Created on Sep 13, 2010
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
include_once("./configure/configure.php"); //--> global var
include_once("Smarty.class.php"); //--> out template
include_once("Common.php");
include_once("UploadFiles.php"); //--> UploadFiles
include_once("Strings.php"); //--> String utils
include_once("customerSession.inc.php");
include_once("Session.php"); //-- Session
include_once("orders/Cart.php"); //--> Cart
include_once("orders/CartProduct.php"); //--> Cart
include_once("orders/CartProductAttribute.php"); //--> Cart
$common = new Common();
$objStrings = new Strings();
$objSession = new Session(DB_TAG_SYSTEM, SESSION_TABLE_NAME); //-- session
$objCart = new Cart(); //--> Cart
session_start();
if($_SESSION['cart'])
$objCart = unserialize($_SESSION['cart']);
else
$objCart = new Cart(); //--> Cart
$isLogin = false;
if($objSession->exist()) {
$isLogin = true;
}
/*----- out html -----*/
$smarty = new Smarty(); //-- out template
$smarty->template_dir = TEMPLATE_DIR;
$smarty->compile_dir = COMPILE_DIR;
$smarty->cache_dir = CACHE_DIR;
//$smarty->force_compile = true;
$smarty->debugging = false;
$smarty->caching = CACHING;
$smarty->cache_lifetime = CACHE_LIFETIME;
$smarty->assign('objCart', $objCart);
$smarty->assign('objStrings', $objStrings);
if(!$smarty->isCached('index.html')){
include_once("includeCategory.php"); //--> include category
$promoProducts = array();
$allproducts = $common->listCustom(DB_TAG_PUBLIC, 'p.id, p.price, s.descript, pd.name, pd.description', "products p, products_description pd, promotion s WHERE p.id = s.productId AND p.status = 'normal' AND p.id = pd.productID AND pd.languageID = $LANGEUAGE_ID", 'ORDER BY p.id', $page, 12);
foreach($allproducts as $key => $value){
$arrImages = $common->getHash(DB_TAG_PUBLIC, "SELECT u.id, u.extName FROM upload_files u, product_images p WHERE u.id = p.imageID AND p.productID = ".$value['id']." AND type = " . UploadFiles::TYPE_IMAGE . ' ORDER BY p.isMain LIMIT 1');
if(count($arrImages) > 0){
$value['imageid'] = key($arrImages);
$value['imageExt'] = $arrImages[$value['imageid']];
}
$promoProducts[] = $value;
}
$featured = array();
$sqlFeatured = "SELECT p.id, p.price, pd.name, pd.description FROM products p, products_description pd WHERE p.status = 'normal' AND p.isFeatured = 1 AND p.id = pd.productID AND pd.languageID = $LANGEUAGE_ID ORDER BY p.id DESC LIMIT 6";
$allFeatured = $common->getAllData(DB_TAG_PUBLIC, $sqlFeatured);
foreach($allFeatured as $key => $value){
$arrImages = $common->getHash(DB_TAG_PUBLIC, "SELECT u.id, u.extName FROM upload_files u, product_images p WHERE u.id = p.imageID AND p.productID = ".$value['id']." AND type = " . UploadFiles::TYPE_IMAGE . ' ORDER BY p.isMain LIMIT 1');
if(count($arrImages) > 0){
$value['imageid'] = key($arrImages);
$value['imageExt'] = $arrImages[$value['imageid']];
}
$featured[] = $value;
}
$products = array();
$sqlProducts = "SELECT p.id, p.price, pd.name FROM products p, products_description pd WHERE p.status = 'normal' AND p.isNew = 1 AND p.id = pd.productID AND pd.languageID = $LANGEUAGE_ID ORDER BY p.status, p.r_ordered DESC, pd.r_viewed LIMIT 6";
$allproducts = $common->getAllData(DB_TAG_PUBLIC, $sqlProducts);
foreach($allproducts as $key => $value){
$arrImages = $common->getHash(DB_TAG_PUBLIC, "SELECT u.id, u.extName FROM upload_files u, product_images p WHERE u.id = p.imageID AND p.productID = ".$value['id']." AND type = " . UploadFiles::TYPE_IMAGE . ' ORDER BY p.isMain LIMIT 1');
if(count($arrImages) > 0){
$value['imageid'] = key($arrImages);
$value['imageExt'] = $arrImages[$value['imageid']];
}
$products[] = $value;
}
include_once("includeSpec.php"); //--> include spec
$smarty->assign('HOME_URL', HOME_URL);
$smarty->assign('HOME_URL_HTTP', HOME_URL);
$smarty->assign('categorys', $categorys);
$smarty->assign('topCategory', $topCategory);
$smarty->assign('featured', $featured);
$smarty->assign('products', $products);
$smarty->assign('specProducts', $specProducts);
$smarty->assign('promoProducts', $promoProducts);
}
$smarty->assign('isLogin', $isLogin);
$smarty->display('index.html');
?>
| 123gohelmetsv2 | trunk/index.php | PHP | asf20 | 4,482 |
package zing.com;
import android.app.Activity;
import android.os.Bundle;
public class ZingActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
} | 0911b-team-5 | trunk/Zing/src/zing/com/ZingActivity.java | Java | oos | 332 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.interfaces;
import android.os.Environment;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public interface IDDBB {
//For the sdcard io
public final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
public final String QUITESLEEP_PATH = "quitesleep";
//For the sdcard & internal data app
public final String DDBB_DIR = "ddbb";
public final String DDBB_FILE = "quitesleep.db";
//Constante para especificar el nivel de profundidad de busqueda en un
//objeto
public final int DEEP = 3;
public static final String SEMAPHORE = "SEMAPHORE";
}
| 120301csr038-description | src/es/cesar/quitesleep/interfaces/IDDBB.java | Java | gpl3 | 1,438 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.syncData;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Contact;
import es.cesar.quitesleep.ddbb.Mail;
import es.cesar.quitesleep.ddbb.Phone;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.dialogs.SyncContactsDialog;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.TokenizerUtils;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class SyncContactsNew extends Thread {
final private String CLASS_NAME = getClass().getName();
private final Context context;
private int insertContact = 0;
private SyncContactsDialog syncDialog;
//-------------- Getters & Setters -------------------------//
public int getInsertContact() {
return insertContact;
}
public void setInsertContact(int insertContact) {
this.insertContact = insertContact;
}
public SyncContactsDialog getSyncDialog() {
return syncDialog;
}
public void setSyncDialog(SyncContactsDialog syncDialog) {
this.syncDialog = syncDialog;
}
//----------------------------------------------------------------------//
/**
* Constructor with all the three obligatory params for run the synchronization
* use for the first time running the application (empty db4o database
* contacts data) or for any other synchronization.
*
* @param context
* @param syncDialog
*/
public SyncContactsNew (
Context context,
SyncContactsDialog syncDialog) {
this.context = context;
this.syncDialog = syncDialog;
}
/**
* This funcion check if the db4o database is full contacts empty, so indicate
* that is the first time too run the application.
*
* @return True or false if the db4o is contact empty or not
* @see boolean
* @throws Exception
*/
public boolean isTheFirstTime () throws Exception{
try {
ClientDDBB clientDDBB = new ClientDDBB();
List<Contact> contactList = clientDDBB.getSelects().selectAllContacts();
clientDDBB.close();
if (contactList != null && contactList.size()>0)
return false;
else
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception();
}
}
/**
* Synchronize the SQLite data contacts, with at least one phone number,
* with the DB4O database.
*
* @param context
* @see insertsContacts after run and finish this function for
* check how many contacts are synchronized.
*/
public void run () {
try {
if (context != null) {
//int insertContact = 0;
ClientDDBB clientDDBB = new ClientDDBB();
//get all contacts from de ddbb
Cursor contactCursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null, // Which columns to return.
null, // WHERE clause.
null, // WHERE clause value substitution
null); // Sort order.
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Num contacts: " + contactCursor.getCount());
//Whule startCursor has content
while (contactCursor.moveToNext()) {
String contactName = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.Data.DISPLAY_NAME));
String contactId = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
//------- for debug only -------------------//
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Name: " + contactName + "\tId: " +
contactId + "\thasPhone: " + hasPhone);
boolean res = Boolean.parseBoolean(hasPhone);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "boolean: " + res);
//---------------------------------------------------//
//If the used contact has at least one phone number, we
//insert it in the db4o ddbb, else not insert.
if (hasPhone.equals("1")) {
//Create the db4o contact object.
Contact contact = new Contact(contactId, contactName);
//insert the contact object
clientDDBB.getInserts().insertContact(contact);
insertContact ++;
//where clausule
String where = ContactsContract.Data.CONTACT_ID + " = " +
contactId + " AND " + ContactsContract.Data.MIMETYPE +
" = '" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE +
"'";
Cursor phonesCursor = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
where,
null,
null);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "count: " + phonesCursor.getCount());
List<String> phonesList = new ArrayList<String>(phonesCursor.getCount());
//While the phonesCursor has content
while (phonesCursor.moveToNext()) {
String phoneNumber = phonesCursor.getString(
phonesCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phonesList.add(phoneNumber);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "phone: " + phoneNumber);
}
//close the phones cursor
phonesCursor.close();
//create the phones object asociated to contacts
createPhoneObjects(contact, phonesList, clientDDBB);
//Get all mail from the contact
Cursor mailCursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,
null,
null);
if (mailCursor.getCount() > 0) {
List<String> mailsList = new ArrayList<String>(mailCursor.getColumnCount());
//While the emailsCursor has content
while (mailCursor.moveToNext()) {
//This would allow you get several email addresses
String emailAddress = mailCursor.getString(
mailCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Email.DATA));
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "email: " + emailAddress);
mailsList.add(emailAddress);
}
//Create the mail objects asociated to every contact
createMailObjects(contact, mailsList, clientDDBB);
}
//close the email cursor
mailCursor.close();
}//end hasPhone
//create the Schedule object if not have been created previously
createSchedule(clientDDBB);
//Commit the transaction
clientDDBB.commit();
}//end contact cursor
//return insertContact;
}//end context!=null
else
//return -1;
insertContact = -1;
//this.sleep(5000);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
//return -1;
insertContact = -1;
}finally {
//Hide and dismiss de synchronization dialog
syncDialog.stopDialog(context);
}
}
/**
*
* @param contact
* @param phonesList
* @param clientDDBB
* @return the number of phones created
* @see int
*/
private int createPhoneObjects (
Contact contact,
List<String> phonesList,
ClientDDBB clientDDBB) {
try {
int numPhones = 0;
for (int i=0; i<phonesList.size(); i++) {
/* Here parse the original phone number, wich, by default
* contains x dash by other wich contains nothing delim.
*/
String newPhone = TokenizerUtils.tokenizerPhoneNumber(phonesList.get(i), null);
Phone phone = new Phone(contact, newPhone);
numPhones ++;
clientDDBB.getInserts().insertPhone(phone);
}
return numPhones;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
*
* @param contact
* @param mailsList
* @param clientDDBB
* @return the number of mails created (inserted)
* @see int
*/
private int createMailObjects (
Contact contact,
List<String> mailsList,
ClientDDBB clientDDBB) {
try {
int numMails = 0;
for (int i=0; i<mailsList.size(); i++) {
Mail mail = new Mail(contact, mailsList.get(i));
numMails ++;
clientDDBB.getInserts().insertMail(mail);
}
return numMails;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
* Create the Schedule object if not was created previously. This object
* is an empty Schedule.
*
* @param clientDDBB
* @return true if Schedule object is created or false is not
* @see boolean
*/
private boolean createSchedule (ClientDDBB clientDDBB) {
try {
Schedule schedule = clientDDBB.getSelects().selectSchedule();
if (schedule == null) {
schedule = new Schedule();
clientDDBB.getInserts().insertSchedule(schedule);
return true;
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/syncData/SyncContactsNew.java | Java | gpl3 | 10,713 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.syncData;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Contact;
import es.cesar.quitesleep.ddbb.Mail;
import es.cesar.quitesleep.ddbb.Phone;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.dialogs.SyncContactsDialog;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.TokenizerUtils;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class SyncContactsRefresh extends Thread {
final private String CLASS_NAME = getClass().getName();
private final Context context;
private int insertContact = 0;
private SyncContactsDialog syncDialog;
//-------------- Getters & Setters -------------------------//
public int getInsertContact() {
return insertContact;
}
public void setInsertContact(int insertContact) {
this.insertContact = insertContact;
}
public SyncContactsDialog getSyncDialog() {
return syncDialog;
}
public void setSyncDialog(SyncContactsDialog syncDialog) {
this.syncDialog = syncDialog;
}
//----------------------------------------------------------------------//
/**
* Constructor with all the three obligatory params for run the synchronization
* use for the first time running the application (empty db4o database
* contacts data) or for any other synchronization.
*
* @param context
* @param syncDialog
*/
public SyncContactsRefresh (
Context context,
SyncContactsDialog syncDialog) {
this.context = context;
this.syncDialog = syncDialog;
}
/**
* Delete all objects associated to Contacts, Mail, Phones, and Banned.
* @return
*/
public boolean deleteAll () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
int deleteContacts = clientDDBB.getDeletes().deleteAllContacts();
int deletePhones = clientDDBB.getDeletes().deleteAllPhones();
int deleteMails = clientDDBB.getDeletes().deleteAllMails();
int deleteBanned = clientDDBB.getDeletes().deleteAllBanned();
int deleteCallLog = clientDDBB.getDeletes().deleteAllCallLog();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteContacts: " + deleteContacts);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deletePhones: " + deletePhones);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteMails: " + deleteMails);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteBanned: " + deleteBanned);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "deleteCallLog:" + deleteCallLog);
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Synchronize the SQLite data contacts, with at least one phone number,
* with the DB4O database.
*
* @param context
* @see insertsContacts after run and finish this function for
* check how many contacts are synchronized.
*/
public void run () {
try {
if (deleteAll())
syncContacts();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}finally {
//Hide and dismiss de synchronization dialog
syncDialog.stopDialog(context);
}
}
/**
* Sync contacts from the ddbb SQLite to the DB4O ddbb
*/
private void syncContacts () {
try {
if (context != null) {
//int insertContact = 0;
ClientDDBB clientDDBB = new ClientDDBB();
//get all contacts from de ddbb
Cursor contactCursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Num contacts: " + contactCursor.getCount());
//Whule startCursor has content
while (contactCursor.moveToNext()) {
String contactName = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.Data.DISPLAY_NAME));
String contactId = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = contactCursor.getString(contactCursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
//------- for debug only -------------------//
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Name: " + contactName + "\tId: " +
contactId + "\thasPhone: " + hasPhone);
boolean res = Boolean.parseBoolean(hasPhone);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "boolean: " + res);
//---------------------------------------------------//
//If the used contact has at least one phone number, we
//insert it in the db4o ddbb, else not insert.
if (hasPhone.equals("1")) {
//Create the db4o contact object.
Contact contact = new Contact(contactId, contactName);
//insert the contact object
clientDDBB.getInserts().insertContact(contact);
insertContact ++;
//where clausule
String where = ContactsContract.Data.CONTACT_ID + " = " +
contactId + " AND " + ContactsContract.Data.MIMETYPE +
" = '" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE +
"'";
Cursor phonesCursor = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
where,
null,
null);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "count: " + phonesCursor.getCount());
List<String> phonesList = new ArrayList<String>(phonesCursor.getCount());
//While the phonesCursor has content
while (phonesCursor.moveToNext()) {
String phoneNumber = phonesCursor.getString(
phonesCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phonesList.add(phoneNumber);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "phone: " + phoneNumber);
}
//close the phones cursor
phonesCursor.close();
//create the phones object asociated to contacts
createPhoneObjects(contact, phonesList, clientDDBB);
//Get all mail from the contact
Cursor mailCursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,
null,
null);
if (mailCursor.getCount() > 0) {
List<String> mailsList = new ArrayList<String>(mailCursor.getColumnCount());
//While the emailsCursor has content
while (mailCursor.moveToNext()) {
//This would allow you get several email addresses
String emailAddress = mailCursor.getString(
mailCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Email.DATA));
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "email: " + emailAddress);
mailsList.add(emailAddress);
}
//Create the mail objects asociated to every contact
createMailObjects(contact, mailsList, clientDDBB);
}
//close the email cursor
mailCursor.close();
}//end hasPhone
//create the Schedule object if not have been created previously
createSchedule(clientDDBB);
//Commit the transaction
clientDDBB.commit();
}//end contact cursor
}//end context!=null
else
//return -1;
insertContact = -1;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
insertContact = -1;
}
}
/**
*
* @param contact
* @param phonesList
* @param clientDDBB
* @return the number of phones created
* @see int
*/
private int createPhoneObjects (
Contact contact,
List<String> phonesList,
ClientDDBB clientDDBB) {
try {
int numPhones = 0;
for (int i=0; i<phonesList.size(); i++) {
/* Here parse the original phone number, wich, by default
* contains x dash by other wich contains nothing delim.
*/
String newPhone = TokenizerUtils.tokenizerPhoneNumber(phonesList.get(i), null);
Phone phone = new Phone(contact, newPhone);
numPhones ++;
clientDDBB.getInserts().insertPhone(phone);
}
return numPhones;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
*
* @param contact
* @param mailsList
* @param clientDDBB
* @return the number of mails created (inserted)
* @see int
*/
private int createMailObjects (
Contact contact,
List<String> mailsList,
ClientDDBB clientDDBB) {
try {
int numMails = 0;
for (int i=0; i<mailsList.size(); i++) {
Mail mail = new Mail(contact, mailsList.get(i));
numMails ++;
clientDDBB.getInserts().insertMail(mail);
}
return numMails;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
* Create the Schedule object if not was created previously. This object
* is an empty Schedule.
*
* @param clientDDBB
* @return true if Schedule object is created or false is not
* @see boolean
*/
private boolean createSchedule (ClientDDBB clientDDBB) {
try {
Schedule schedule = clientDDBB.getSelects().selectSchedule();
if (schedule == null) {
schedule = new Schedule();
clientDDBB.getInserts().insertSchedule(schedule);
return true;
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/syncData/SyncContactsRefresh.java | Java | gpl3 | 11,338 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.activities;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.dialogs.WarningDialog;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.subactivities.About;
import es.cesar.quitesleep.subactivities.AddBanned;
import es.cesar.quitesleep.subactivities.DeleteBanned;
import es.cesar.quitesleep.subactivities.Help;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ContactsTab extends Activity implements OnClickListener {
final private String CLASS_NAME = getClass().getName();
final private int WARNING_DIALOG = 1;
//Ids for the button widgets
private final int addBannedId = R.id.contacts_button_addBanned;
private final int deleteBannedId = R.id.contacts_button_deleteBanned;
private final int syncContactsID = R.id.contacts_button_syncContacts;
//Ids for option menu
final int aboutMenuId = R.id.menu_information_about;
final int helpMenuId = R.id.menu_information_help;
//Ids for warning dialog
private WarningDialog warningDialog;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactstab);
try {
//Instanciate all buttons
Button addBannedButton = (Button)findViewById(addBannedId);
Button deleteBannedButton = (Button)findViewById(deleteBannedId);
Button syncContactsButton = (Button)findViewById(syncContactsID);
//Define the buttons listener
addBannedButton.setOnClickListener(this);
deleteBannedButton.setOnClickListener(this);
syncContactsButton.setOnClickListener(this);
warningDialog = new WarningDialog(this, ConfigAppValues.WARNING_SYNC_CONTACTS);
}catch (Exception e) {
e.printStackTrace();
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, e.toString());
}
}
/**
* onClick method for the view widgets
*
* @param view View of the used widget
*/
public void onClick (View view) {
int viewId = view.getId();
switch (viewId) {
case addBannedId:
Intent intentAddContacts = new Intent(this, AddBanned.class);
startActivityForResult(intentAddContacts, ConfigAppValues.REQCODE_ADD_BANNED);
break;
case deleteBannedId:
Intent intentViewContacts = new Intent(this, DeleteBanned.class);
startActivityForResult(intentViewContacts, ConfigAppValues.REQCODE_DELETE_BANNED);
break;
case syncContactsID:
showDialog(WARNING_DIALOG);
break;
}
}
/**
* Create the activity dialogs used for it
*
* @param id
* @return the dialog for the option specified
* @see Dialog
*/
@Override
protected Dialog onCreateDialog (int id) {
Dialog dialog;
switch (id) {
case WARNING_DIALOG:
if (QSLog.DEBUG_D) QSLog.d(CLASS_NAME, "Create the WarningDialog for 1st time");
dialog = warningDialog.getAlertDialog();
break;
default:
dialog = null;
}
return dialog;
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
//TODO
if (QSLog.DEBUG_D) QSLog.d(CLASS_NAME, "RequestCode: " + requestCode + "\nResultCode: " + resultCode);
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
try {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.informationmenu, menu);
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* @param item
* @return boolean
*/
@Override
public boolean onOptionsItemSelected (MenuItem item) {
try {
switch (item.getItemId()) {
case aboutMenuId:
Intent intentAbout = new Intent(this, About.class);
startActivityForResult(intentAbout, ConfigAppValues.LAUNCH_ABOUT);
break;
case helpMenuId:
Intent intentHelp = new Intent(this, Help.class);
startActivityForResult(intentHelp, ConfigAppValues.LAUNCH_ABOUT);
break;
default:
break;
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/activities/ContactsTab.java | Java | gpl3 | 5,501 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.activities;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.dialogs.SyncContactsDialog;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.syncData.SyncContactsNew;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* @version 1.0, 02-21-2010
*
* Main class for start QuiteSleep App, this class implement the tabs wigets
* to show them.
*
*/
public class Main extends TabActivity {
final String CLASS_NAME = getClass().getName();
@Override
public void onCreate (Bundle savedInstanceState) {
try {
//Set the min api level for the application, used for choice differents
//api methods for differents api levels.
ConfigAppValues.setMinApiLevel(getApplicationInfo().targetSdkVersion);
//Set the app context for get the ddbb file and other file access
if (ConfigAppValues.getContext() == null)
ConfigAppValues.setContext(this);
if (QSLog.DEBUG_I)QSLog.i(CLASS_NAME, "SDK Version: " +
String.valueOf(ConfigAppValues.getMinApiLevel()));
super.onCreate(savedInstanceState);
//Create the app top bar
createAppBar();
//Sync the databases if the db4o database is empty (first time run the app)
syncDatabases();
//Resource object to get Drawables
Resources resources = getResources();
//The activity tabHost
final TabHost tabHost = getTabHost();
//Reusable TabSpec for each tab
final TabHost.TabSpec tabSpec = null;
//Reusable intent for each tab
final Intent intent = null;
//------------ Contacts Tab ------------------------------//
createContactsTab(intent, tabSpec, tabHost, resources);
//------------ Schedule Tab --------------------------//
createScheduleTab(intent, tabSpec, tabHost, resources);
//------------ Settings Tab --------------------------//
createSettingsTab(intent, tabSpec, tabHost, resources);
//------------- Logs Tab -----------------------------//
createLogsTab(intent, tabSpec, tabHost, resources);
//Set the init (main) tab
tabHost.setCurrentTab(0);
}catch (Exception e) {
Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Create the Application Title Bar in top of the activity
*
* @throws Exception
*/
private void createAppBar () throws Exception {
try {
//Put an app icon to the upper left of the screen
Window window = getWindow();
window.requestFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.group_tabs);
window.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.quitesleep);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception();
}
}
/**
* Sync the contacts data between SQLite and DB4O databases the first time
* if the db4o database is empty.
* It is done used one thread for it.
*/
private void syncDatabases () {
try {
SyncContactsDialog syncDialog = new SyncContactsDialog();
SyncContactsNew syncContacts =
new SyncContactsNew(this, syncDialog);
//Only if the db4o database is empty, we proceed
//with the synchronization, otherwise we don't anything
if (syncContacts.isTheFirstTime()) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Proceed with the synchronization for the first time");
syncDialog.showDialogFirstTime(this);
syncContacts.start();
}else
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "The db4o database already contains data contacts");
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error();
}
}
/**
* Create the Contacts Tab
*
* @param intent
* @param tabSpec
* @param tabHost
* @param resources
* @throws Exception
*/
private void createContactsTab (
Intent intent,
TabSpec tabSpec,
TabHost tabHost,
Resources resources) throws Exception {
try {
//--------------- Contacts Tab ----------------------//
//Create an intent to launch an Activiy for the tab (to be reused)
intent = new Intent().setClass(this, ContactsTab.class);
//Get the string resource from the string xml set constants
CharSequence contactsLabel = getString(R.string.contacts_tab_label);
//Initialize a TabSpec for each tab and add it to the TabHost. Also
//we add the intent to the tab for when it push, use the intent added
//(go to the clock tab)
tabSpec = tabHost.newTabSpec(contactsLabel.toString()).setIndicator(
contactsLabel,
resources.getDrawable(R.drawable.contactstab)).setContent(intent);
//Add the TabSpec to the TabHost
tabHost.addTab(tabSpec);
}catch (Exception e) {
e.printStackTrace();
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception(e.toString());
}
}
/**
* Create the Schedule Tab
*
* @param intent
* @param tabSpec
* @param tabHost
* @param resources
* @throws Exception
*/
private void createScheduleTab (
Intent intent,
TabSpec tabSpec,
TabHost tabHost,
Resources resources) throws Exception {
try {
//------------ Schedule Tab --------------------------//
intent = new Intent().setClass(this, ScheduleTab.class);
CharSequence scheduleLabel = getString(R.string.schedule_tab_label);
tabSpec = tabHost.newTabSpec(scheduleLabel.toString()).setIndicator(
scheduleLabel,
resources.getDrawable(R.drawable.scheduletab)).setContent(intent);
tabHost.addTab(tabSpec);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception(e.toString());
}
}
/**
*
* @param intent
* @param tabSpec
* @param tabHost
* @param resources
* @throws Exception
*/
private void createSettingsTab (
Intent intent,
TabSpec tabSpec,
TabHost tabHost,
Resources resources) throws Exception {
try {
//------------ Settings Tab --------------------------//
intent = new Intent().setClass(this, SettingsTab.class);
CharSequence messageLabel = getString(R.string.settings_tab_label);
tabSpec = tabHost.newTabSpec(messageLabel.toString()).setIndicator(
messageLabel,
resources.getDrawable(R.drawable.settingstab)).setContent(intent);
tabHost.addTab(tabSpec);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception(e.toString());
}
}
/**
*
* @param intent
* @param tabSpec
* @param tabHost
* @param resources
* @throws Exception
*/
private void createLogsTab (
Intent intent,
TabSpec tabSpec,
TabHost tabHost,
Resources resources) throws Exception {
try {
//------------ Logs Tab --------------------------//
intent = new Intent().setClass(this, LogsTab.class);
CharSequence messageLabel = getString(R.string.logs_tab_label);
tabSpec = tabHost.newTabSpec(messageLabel.toString()).setIndicator(
messageLabel,
resources.getDrawable(R.drawable.logstab)).setContent(intent);
tabHost.addTab(tabSpec);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception(e.toString());
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/activities/Main.java | Java | gpl3 | 8,860 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.notifications.QuiteSleepNotification;
import es.cesar.quitesleep.operations.StartStopServicesOperations;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.subactivities.About;
import es.cesar.quitesleep.subactivities.Help;
import es.cesar.quitesleep.subactivities.MailSettings;
import es.cesar.quitesleep.subactivities.SmsSettings;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@mgail.com
*
*/
public class SettingsTab extends Activity implements OnClickListener {
private final String CLASS_NAME = getClass().getName();
//Ids for the button widgets
final int mailButtonId = R.id.settings_button_mail;
final int smsButtonId = R.id.settings_button_sms;
final int serviceToggleButtonId = R.id.settings_togglebutton_service;
//Ids for option menu
final int aboutMenuId = R.id.menu_information_about;
final int helpMenuId = R.id.menu_information_help;
//Activity buttons
private Button mailButton;
private Button smsButton;
private ToggleButton serviceToggleButton;
//Notification
//private NotificationManager notificationManager;
//final private int notificationId = R.layout.quitesleep_notification;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settingstab);
//All Activity buttons
mailButton = (Button)findViewById(mailButtonId);
smsButton = (Button)findViewById(smsButtonId);
serviceToggleButton = (ToggleButton)findViewById(serviceToggleButtonId);
//Define all button listeners
mailButton.setOnClickListener(this);
smsButton.setOnClickListener(this);
serviceToggleButton.setOnClickListener(this);
//Get the notification manager service
//notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
/* Set the previous saved state in the ddbb in the widgets that need
* the saved state, such as toggle button.
*/
setDefaultSavedData();
}
/**
* Listener for all buttons in this Activity
*/
public void onClick (View view) {
int viewId = view.getId();
switch (viewId) {
case mailButtonId:
Intent intentMailSettings = new Intent(this, MailSettings.class);
startActivityForResult(intentMailSettings, ConfigAppValues.REQCODE_MAIL_SETTINGS);
break;
case smsButtonId:
Intent intentSmsSettings = new Intent(this, SmsSettings.class);
startActivityForResult(intentSmsSettings, ConfigAppValues.REQCODE_SMS_SETTINGS);
break;
case serviceToggleButtonId:
startStopServiceProcess();
QuiteSleepNotification.showNotification(
this,
serviceToggleButton.isChecked());
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
try {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.informationmenu, menu);
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* @param item
* @return boolean
*/
@Override
public boolean onOptionsItemSelected (MenuItem item) {
try {
switch (item.getItemId()) {
case aboutMenuId:
Intent intentAbout = new Intent(this, About.class);
startActivityForResult(intentAbout, ConfigAppValues.LAUNCH_ABOUT);
break;
case helpMenuId:
Intent intentHelp = new Intent(this, Help.class);
startActivityForResult(intentHelp, ConfigAppValues.LAUNCH_ABOUT);
break;
default:
break;
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Put the ddbb saved data in the activity widgets if someone need to
* chage this state using a previous save data.
*/
private void setDefaultSavedData () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
serviceToggleButton.setChecked(settings.isQuiteSleepServiceState());
}else
serviceToggleButton.setChecked(false);
clientDDBB.close();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Function that depends the serviceToggleButton state try to start the
* QuiteSleep incoming call service or stop it.
*/
private void startStopServiceProcess () {
try {
boolean result = StartStopServicesOperations.startStopQuiteSleepService(
serviceToggleButton.isChecked());
if (serviceToggleButton.isChecked()) {
/* Deactivate the notification toast because now use the
* status bar notification
*/
/*
if (result)
//All right, start the service was ok!
Toast.makeText(
this,
this.getString(
R.string.settings_toast_start_service),
Toast.LENGTH_SHORT).show();
else
//An error has ocurred!!
Toast.makeText(
this,
this.getString(
R.string.settings_toast_fail_service),
Toast.LENGTH_SHORT).show();
*/
}else {
if (result)
//All right, stop the service was ok!
if (QSToast.RELEASE) QSToast.r(
this,
this.getString(
R.string.settings_toast_stop_service),
Toast.LENGTH_SHORT);
else
//An error has ocurred!!
if (QSToast.RELEASE) QSToast.r(
this,
this.getString(
R.string.settings_toast_fail_service),
Toast.LENGTH_SHORT);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/*
@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
*/
}
| 120301csr038-description | src/es/cesar/quitesleep/activities/SettingsTab.java | Java | gpl3 | 7,781 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.activities;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.dialogs.EndTimeDialog;
import es.cesar.quitesleep.dialogs.StartTimeDialog;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.subactivities.About;
import es.cesar.quitesleep.subactivities.Help;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ScheduleTab extends Activity implements OnClickListener {
private final String CLASS_NAME = getClass().getName();
private final int START_TIME_DIALOG = 0;
private final int END_TIME_DIALOG = 1;
//Ids for the button widgets
private final int startTimeButtonId = R.id.schedule_button_startTime;
private final int endTimeButtonId = R.id.schedule_button_endTime;
private final int daysWeekButtonId = R.id.schedule_button_daysweek;
//Ids for thextViews widgets
private final int startTimeLabelId = R.id.schedule_textview_startTime;
private final int endTimeLabelId = R.id.schedule_textview_endTime;
//Days of the week checkboxes Ids
private final int mondayCheckId = R.id.schedule_checkbox_monday;
private final int tuesdayCheckId = R.id.schedule_checkbox_tuesday;
private final int wednesdayCheckId = R.id.schedule_checkbox_wednesday;
private final int thursdayCheckId = R.id.schedule_checkbox_thursday;
private final int fridayCheckId = R.id.schedule_checkbox_friday;
private final int saturdayCheckId = R.id.schedule_checkbox_saturday;
private final int sundayCheckId = R.id.schedule_checkbox_sunday;
//Used dialogs in this activity
private StartTimeDialog startTimeDialog;
private EndTimeDialog endTimeDialog;
//labels for start and end times
private TextView startTimeLabel;
private TextView endTimeLabel;
//Days of the week checkboxes
private CheckBox mondayCheck;
private CheckBox tuesdayCheck;
private CheckBox wednesdayCheck;
private CheckBox thursdayCheck;
private CheckBox fridayCheck;
private CheckBox saturdayCheck;
private CheckBox sundayCheck;
//Ids for option menu
final int aboutMenuId = R.id.menu_information_about;
final int helpMenuId = R.id.menu_information_help;
final private String CALCULATOR_FONT = "fonts/calculator_script_mt.ttf";
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scheduletab);
startTimeDialog = new StartTimeDialog(this);
endTimeDialog = new EndTimeDialog(this);
Button startTimeButton = (Button)findViewById(startTimeButtonId);
Button endTimeButton = (Button)findViewById(endTimeButtonId);
Button daysWeekButton = (Button)findViewById(daysWeekButtonId);
//--------- Define our own text style used a custom font ------//
startTimeLabel = (TextView)findViewById(startTimeLabelId);
endTimeLabel = (TextView)findViewById(endTimeLabelId);
Typeface face = Typeface.createFromAsset(getAssets(), CALCULATOR_FONT);
startTimeLabel.setTypeface(face);
endTimeLabel.setTypeface(face);
//-------------------------------------------------------------------//
//Sets the timeLabes into start and end time dialogs for update the changes
startTimeDialog.setStartTimeLabel(startTimeLabel);
endTimeDialog.setEndTimeLabel(endTimeLabel);
//Instantiate the days of the week checkboxes
mondayCheck = (CheckBox)findViewById(mondayCheckId);
tuesdayCheck = (CheckBox)findViewById(tuesdayCheckId);
wednesdayCheck = (CheckBox)findViewById(wednesdayCheckId);
thursdayCheck = (CheckBox)findViewById(thursdayCheckId);
fridayCheck = (CheckBox)findViewById(fridayCheckId);
saturdayCheck = (CheckBox)findViewById(saturdayCheckId);
sundayCheck = (CheckBox)findViewById(sundayCheckId);
//Define the onClick listeners
startTimeButton.setOnClickListener(this);
endTimeButton.setOnClickListener(this);
daysWeekButton.setOnClickListener(this);
/* Set the default saved data when this activity is run for first time
* (not for first time globally, else for all times that we run
* the application and show this activity for first time)
*/
setDefaultSavedData();
}
/**
* Listener for all buttons in this Activity
*/
public void onClick (View view) {
int viewId = view.getId();
switch (viewId) {
case startTimeButtonId:
showDialog(START_TIME_DIALOG);
break;
case endTimeButtonId:
showDialog(END_TIME_DIALOG);
break;
case daysWeekButtonId:
saveDayWeeksSelection();
break;
}
}
/**
* For the first time that create the dialogs
*/
@Override
protected Dialog onCreateDialog (int id) {
Dialog dialog;
switch (id) {
case START_TIME_DIALOG:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the StartTimeDialog for 1st time");
dialog = startTimeDialog.getTimePickerDialog();
break;
case END_TIME_DIALOG:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Create the EndTimeDialog for 1st time");
dialog = endTimeDialog.getTimePickerDialog();
break;
default:
dialog = null;
}
return dialog;
}
/**
* This function prepare the dalogs every time to call for some of this
*
* @param int
* @param dialog
*/
@Override
protected void onPrepareDialog (int idDialog, Dialog dialog) {
try {
switch (idDialog) {
case START_TIME_DIALOG:
break;
case END_TIME_DIALOG:
break;
default:
break;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
//TODO
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "en onActiviryResult");
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
try {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.informationmenu, menu);
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* @param item
* @return boolean
*/
@Override
public boolean onOptionsItemSelected (MenuItem item) {
try {
switch (item.getItemId()) {
case aboutMenuId:
Intent intentAbout = new Intent(this, About.class);
startActivityForResult(intentAbout, ConfigAppValues.LAUNCH_ABOUT);
break;
case helpMenuId:
Intent intentHelp = new Intent(this, Help.class);
startActivityForResult(intentHelp, ConfigAppValues.LAUNCH_ABOUT);
break;
default:
break;
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Save the days of the weeks checkboxes state into a Schedule object from the
* database. If the Schedule object isn't create, we don't do nothing, not save the
* checkboxes state.
*
* @return true or false if the schedule save was good or not
* @see boolean
*/
private boolean saveDayWeeksSelection () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Schedule schedule = clientDDBB.getSelects().selectSchedule();
if (schedule != null) {
schedule.setMonday(mondayCheck.isChecked());
schedule.setTuesday(tuesdayCheck.isChecked());
schedule.setWednesday(wednesdayCheck.isChecked());
schedule.setThursday(thursdayCheck.isChecked());
schedule.setFriday(fridayCheck.isChecked());
schedule.setSaturday(saturdayCheck.isChecked());
schedule.setSunday(sundayCheck.isChecked());
clientDDBB.getInserts().insertSchedule(schedule);
clientDDBB.commit();
clientDDBB.close();
if (QSToast.RELEASE) QSToast.r(
this,
this.getString(
R.string.schedule_toast_daysweek_ok),
Toast.LENGTH_SHORT);
return true;
}else {
if (QSToast.RELEASE) QSToast.r(
this,
this.getString(
R.string.schedule_toast_daysweek_ko),
Toast.LENGTH_SHORT);
return false;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error(e.toString());
}
}
/**
* Set the default saved data in the start and end time labels and
* all checkboxes associated to a day of the week.
*/
private void setDefaultSavedData () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Schedule schedule = clientDDBB.getSelects().selectSchedule();
if (schedule != null) {
if (schedule.getStartFormatTime()!= null &&
!schedule.getStartFormatTime().equals(""))
startTimeLabel.setText(schedule.getStartFormatTime());
if (schedule.getEndFormatTime() != null &&
!schedule.getEndFormatTime().equals(""))
endTimeLabel.setText(schedule.getEndFormatTime());
mondayCheck.setChecked(schedule.isMonday());
tuesdayCheck.setChecked(schedule.isTuesday());
wednesdayCheck.setChecked(schedule.isWednesday());
thursdayCheck.setChecked(schedule.isThursday());
fridayCheck.setChecked(schedule.isFriday());
saturdayCheck.setChecked(schedule.isSaturday());
sundayCheck.setChecked(schedule.isSunday());
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/activities/ScheduleTab.java | Java | gpl3 | 11,105 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.activities;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.ddbb.CallLog;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.dialogs.WarningDialog;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class LogsTab extends ListActivity {
//Constants
final private String CLASS_NAME = this.getClass().getName();
final private int WARNING_REMOVE_DIALOG = 0;
final private int WARNING_REFRESH_DIALOG = 1;
//Widgets Ids
private final int removeCallLogMenuId = R.id.menu_calllog_remove;
private final int refreshCallLogMenuId = R.id.menu_calllog_refresh;
//Widgets
private WarningDialog warningRemoveDialog;
private WarningDialog warningRefreshDialog;
private ArrayAdapter<String> arrayAdapter;
//this activity
private Activity thisActivity = this;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
warningRemoveDialog = new WarningDialog(
this,
ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS);
warningRefreshDialog = new WarningDialog(
this,
ConfigAppValues.WARNING_REFRESH_CALL_LOG);
getAllCallLogList();
}
/**
* Get all CallLog list from de ddbb
*/
private void getAllCallLogList () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
List<CallLog> callLogList = clientDDBB.getSelects().selectAllCallLog();
List<String> callLogListString = convertCallLogList(callLogList);
if (callLogListString != null) {
arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.logstab,
R.id.logstab_textview_contact,
callLogListString);
setListAdapter(arrayAdapter);
}
clientDDBB.close();
}catch (Exception e) {
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
*
* @param contactList
* @return The contactList but only the list with the name contacts
* @see List<String>
*/
private List<String> convertCallLogList (List<CallLog> callLogList) throws Exception {
try {
if (callLogList != null && callLogList.size()>0) {
List<String> callLogListString = new ArrayList<String>();
for (int i=0; i<callLogList.size(); i++) {
String callLogString = callLogList.get(i).toString();
if (callLogString != null)
callLogListString.add(callLogString);
}
return callLogListString;
}
return null;
}catch (Exception e) {
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception();
}
}
/**
* Create the activity dialogs used for it
*
* @param id
* @return the dialog for the option specified
* @see Dialog
*/
@Override
protected Dialog onCreateDialog (int id) {
Dialog dialog;
switch (id) {
case WARNING_REMOVE_DIALOG:
dialog = warningRemoveDialog.getAlertDialog();
break;
case WARNING_REFRESH_DIALOG:
dialog = warningRefreshDialog.getAlertDialog();
break;
default:
dialog = null;
}
return dialog;
}
/**
* This function prepare the dalogs every time to call for some of this
*
* @param int
* @param dialog
*/
@Override
protected void onPrepareDialog (int idDialog, Dialog dialog) {
try {
switch (idDialog) {
case WARNING_REMOVE_DIALOG:
warningRemoveDialog.setContext(this);
warningRemoveDialog.setArrayAdapter(arrayAdapter);
warningRemoveDialog.setHandler(handlerRemove);
break;
case WARNING_REFRESH_DIALOG:
warningRefreshDialog.setContext(this);
warningRefreshDialog.setArrayAdapter(arrayAdapter);
warningRefreshDialog.setHandler(handlerRefresh);
break;
default:
break;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
try {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.calllogmenu, menu);
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* @param item
* @return boolean
*/
@Override
public boolean onOptionsItemSelected (MenuItem item) {
try {
switch (item.getItemId()) {
case removeCallLogMenuId:
showDialog(WARNING_REMOVE_DIALOG);
break;
case refreshCallLogMenuId:
showDialog(WARNING_REFRESH_DIALOG);
break;
default:
break;
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E) QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Handler for clear the listView and the array adapter once we have been
* add all contacts to the banned list
*/
public final Handler handlerRemove = new Handler() {
public void handleMessage(Message message) {
if (arrayAdapter != null && arrayAdapter.getCount()>0) {
//int count = arrayAdapter.getCount();
int numRemoveCallLogs = message.getData().getInt(
ConfigAppValues.NUM_REMOVE_CALL_LOGS);
//clear the arrayAdapter
arrayAdapter.clear();
//Show the toast message
Toast.makeText(
ConfigAppValues.getContext(),
numRemoveCallLogs + " " + ConfigAppValues.getContext().getString(
R.string.menu_calllog_remove_toast),
Toast.LENGTH_SHORT).show();
}
}
};
/**
* Handler for clear the listView and the array adapter once we have been
* add all contacts to the banned list
*/
public final Handler handlerRefresh = new Handler() {
public void handleMessage(Message message) {
ArrayList<String> callLogListString = null;
if (arrayAdapter != null) {
callLogListString = message.getData().getStringArrayList(
ConfigAppValues.REFRESH_CALL_LOG);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "callLoglistString: " + callLogListString);
//set the array adapter
if (callLogListString != null) {
//first delete the previous content list
arrayAdapter.clear();
//Second, add all call logs to the list
for (int i=0; i<callLogListString.size(); i++) {
String callLog = callLogListString.get(i);
Log.d(CLASS_NAME, "callLog:" ) ;
arrayAdapter.add(callLog);
}
}
//Show the toast message
if (QSToast.RELEASE) QSToast.r(
ConfigAppValues.getContext(),
ConfigAppValues.getContext().getString(
R.string.menu_calllog_refresh_toast),
Toast.LENGTH_SHORT);
}
/* If the arrayAdapter previously doesn't have any call log, this
* not been initialized, so initialize now.
*/
else {
callLogListString = message.getData().getStringArrayList(
ConfigAppValues.REFRESH_CALL_LOG);
Log.d(CLASS_NAME, "inicializando arrayAdapter. " +
"CallLogListString: " + callLogListString);
arrayAdapter = new ArrayAdapter<String>(
thisActivity,
R.layout.logstab,
R.id.logstab_textview_contact,
callLogListString);
setListAdapter(arrayAdapter);
}
}
};
}
| 120301csr038-description | src/es/cesar/quitesleep/activities/LogsTab.java | Java | gpl3 | 8,955 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.receivers;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* Class that implements the sms receiver action for listen the send action message
*
*/
public class SendActionSMSReceiver extends BroadcastReceiver{
private String CLASS_NAME = getClass().getName();
final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Successful transmission!!");
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext(),
"Successful transmission!!",
Toast.LENGTH_SHORT);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Nonspecific Failure!!");
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Intent extra: "
+ intent.getExtras().getInt("errorCode"));
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext(),
"Nonspecific Failure!!",
Toast.LENGTH_SHORT);
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Radio is turned Off!!");
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext(),
"Radio is turned Off!!",
Toast.LENGTH_SHORT);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "PDU Failure");
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext(),
"PDU Failure",
Toast.LENGTH_SHORT);
break;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/receivers/SendActionSMSReceiver.java | Java | gpl3 | 2,850 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.receivers;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.listeners.MyPhoneStateListener;
import es.cesar.quitesleep.notifications.QuiteSleepNotification;
import es.cesar.quitesleep.operations.IncomingCallOperations;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class PhoneStateReceiver extends BroadcastReceiver {
private final String CLASS_NAME = getClass().getName();
//Constants for all broadcastreceiver types used in the app
private final String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";
private final String PHONE_STATE = "android.intent.action.PHONE_STATE";
private final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
//Other constants used
private final String PDUS = "pdus";
@Override
public void onReceive (Context context, Intent intent) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "BroadcastReceive. Tipo: " + intent.getAction());
//------------- LISTEN FOR BOOT COMPLETED ------------------//
if (intent.getAction().equals(BOOT_COMPLETED)) {
listenBootCompleted(context);
}
//---------- LISTEN FOR INCOMING CALLS ------------------//
else if (intent.getAction().equals(PHONE_STATE)) {
listenIncomingCalls(context);
}
//----------- LISTEN FOR INCOMING SMS ----------------------//
else if (intent.getAction().equals(SMS_RECEIVED)) {
//listenIncomingSMS(context, intent);
}
}
/**
* Listen for BOOT_COMPLETED event and show the QuiteSleep status bar
* notification if the QuiteSleep service is previously configured to start
* Also initialize things like ConfigAppValues.setContext()
*
* @param context
*/
private void listenBootCompleted (Context context) {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "en Boot_Completed!!");
if (ConfigAppValues.getContext() == null)
ConfigAppValues.setContext(context);
if (ConfigAppValues.getQuiteSleepServiceState() != null) {
if (ConfigAppValues.getQuiteSleepServiceState()) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Show notification x ConfigAppValues: " + ConfigAppValues.getQuiteSleepServiceState());
QuiteSleepNotification.showNotification(context, true);
}
}
else {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
ConfigAppValues.setQuiteSleepServiceState(settings.isQuiteSleepServiceState());
if (settings.isQuiteSleepServiceState()) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Show notification x Settings: " + settings.isQuiteSleepServiceState());
QuiteSleepNotification.showNotification(context, true);
}
}
else {
ConfigAppValues.setQuiteSleepServiceState(false);
settings = new Settings(false);
clientDDBB.getInserts().insertSettings(settings);
clientDDBB.commit();
}
clientDDBB.close();
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Listen for incoming calls and use the listener for.
* @param context
*/
private synchronized void listenIncomingCalls (Context context) {
try {
MyPhoneStateListener phoneListener = new MyPhoneStateListener(context);
TelephonyManager telephony =
(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Listen the incoming SMS.
*
* @param context
* @param intent
*/
/*
private void listenIncomingSMS (Context context, Intent intent) {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SMS RECEIVED!!!!!");
SmsManager sms = SmsManager.getDefault();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get(PDUS);
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i=0; i<pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message:messages) {
String messageText = message.getMessageBody();
String phoneSender = message.getOriginatingAddress();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SMS Msg: " + messageText);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SMS From: " + phoneSender);
if (IncomingCallOperations.ringerMode() != AudioManager.RINGER_MODE_SILENT)
IncomingCallOperations.silentIncomingCall(phoneSender);
}
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
*/
}
| 120301csr038-description | src/es/cesar/quitesleep/receivers/PhoneStateReceiver.java | Java | gpl3 | 6,381 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* Class that implements the sms delivery action for listen the send action message
*
*/
public class DeliveredActionSMSReceiver extends BroadcastReceiver {
private String CLASS_NAME = getClass().getName();
final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "The user have been receive the SMS message!!");
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext(),
"The user have been receive the SMS message!!",
Toast.LENGTH_SHORT);;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/receivers/DeliveredActionSMSReceiver.java | Java | gpl3 | 1,818 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.notifications;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.activities.Main;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class QuiteSleepNotification {
private final static String CLASS_NAME = "es.cesar.quitesleep.notifications.QuiteSleepNotification";
//Notification
private static NotificationManager notificationManager = null;
final private static int notificationId = R.layout.quitesleep_notification;
/**
* Create the intent that is used when the user touch the QuiteSleep
* notification, and then go to the Main class application.
*
* @return the PendingIntent
* @see PendingIntent
*/
private static PendingIntent notificationIntent (Context context) {
// The PendingIntent to launch our activity if the user selects this
// notification. Note the use of FLAG_UPDATE_CURRENT so that if there
// is already an active matching pending intent, we will update its
// extras to be the ones passed in here.
PendingIntent contentIntent = PendingIntent.getActivity(
context,
0,
new Intent(
context,
Main.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT);
return contentIntent;
}
/**
* Show the QuiteSleep service running notification. If is the stop
* action, cancel the notification and hide.
*/
public static void showNotification (Context context, boolean showNotification) {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "notifiactionId: " + notificationId);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "showNotification: " + showNotification);
if (showNotification) {
//Get the notification manager service
if (notificationManager == null)
notificationManager =
(NotificationManager)context.
getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence title = context.getText(R.string.app_name);
CharSequence message;
message = ConfigAppValues.getContext().getText(
R.string.quitesleep_notification_start_message);
Notification notification = new Notification(
R.drawable.quitesleep_statusbar,
message,
System.currentTimeMillis());
notification.setLatestEventInfo(
context,
title,
message,
notificationIntent(context));
/* For the led flash custom
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
*/
notificationManager.notify(notificationId, notification);
}else if (notificationManager != null){
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Cancelando la notificacion");
notificationManager.cancel(notificationId);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/notifications/QuiteSleepNotification.java | Java | gpl3 | 4,229 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.callServices;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.os.Vibrator;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class NormalModeCallService extends Service {
private final String CLASS_NAME = getClass().getName();
//------------ Inherited method re-implement ----------------------//
@Override
public void onCreate () {
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
/*
if ((flags & START_FLAG_RETRY) == 0) {
//TODO If it's a restart, do something
}else {
//TODO Alternative background process
}
*/
putRingerModeNormal();
stopSelf();
return Service.START_NOT_STICKY;
}
//------------------------------------------------------------------------//
/**
* Put the mobile in normal mode (audio and vibrate), important: normal mode
* such the user defined previously (before to put the mobile in silence)
*
*/
private void putRingerModeNormal () {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Poniendo el movil en modo normal");
AudioManager audioManager =
(AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
ConfigAppValues.processIdleCall = false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Put the vibrator in mode On
*/
private void vibrateOn () {
try {
String vibratorService = Context.VIBRATOR_SERVICE;
Vibrator vibrator = (Vibrator)ConfigAppValues.getContext().
getSystemService(vibratorService);
vibrator.vibrate(1000);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/callServices/NormalModeCallService.java | Java | gpl3 | 3,037 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.callServices;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import es.cesar.quitesleep.operations.IncomingCallOperations;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class SilentModeCallService extends Service {
private final String CLASS_NAME = getClass().getName();
//------------ Inherited method re-implement ----------------------//
@Override
public void onCreate () {
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
/*
if ((flags & START_FLAG_RETRY) == 0) {
//TODO If it's a restart, do something
}else {
//TODO Alternative background process
}
*/
String incomingCallNumber = intent.getExtras().getString(ConfigAppValues.INCOMING_CALL_NUMBER);
IncomingCallOperations incomingCallOperations =
new IncomingCallOperations(incomingCallNumber);
//If i use threads
incomingCallOperations.start();
//I i don't use threads
//incomingCallOperations.silentIncomingCall();
//Stop the service by self way
stopSelf();
//before i used start_sticky
return Service.START_NOT_STICKY;
}
//------------------------------------------------------------------------//
}
| 120301csr038-description | src/es/cesar/quitesleep/callServices/SilentModeCallService.java | Java | gpl3 | 2,144 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Settings extends Id {
public final String CLASS_NAME = getClass().getName();
//Attribute Settings QuiteSleep service
private boolean quiteSleepServiceState = false;
//Attribute Mail Settings
private String user;
private String passwd;
private String subject;
private String body;
private boolean mailService = false;
//Attribute SMS Settings
private String smsText;
private boolean smsService = false;
//--------------- Getters & Setters --------------------------//
//@@@@@@@@@ QuiteSleep service @@@@@@@@@@@@@@@//
public boolean isQuiteSleepServiceState() {
return quiteSleepServiceState;
}
public void setQuiteSleepServiceState(boolean quiteSleepServiceState) {
this.quiteSleepServiceState = quiteSleepServiceState;
}
//@@@@@@@@@@ Mail Service @@@@@@@@@@@@@@@@@@//
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isMailService() {
return mailService;
}
public void setMailService(boolean mailService) {
this.mailService = mailService;
}
//@@@@@@@@@@@@ SMS service @@@@@@@@@@@@@@@@@@@@//
public boolean isSmsService() {
return smsService;
}
public void setSmsService(boolean smsService) {
this.smsService = smsService;
}
public String getSmsText() {
return smsText;
}
public void setSmsText(String smsText) {
this.smsText = smsText;
}
//------------------------------------------------------------------------//
/**
* Constructor without parameters
*/
public Settings () {
super();
}
/**
* Constructor with the basic paramters
* @param quiteSleepServiceState
*/
public Settings (boolean quiteSleepServiceState) {
super();
this.quiteSleepServiceState = quiteSleepServiceState;
}
@Override
public String toString () {
return "Settings: \tquiteSleepServiceState: " + quiteSleepServiceState;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Settings.java | Java | gpl3 | 3,097 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Phone extends Id {
private Contact contact;
private String contactPhone;
private boolean usedToSend;
//------- Getters & Setters --------------//
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public boolean isUsedToSend() {
return usedToSend;
}
public void setUsedToSend(boolean usedToSend) {
this.usedToSend = usedToSend;
}
//---------------------------------------------//
/**
* Constructor without parameters
*/
public Phone () {
super();
}
/**
* Constructor with basic paramters
*
* @param contact
* @param contactPhone
*/
public Phone (Contact contact, String contactPhone) {
super();
this.contact = contact;
this.contactPhone = contactPhone;
}
public Phone (Contact contact, String contactPhone, boolean usedToSend) {
super();
this.contact = contact;
this.contactPhone = contactPhone;
this.usedToSend = usedToSend;
}
@Override
public String toString () {
return "Contact: " + contact + "\nPhone: " + contactPhone + "\tUsedToSend: " + usedToSend;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Phone.java | Java | gpl3 | 2,134 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import java.text.DateFormat;
import java.util.Date;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Schedule extends Id {
//--- Time in Calendar format -----//
private Date startTime;
private Date endTime;
//---- Time formatted ----------------//
private String startFormatTime;
private String endFormatTime;
//---------- Week days ------------------//
private boolean monday = false;
private boolean tuesday = false;
private boolean wednesday = false;
private boolean thursday = false;
private boolean friday = false;
private boolean saturday = false;
private boolean sunday = false;
//--------------------------------------------------//
//------ Getters & Setters --------------//
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getStartFormatTime() {
return startFormatTime;
}
public void setStartFormatTime(String startFormatTime) {
this.startFormatTime = startFormatTime;
}
public String getEndFormatTime() {
return endFormatTime;
}
public void setEndFormatTime(String endFormatTime) {
this.endFormatTime = endFormatTime;
}
//---------------- Week days ---------------------------//
public boolean isMonday() {
return monday;
}
public void setMonday(boolean monday) {
this.monday = monday;
}
public boolean isTuesday() {
return tuesday;
}
public void setTuesday(boolean tuesday) {
this.tuesday = tuesday;
}
public boolean isWednesday() {
return wednesday;
}
public void setWednesday(boolean wednesday) {
this.wednesday = wednesday;
}
public boolean isThursday() {
return thursday;
}
public void setThursday(boolean thursday) {
this.thursday = thursday;
}
public boolean isFriday() {
return friday;
}
public void setFriday(boolean friday) {
this.friday = friday;
}
public boolean isSaturday() {
return saturday;
}
public void setSaturday(boolean saturday) {
this.saturday = saturday;
}
public boolean isSunday() {
return sunday;
}
public void setSunday(boolean sunday) {
this.sunday = sunday;
}
//------------- StartTimes ----------------------------------//
public void setAllStartTime (Date startTime, String startFormatTime) {
this.startTime = startTime;
this.startFormatTime = startFormatTime;
}
public void setAllEndTime (Date endTime, String endFormatTime) {
this.endTime = endTime;
this.endFormatTime = endFormatTime;
}
//--------------------------------------------------------------------//
/**
* Constructor without parameters
*/
public Schedule () {
super();
}
/**
* Constructor with the basic parameters
* @param startTime
* @param endTime
*/
public Schedule (Date startTime, Date endTime) {
super();
this.startTime = startTime;
this.endTime = endTime;
//Convert all calendar schedules to format strings schedules
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
this.startFormatTime = dateFormat.format(startTime);
this.endFormatTime = dateFormat.format(endTime);
}
/**
*
* @param startTime
* @param endTime
* @param startFormatTime
* @param endFormatTime
*/
public Schedule (
Date startTime,
Date endTime,
String startFormatTime,
String endFormatTime) {
super();
this.startTime = startTime;
this.endTime = endTime;
this.startFormatTime = startFormatTime;
this.endFormatTime = endFormatTime;
}
@Override
public String toString () {
return "StartTime: " + startFormatTime + "\tEndTime: " +
endFormatTime + "\nMonday: " + monday + "\tTuesday: " + tuesday +
"\tWednesday: " + wednesday + "\tThursday:" + thursday + "\tFriday: " +
friday + "\tSaturday: " + saturday + "\tSunday: " + sunday;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Schedule.java | Java | gpl3 | 4,728 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Banned extends Id {
private Contact contact;
private Schedule schedule;
//-------- Getters & Setters ---------------//
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public Schedule getSchedule() {
return schedule;
}
public void setSchedule(Schedule schedule) {
this.schedule = schedule;
}
//----------------------------------------------//
/**
* Constructor without parameters
*/
public Banned () {
super();
}
/**
* Contacts with all parameters
*
* @param contact
* @param schedule
*/
public Banned (Contact contact, Schedule schedule) {
super();
this.contact = contact;
this.schedule = schedule;
}
@Override
public String toString () {
return "Contact: " + contact + "\nSchedule: " + schedule;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Banned.java | Java | gpl3 | 1,703 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class CallLog extends Id {
private int numOrder;
private Contact contact;
private String phoneNumber;
private boolean sendSms = false;
private int numSendMail;
private String timeCall;
//------------------------------------------------------------------------//
public void setNumOrder(int numOrder) {
this.numOrder = numOrder;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public Contact getContact() {
return contact;
}
public int getNumOrder() {
return numOrder;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public boolean isSendSms() {
return sendSms;
}
public void setSendSms(boolean sendSms) {
this.sendSms = sendSms;
}
public int getNumSendMail() {
return numSendMail;
}
public void setNumSendMail(int numSendMail) {
this.numSendMail = numSendMail;
}
public String getTimeCall() {
return timeCall;
}
public void setTimeCall(String timeCall) {
this.timeCall = timeCall;
}
//------------------------------------------------------------------------//
/**
* Constructor without parameters
*/
public CallLog () {
super();
}
/**
* Constructor with the first paramter to get usually
*
* @param phone
*/
public CallLog (String phone) {
super();
this.phoneNumber = phone;
}
/**
* Constructor with all parameters
*
* @param contact
* @param phone
* @param numSendSms
* @param sendMail
* @param timeCall
* @param timeCallLong
*/
public CallLog (
Contact contact,
String phone,
boolean sendSms,
int numSendMail,
String timeCall) {
super();
this.contact = contact;
this.phoneNumber = phone;
this.sendSms = sendSms;
this.numSendMail = numSendMail;
this.timeCall = timeCall;
}
@Override
public String toString () {
return contact.getContactName() + "\t(" + phoneNumber + ")" + "\n" +
timeCall + "\t\tSms: " + (sendSms ? 1:0) + "\tEmail: " + numSendMail;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/CallLog.java | Java | gpl3 | 2,923 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import java.io.Serializable;
import es.cesar.quitesleep.utils.SHA1Utils;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Id implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
protected String id = "";
public String getId () {
return id;
}
public void setId (String id) {
this.id = id;
}
/**
* Constructor that create an unique Identificator Id for any object
* in the DDBB.
*/
public Id () {
//get the actual system time in nanoseconds
String time = String.valueOf(System.nanoTime());
//Create a sha1 string for the time previously got
this.id = SHA1Utils.generateSHA1toString(time);
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Id.java | Java | gpl3 | 1,575 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import java.util.List;
import android.util.Log;
import com.db4o.ObjectContainer;
import com.db4o.ext.StoredClass;
import com.db4o.query.Query;
import es.cesar.quitesleep.interfaces.IDDBB;
import es.cesar.quitesleep.staticValues.DDBBValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Selects implements IDDBB {
private final String CLASS_NAME = getClass().getName();
private ObjectContainer db;
/**
* Constructor
*
* @param db
*/
public Selects (ObjectContainer db) {
this.db = db;
}
/**
* Select all Contact objects from the DDBB and return it.
*
* @return All Contact objects from the DDBB
* @see List<Contact>
*/
public List<Contact> selectAllContacts () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Contact.class);
//Ordered by name (first A....last Z)
query.descend(DDBBValues.CONTACT_NAME).orderAscending();
List<Contact> contactList = query.execute();
return contactList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Select one Contact that is the same with the name passed
*
* @param contactName
* @return The contact match with the passed name
* @see Contact
*/
public Contact selectContactForName (String contactName) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Contact.class);
query.descend(DDBBValues.CONTACT_NAME).constrain(contactName);
List<Contact> contactList = query.execute();
if (contactList != null && contactList.size() == 1)
return contactList.get(0);
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString());
return null;
}
}
/**
* Select Contact object match with the passed phoneNumber, search
* along all contact's phone numbers.
*
* @param phoneContact
* @return Contact that match with the passed phone number
* any contact's phone number
* @see Contact
*/
public Contact selectContactForPhoneNumber (String phoneContact) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Phone.class);
query.descend(DDBBValues.CONTACT_PHONE).constrain(phoneContact);
List<Phone> contactList = query.execute();
if (contactList != null && contactList.size() == 1) {
Phone phone = contactList.get(0);
return phone.getContact();
}
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString());
return null;
}
}
/**
* Select Contact object match with the passed phoneNumber, search
* along all contact's phone numbers.
*
* @param phoneNumber
* @return Contact that match with the passed phone number
* any contact's phone number
* @see Contact
*/
public Contact selectContactForMail (String mailContact) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Mail.class);
query.descend(DDBBValues.CONTACT_MAIL).constrain(mailContact);
List<Mail> contactList = query.execute();
if (contactList != null && contactList.size() == 1) {
Mail mail = contactList.get(0);
return mail.getContact();
}
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString());
return null;
}
}
/**
* Get all phones of the selected contact
* @param contactName
* @return All phones about the selected contact
* @see List<Phone>
*/
public List<Phone> selectAllContactPhonesForName (String contactName) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Phone.class);
query.descend(DDBBValues.CONTACT).descend(
DDBBValues.CONTACT_NAME).constrain(contactName);
List<Phone> phonesList = query.execute();
return phonesList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Get all mails from the selected contact
* @param contactName
* @return List with all contact's mails
* @see List<Mail>
*/
public List<Mail> selectAllContactMailsForName (String contactName) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Mail.class);
query.descend(DDBBValues.CONTACT).descend(
DDBBValues.CONTACT_NAME).constrain(contactName);
List<Mail> mailsList = query.execute();
return mailsList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
*
* @param contact
* @return
*/
public List<Mail> selectAllContactMailForContact (Contact contact) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Mail.class);
query.descend(DDBBValues.CONTACT).constrain(contact);
List<Mail> mailList = query.execute();
return mailList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Get all banned contacts from the database
*
* @return List with all contacts or null if there any exception
* @see List<Banned>
*/
public List<Banned> selectAllBannedContacts () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Banned.class);
//Ordered by name (first A....last Z)
query.descend(DDBBValues.CONTACT).
descend(DDBBValues.CONTACT_NAME).orderAscending();
List<Banned> bannedList = query.execute();
return bannedList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Get all not banned contacts from the database
*
* @return
*/
public List<Contact> selectAllNotBannedContacts () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Contact.class);
query.descend(DDBBValues.BANNED).constrain(false);
query.descend(DDBBValues.CONTACT_NAME).orderAscending();
List<Contact> contactList = query.execute();
return contactList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Get the banned contact associate to the phone number passed to the
* function. Check if the contact name associate to the phone is in the
* ddbb and if the contact has the flag banned to true.
*
* @param phoneNumber
* @return contact if exists one contact banned who has
* the incoming number passed
* @see Contact
*/
public Contact selectBannedContactForPhoneNumber (String phoneNumber) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Phone.class);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "PhoneNumber: " + phoneNumber);
query.descend(DDBBValues.CONTACT_PHONE).constrain(phoneNumber).and(
query.descend(DDBBValues.CONTACT).descend(DDBBValues.BANNED).constrain(true));
List<Phone> phoneBannedList = query.execute();
if (phoneBannedList != null && phoneBannedList.size() == 1) {
Phone phone = phoneBannedList.get(0);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Phone: " + phone);
return phone.getContact();
}
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Get the banned object that match with the contactName passed.
*
* @param contactName
* @return The banned object matches with the contactName passed.
* @see Banned
*/
public Banned selectBannedContactForName (String contactName) {
try {
synchronized(SEMAPHORE) {
Query query = db.query();
query.constrain(Banned.class);
query.descend(DDBBValues.CONTACT).descend(
DDBBValues.CONTACT_NAME).constrain(contactName);
List<Banned> bannedList = query.execute();
if (bannedList != null && bannedList.size() == 1)
return bannedList.get(0);
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Get the (for the moment) the one Schedule object in the database.
* For now (04-17-2010) in this application version of quitesleep, must be
* only one Schedule object in the database, so all banned objects have to
* use the same Schedule object.
*
* @return The (for the moment) only Schedule object in the database
* @see Schedule
*/
public Schedule selectSchedule () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Schedule.class);
List<Schedule> scheduleList = query.execute();
if (scheduleList != null && scheduleList.size() == 1)
return scheduleList.get(0);
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Return the settings object only if is the one in the ddbb, else
* return null because have to be an error, only must be one Settings object
* in the ddbb.
*
* @return The settings object
* @see Settings
*/
public Settings selectSettings () {
try {
synchronized(SEMAPHORE) {
Query query = db.query();
query.constrain(Settings.class);
List<Settings> settingsList = query.execute();
if (settingsList != null && settingsList.size()==1)
return settingsList.get(0);
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
*
* @param phoneNumber
* @return
*/
public Phone selectPhoneForPhoneNumber (String phoneNumber) {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Phone.class);
query.descend(DDBBValues.CONTACT_PHONE).constrain(phoneNumber);
List<Phone> phoneList = query.execute();
if (phoneList != null)
return phoneList.get(0);
else
return null;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
*
* @return
*/
public List<CallLog> selectAllCallLog () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(CallLog.class);
//Order by the most new to the most older
query.descend(DDBBValues.NUM_ORDER).orderDescending();
List<CallLog> callLogList = query.execute();
return callLogList;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
*
* @return
*/
public int countCallLog () {
try {
synchronized (SEMAPHORE) {
StoredClass storedClass = db.ext().storedClass(CallLog.class);
return storedClass.getIDs().length;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Selects.java | Java | gpl3 | 13,102 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import android.util.Log;
import com.db4o.ObjectContainer;
import es.cesar.quitesleep.interfaces.IDDBB;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* @note This class is also used as update parent class, because the operations
* are the same in both cases
*
*/
public class Inserts implements IDDBB{
private final String CLASS_NAME = getClass().getName();
//The link with the database for can does operations
protected ObjectContainer db;
/**
* Constructor
*
* @param db
*/
public Inserts (ObjectContainer db) {
this.db = db;
}
/**
* Insert one Contact object in the DDBB.
*
* @param contact
* @return true or false depends the operation result
* @see boolean
*/
public boolean insertContact (Contact contact) {
try {
synchronized(SEMAPHORE) {
db.store(contact);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param phone
* @return boolean
*/
public boolean insertPhone (Phone phone) {
try {
synchronized (SEMAPHORE) {
db.store(phone);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param mail
* @return
*/
public boolean insertMail (Mail mail) {
try {
synchronized (SEMAPHORE) {
db.store(mail);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param banned
* @return
*/
public boolean insertBanned (Banned banned) {
try {
synchronized (SEMAPHORE) {
db.store(banned);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param schedule
* @return
*/
public boolean insertSchedule (Schedule schedule) {
try {
synchronized(SEMAPHORE) {
db.store(schedule);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param settings
* @return
*/
public boolean insertSettings (Settings settings) {
try {
synchronized (SEMAPHORE) {
db.store(settings);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param callLog
* @return
*/
public boolean insertCallLog (CallLog callLog) {
try {
synchronized (SEMAPHORE) {
db.store(callLog);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Inserts.java | Java | gpl3 | 4,102 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import java.util.List;
import android.util.Log;
import com.db4o.ObjectContainer;
import com.db4o.query.Query;
import es.cesar.quitesleep.interfaces.IDDBB;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Deletes implements IDDBB {
final String CLASS_NAME = getClass().getName();
private ObjectContainer db;
/**
* Constructor
*
* @param db
*/
public Deletes (ObjectContainer db) {
this.db = db;
}
/**
* Delete one Contact object in the DDBB that matches with the passed
*
* @param contact
* @return true or false with the operation result
* @see boolean
*/
public boolean deleteContact (Contact contact) {
try {
synchronized (SEMAPHORE) {
db.delete(contact);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Delete the banned object passed
*
* @param banned
* @return true or false of the banned object delete sucessfully
* @see boolean
*/
public boolean deleteBanned (Banned banned) {
try {
synchronized (SEMAPHORE) {
db.delete(banned);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @param settings
* @return
*/
public boolean deleteSettings (Settings settings) {
try {
synchronized(SEMAPHORE) {
db.delete(settings);
return true;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
*
* @return
*/
public int deleteAllContacts () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Contact.class);
List<Contact> contactList = query.execute();
int deletes = 0;
if (contactList != null)
for (int i=0; i<contactList.size(); i++){
Contact contact = contactList.get(i);
db.delete(contact);
deletes ++;
}
return deletes;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
*
* @return
*/
public int deleteAllPhones () {
try {
synchronized(SEMAPHORE) {
Query query = db.query();
query.constrain(Phone.class);
List<Phone> phoneList = query.execute();
int deletes = 0;
if (phoneList != null)
for (int i=0; i<phoneList.size(); i++) {
Phone phone = phoneList.get(i);
db.delete(phone);
deletes ++;
}
return deletes;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
*
* @return
*/
public int deleteAllMails () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(Mail.class);
List<Mail> mailList = query.execute();
int deletes = 0;
if (mailList != null)
for (int i=0; i<mailList.size(); i++) {
Mail mail = mailList.get(i);
db.delete(mail);
deletes++;
}
return deletes;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
*
* @return
*/
public int deleteAllBanned () {
try {
Query query = db.query();
query.constrain(Banned.class);
List<Banned> bannedList = query.execute();
int deletes = 0;
if (bannedList != null)
for (int i=0; i<bannedList.size(); i++) {
Banned banned = bannedList.get(i);
db.delete(banned);
deletes++;
}
return deletes;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
*
* @return
*/
public int deleteAllCallLog () {
try {
synchronized (SEMAPHORE) {
Query query = db.query();
query.constrain(CallLog.class);
List<CallLog> callLogList = query.execute();
int deletes = 0;
if (callLogList != null)
for (int i=0; i<callLogList.size(); i++) {
CallLog callLog = callLogList.get(i);
db.delete(callLog);
deletes ++;
}
return deletes;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Deletes.java | Java | gpl3 | 5,697 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Contact extends Id {
private String contactId;
private String contactName;
private boolean banned = false;
//------------- Getters & Setters ------------------------------//
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public boolean isBanned() {
return banned;
}
public void setBanned(boolean banned) {
this.banned = banned;
}
//------------------------------------------------------------------------//
/**
* Constructor without parameters
*/
public Contact () {
super();
}
/**
* Complete constructor with two essential properties, contact id and contact name
*
* @param contactId
* @param contactName
*/
public Contact (String contactId, String contactName) {
super();
this.contactId = contactId;
this.contactName = contactName;
}
/**
* Function return toString
*/
public String toString () {
return "ContactId: " + contactId + "\tContactName: " + contactName +
"\tBanned: " + banned;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Contact.java | Java | gpl3 | 2,085 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import android.util.Log;
import com.db4o.ObjectContainer;
import com.db4o.ObjectServer;
import es.cesar.quitesleep.interfaces.IDDBB;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ClientDDBB implements IDDBB{
final String CLASS_NAME = getClass().getName();
protected ObjectContainer clientDDBB;
protected Selects selects;
protected Inserts inserts;
protected Updates updates;
protected Deletes deletes;
/**
* This function return the ObjectContainer ised like as clientDDBB for
* the application.
*
* @return The ObjectContainer used like as clientDDBB
* @see ObjectContainer
*/
public ObjectContainer getObjectContainer () {
return clientDDBB;
}
/**
* Otro cliente para conectarse al servidor de forma embebida, pero
* a diferencia del anterior, usamos una clase estática que lo lanza.
*/
public ClientDDBB () {
try
{
synchronized (SEMAPHORE) {
clientDDBB = ServerDDBB.getServer().openClient();
selects = new Selects(clientDDBB);
inserts = new Inserts(clientDDBB);
updates = new Updates(clientDDBB);
deletes = new Deletes(clientDDBB);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
*
* @param cliente
*/
public ClientDDBB (ObjectContainer clientDDBB) {
try {
synchronized (SEMAPHORE) {
selects = new Selects(clientDDBB);
inserts = new Inserts(clientDDBB);
updates = new Updates(clientDDBB);
deletes = new Deletes(clientDDBB);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Constructor al que le pasamos un servidor para que lo utilice en vez
* de utilizar el que pone en memoria la clase ServerBBDDEmbebido.
*
* Este constructor esta creado para ser utilizado en la Migración de BBDD.
*
* @param server
*/
public ClientDDBB (ObjectServer serverDDBB) {
try
{
synchronized (SEMAPHORE) {
clientDDBB = serverDDBB.openClient();
selects = new Selects(clientDDBB);
inserts = new Inserts(clientDDBB);
updates = new Updates(clientDDBB);
deletes = new Deletes(clientDDBB);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Function that close the ClientDDBB if it's opened previously
*/
public void close () {
if (!isClosed())
// close the ObjectContainer
clientDDBB.close();
}
/**
* Function that said if the client is closed
* @return true or false if the clientDDBB is closed or not
* @see boolean
*/
public boolean isClosed () {
if (clientDDBB != null)
return clientDDBB.ext().isClosed();
else
return true;
}
public void commit () {
clientDDBB.commit();
}
public ObjectContainer getClientDDBB() {
return clientDDBB;
}
public void setClientDDBB(ObjectContainer clientDDBB) {
this.clientDDBB = clientDDBB;
}
public Selects getSelects() {
return selects;
}
public void setSelects(Selects selects) {
this.selects = selects;
}
public Inserts getInserts() {
return inserts;
}
public void setInserts(Inserts inserts) {
this.inserts = inserts;
}
public Updates getUpdates() {
return updates;
}
public void setUpdates(Updates updates) {
this.updates = updates;
}
public Deletes getDeletes() {
return deletes;
}
public void setDeletes(Deletes deletes) {
this.deletes = deletes;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/ClientDDBB.java | Java | gpl3 | 4,832 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Mail extends Id {
private Contact contact;
private String contactMail;
private boolean usedToSend;
//------ Getters & Setters ---------------//
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public String getContactMail() {
return contactMail;
}
public void setContactMail(String contactMail) {
this.contactMail = contactMail;
}
public boolean isUsedToSend() {
return usedToSend;
}
public void setUsedToSend(boolean usedToSend) {
this.usedToSend = usedToSend;
}
//------------------------------------------------//
/**
* Constructor without parameters
*/
public Mail () {
super();
}
/**
* Constructor with basic parameters
* @param contact
* @param contactMail
*/
public Mail (Contact contact, String contactMail) {
super();
this.contact = contact;
this.contactMail = contactMail;
}
/**
* Constructor with all parameters
* @param contact
* @param contactMail
* @param usedToSend
*/
public Mail (Contact contact, String contactMail, boolean usedToSend) {
super();
this.contact = contact;
this.contactMail = contactMail;
this.usedToSend = usedToSend;
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Mail.java | Java | gpl3 | 2,082 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import android.util.Log;
import com.db4o.ObjectServer;
import com.db4o.cs.Db4oClientServer;
import com.db4o.cs.config.ServerConfiguration;
import es.cesar.quitesleep.interfaces.IDDBB;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ServerDDBB implements IDDBB {
private final static String CLASS_NAME = "es.cesar.quitesleep.ddbb.ServerDDBB";
/**
* This object is for get only one Singleton object and create ONLY inside
* of this class mode.
*/
private static ServerDDBB SINGLETON = null;
/**
* This object is the server DDBB file properly said
*/
private static ObjectServer server = null;
/**
* Constructor for the ServerDDBB
*/
private ServerDDBB () {
try
{
if (QSLog.DEBUG_I)QSLog.i(CLASS_NAME, "Before to open the DDBB");
ServerConfiguration configuration =
Db4oClientServer.newServerConfiguration();
configuration.common().allowVersionUpdates(true);
configuration.common().activationDepth(DEEP);
server = Db4oClientServer.openServer(
configuration, getDDBBFile(DDBB_FILE), 0);
if (server == null)
if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Server Null!!!!");
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Create the server instance if the server doesn't create before
*/
private synchronized static void createInstance () {
if (server == null)
SINGLETON = new ServerDDBB();
}
/**
* Get the server DDBB instance, if the singleton object doesn't create
* before, we create for use it.
*
* @return The server object
* @see ObjectsServer
*/
public static ObjectServer getServer() {
if (SINGLETON == null)
createInstance();
return server;
}
/**
* Function for logs only
*/
public static void checkServer () {
if (SINGLETON == null)
if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Singleton Nul!!!");
else
if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Singleton Not Null!!!");
if (server == null)
if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Server Null!!!");
else
if (QSLog.DEBUG_W)QSLog.w(CLASS_NAME, "Server Not Null!!!");
}
/**
* Destructor class function
*/
protected void finalize () {
if (server != null) {
server.close();
server = null;
}
}
/**
* Function that defrag de Server DDBB File for get free space
*/
public static void defrag () {
try
{
if (server != null)
com.db4o.defragment.Defragment.defrag(
getDDBBFile(DDBB_FILE),
getDDBBFile(DDBB_FILE + ".old"));
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Function that returns the ddbb file string from the app
*
* @param ddbb_file
* @return The ddbb filename
* @see String
*/
private static String getDDBBFile(String ddbb_file) {
//ConfigAppValues.getContext();
if (ConfigAppValues.getContext() != null)
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "getContext != null");
else
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "getContext == null");
return ConfigAppValues.getContext().getDir(
DDBB_DIR,
ConfigAppValues.getContext().MODE_PRIVATE)
+ "/" + ddbb_file;
//NOTA: Para escribir en la sdcard, no se utiliza getContext().getDir()
//Se utiliza FileOutputStream y las funciones normales de java.io
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/ServerDDBB.java | Java | gpl3 | 4,742 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.ddbb;
import com.db4o.ObjectContainer;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class Updates extends Inserts {
private final String CLASS_NAME = getClass().getName();
public Updates (ObjectContainer db) {
super(db);
}
}
| 120301csr038-description | src/es/cesar/quitesleep/ddbb/Updates.java | Java | gpl3 | 1,040 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.listeners;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import es.cesar.quitesleep.callServices.NormalModeCallService;
import es.cesar.quitesleep.callServices.SilentModeCallService;
import es.cesar.quitesleep.operations.CheckSettingsOperations;
import es.cesar.quitesleep.operations.IncomingCallOperations;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class MyPhoneStateListener extends PhoneStateListener {
private final String CLASS_NAME = getClass().getName();
/**
* Constructor with the context parameter for use if the application
* not run and is the BOOT_COMPLETED BroadcastReceiver that is launch
* this.
* @param context
*/
public MyPhoneStateListener (Context context) {
super();
if (ConfigAppValues.getContext() == null)
ConfigAppValues.setContext(context);
}
/**
* Function that receive the state id for the phone state type
* (idle, offhook and ringing), and the incoming number that is doing
* the call.
*/
public void onCallStateChanged (int state, String incomingNumber) {
try {
switch (state) {
//------------- CALL_STATE_IDLE ----------------------//
case TelephonyManager.CALL_STATE_IDLE:
processCallStateIdle();
break;
//----------------- CALL_STATE_OFFHOOK --------------//
case TelephonyManager.CALL_STATE_OFFHOOK:
processCallStateOffhook();
break;
//----------------- CALL_STATE_RINGING --------------//
case TelephonyManager.CALL_STATE_RINGING:
processCallStateRinging(incomingNumber);
break;
default:
break;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Proces the CALL_STATE_IDLE signal from PhoneReceiver
*/
private void processCallStateIdle () {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "IDLE");
ConfigAppValues.processRingCall = false;
if (ringerMode() == AudioManager.RINGER_MODE_SILENT &&
CheckSettingsOperations.checkQuiteSleepServiceState() &&
!ConfigAppValues.processIdleCall) {
/* Put one pause of 1 second for wait before put the
* ringer mode to normal again
*/
//Thread.sleep(1000);
ConfigAppValues.processIdleCall = true;
//-- If u choose use Android Service for process incoming call use this --//
ConfigAppValues.getContext().startService(
new Intent(
ConfigAppValues.getContext(),
NormalModeCallService.class));
//------------------------------------------------------------//
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext().getApplicationContext(),
"IDLE!!!!!!!!",
Toast.LENGTH_SHORT);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(
CLASS_NAME,
ExceptionUtils.exceptionTraceToString(e.toString(), e.getStackTrace()));
}
}
/**
* Proces the CALL_STATE_OFFHOOK signal from PhoneReceiver
*/
private void processCallStateOffhook () {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "OFFHOOK");
ConfigAppValues.processRingCall = false;
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext().getApplicationContext(),
"OFFHOOK!!!!!!!!",
Toast.LENGTH_SHORT);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Proces the CALL_STATE_RINGING signal from PhoneReceiver
*/
private void processCallStateRinging (String incomingNumber) {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "RINGING");
/* Put the device in silent mode if the inc.oming number is
* from contact banned and in schedule interval
*/
if (ringerMode() != AudioManager.RINGER_MODE_SILENT &&
CheckSettingsOperations.checkQuiteSleepServiceState() &&
!ConfigAppValues.processRingCall) {
ConfigAppValues.processRingCall = true;
//-- If u choose use Android Service for send SMS use this --//
ConfigAppValues.getContext().startService(
new Intent(
ConfigAppValues.getContext(),
SilentModeCallService.class).putExtra(
ConfigAppValues.INCOMING_CALL_NUMBER,
incomingNumber));
//------------------------------------------------------------//
if (QSToast.DEBUG) QSToast.d(
ConfigAppValues.getContext().getApplicationContext(),
"RINGING!!!!!!!!",
Toast.LENGTH_SHORT);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Get what ringer mode is at the moment.
*
* @return return RINGER_MODE_SILENT(0), RINGER_MODE_NORMAL(2), RINGER_MODE_VIBRATE(1)
* @see int
* @throws Exception
*/
private int ringerMode () throws Exception {
try {
AudioManager audioManager =
(AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE);
//Only for traces
switch (audioManager.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Ringer_Mode_Silent");
break;
case AudioManager.RINGER_MODE_NORMAL:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Ringer_Mode_Normal");
break;
case AudioManager.RINGER_MODE_VIBRATE:
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Ringer_Mode_Vibrate");
break;
default:
break;
}
return audioManager.getRingerMode();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Exception();
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/listeners/MyPhoneStateListener.java | Java | gpl3 | 7,212 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import java.util.StringTokenizer;
import android.util.Log;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class TokenizerUtils {
private final static String CLASS_NAME = "es.cesar.quitesleep.utils.TokenizerUtils";
public static void main (String[] args) {
final String PHONE = "6-76-10--4-15-9";
String newPhone = tokenizerPhoneNumber(PHONE, null);
//Log.e("tokens", "OldPhone: " + PHONE + "NewPhone: " + newPhone);
System.out.println("OldPhone: " + PHONE + " NewPhone: " + newPhone);
}
/**
* Tokenize the passed phoneNumber erasing the string separator and return
* the phone number whitout these.
*
* @param phoneNumber
* @param delim
* @return the new String without the delim chars
* @see String
*/
public static String tokenizerPhoneNumber (
String phoneNumber,
String delim) {
final String DEFAULT_DELIM = "-";
try {
//If not delim has been specified, put the default delim
if (delim == null)
delim = DEFAULT_DELIM;
//If phone number is different from null we parse it.
if (phoneNumber != null) {
/* Separate the phone number into tokens which the delim string
* is the "separate word"
*/
StringTokenizer tokenizer = new StringTokenizer(phoneNumber, delim);
String phoneNumberWithoutDelim = "";
while (tokenizer.hasMoreTokens())
phoneNumberWithoutDelim = phoneNumberWithoutDelim + tokenizer.nextToken();
return phoneNumberWithoutDelim;
}
return null;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Add an increase of hours to the time passed, if the delim parameter is null
* we use the default parameter ":"
*
* @param time
* @param increase
* @param delim
* @return the new time with the increase done
* @see String
*/
public static String addIncreaseDate (String time, int increase, String delim) {
try {
final String DEFAULT_DELIM = ":";
if (delim == null)
delim = DEFAULT_DELIM;
if (time != null) {
/* Separate the time into tokens which the delim string
* is the "separate word"
*/
StringTokenizer tokenizer = new StringTokenizer(time, delim);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "count tokens: " + tokenizer.countTokens());
if (tokenizer.countTokens() == 2) {
String hourString = tokenizer.nextToken();
String minStrig = tokenizer.nextToken();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "hourString: " + hourString + "\tminString: " + minStrig);
int hour = Integer.valueOf(hourString);
String completeNewTime = String.valueOf(hour + increase) + ":" + minStrig;
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "new time: " + completeNewTime);
return completeNewTime;
}
} else {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "time == null");
return null;
}
return null;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/utils/TokenizerUtils.java | Java | gpl3 | 4,193 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import android.content.Context;
import android.widget.Toast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* Class for show or not Toast notificactions
* Two levels:
* - Debug mode (for develop process)
* - Release mode (for release app)
*
*/
public class QSToast {
private final static String CLASS_NAME = "es.cesar.quitelseep.utils.QSToast";
public static final boolean DEBUG = true;
public static final boolean RELEASE = true;
/**
* Toast for debug (d) mode
*
* @param context
* @param message
* @param length
*/
public static void d(Context context, String message, int length) {
Toast.makeText(
context,
message,
length).show();
}
/**
* Toast for release (r) mode
*
* @param context
* @param message
* @param length
*/
public static void r(Context context, String message, int length) {
Toast.makeText(
context,
message,
length).show();
}
}
| 120301csr038-description | src/es/cesar/quitesleep/utils/QSToast.java | Java | gpl3 | 1,725 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataSource;
/**
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* @codefrom http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-ap
*
*/
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
} | 120301csr038-description | src/es/cesar/quitesleep/utils/ByteArrayDataSource.java | Java | gpl3 | 2,122 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import android.util.Log;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class QSLog {
public static final boolean DEBUG_V = true;
public static final boolean DEBUG_D = true;
public static final boolean DEBUG_I = true;
public static final boolean DEBUG_W = true;
public static final boolean DEBUG_E = true;
public static void v(String className, String msg) {
Log.v(className, msg);
}
public static void d(String className, String msg) {
Log.d(className, msg);
}
public static void i(String className, String msg) {
Log.i(className, msg);
}
public static void w(String className, String msg) {
Log.w(className, msg);
}
public static void e(String className, String msg) {
Log.e(className, msg);
}
}
| 120301csr038-description | src/es/cesar/quitesleep/utils/QSLog.java | Java | gpl3 | 1,583 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import android.util.Log;
/**
*
* @author Cesar Valiente Gordo y Eduardo Coca Sola
* @mail cesar.valiente@gmail.com
*
*/
public class SHA1Utils {
final static String CLASS_NAME = "SHA1Util";
// Genera SHA-1 de un char[]
public static byte[] generateSHA1 (char chars[]) {
return generateSHA1(new String(chars));
}
// Genera SHA-1 de un String
public static byte[] generateSHA1 (String str) {
return generateSHA1(str.getBytes());
}
// Genera SHA-1 de un InputStream
public static byte[] generateSHA1 (InputStream is) {
try {
return generateSHA1(InputStreamUtils.InputStreamTOByte(is));
} catch (Exception e) {
return null;
}
}
public static String generateSHA1toString (String str) {
try
{
byte[] datos = generateSHA1(str.getBytes());
return byteArrayToHexString(datos);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME,
ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
public static String generateSHA1toString (InputStream is) {
try {
return InputStreamUtils.byteToString(generateSHA1(InputStreamUtils.InputStreamTOByte(is)));
} catch (Exception e) {
return null;
}
}
// Genera SHA-1 de un File
public static byte[] generateSHA1 (File file) {
try {
return generateSHA1(new FileInputStream (file));
} catch (Exception e) {
return null;
}
}
// Genera SHA-1 de un byte[]
public static byte[] generateSHA1 (byte[] bytes) {
byte[] encryted = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(bytes);
encryted = digest.digest();
} catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
return encryted;
}
// Codifica un byte[] en hexadecimal
public static String byteArrayToHexString(byte[] b){
if (b==null) return null;
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++){
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
// Codifica String hexadecimal en byte[]
public static byte[] hexStringToByteArray(String s) {
if (s==null) return null;
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++){
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte)v;
}
return b;
}
// Compara dos byte[] elemento a elemento
public static boolean compareByteArrays (byte[] b1, byte[] b2) {
return b1!=null && b2!=null && Arrays.equals(b1, b2) ;
}
// Compara dos String
public static boolean compareHexString (String s1, String s2) {
return s1!=null && s2!=null && s1.equalsIgnoreCase(s2);
}
} | 120301csr038-description | src/es/cesar/quitesleep/utils/SHA1Utils.java | Java | gpl3 | 3,937 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author Cesar Valiente Gordo y Eduardo Coca Sola
* @mail cesar.valiente@gmail.com
*
*/
public class InputStreamUtils {
final static int BUFFER_SIZE = 4096; // Tamaño de los bloques a leer/escribir al comprimir en ZIP
/**************************************************************************
*
* @param in InputStream
* @return String
* @throws Exception
*
* Funci�n que pasa de InputStream a String
**************************************************************************/
public static String InputStreamTOString (InputStream in) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1; // Bytes leidos por bloque
while ( (count = in.read(data,0,BUFFER_SIZE)) != -1 )
outStream.write(data,0,count);
data=null;
return new String (outStream.toByteArray(),"ISO-8859-1");
}
/**
*
* @param in
* @param encoding
* @return
* @throws Exception
*/
public static String InputStreamTOString (InputStream in, String encoding) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1; // Bytes leidos por bloque
while ( (count = in.read(data,0,BUFFER_SIZE)) != -1 )
outStream.write(data,0,count);
data=null;
return new String (outStream.toByteArray(),encoding);
}
/**************************************************************************
*
* @param in String
* @return InputStream
* @throws Exception
*
* Funci�n que pasa de String a InputStream
**************************************************************************/
public static InputStream StringTOInputStream (String in) throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("ISO-8859-1"));
return is;
}
/**************************************************************************
*
* @param in InputStream
* @return byte[]
* @throws IOException
*
* Funci�n que pasa convierte un InputStream a un array de bytes (byte[])
**************************************************************************/
public static byte[] InputStreamTOByte (InputStream in) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1; // Bytes leidos por bloque
while ( (count = in.read(data,0,BUFFER_SIZE)) != -1 )
outStream.write(data,0,count);
data=null;
return outStream.toByteArray();
}
//TODO revisar este metodo
public static InputStream byteTOInputStream (byte[] in) throws Exception {
ByteArrayInputStream resultado = new ByteArrayInputStream(in);
return resultado;
}
public static String byteToString (byte[] in) throws Exception {
InputStream ins = byteTOInputStream(in);
return InputStreamTOString(ins);
}
} | 120301csr038-description | src/es/cesar/quitesleep/utils/InputStreamUtils.java | Java | gpl3 | 4,077 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.utils;
import android.util.Log;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ExceptionUtils {
public static final String CLASS_NAME = "es.cesar.quitesleep.utils.ExceptionUtils";
/**
*
* @param stackTrace
* @return
*/
public static String exceptionTraceToString (
String exception,
StackTraceElement[] stackTrace) {
try {
String completeTrace = "";
for (int i=0; i<stackTrace.length; i++) {
if (completeTrace.equals(""))
completeTrace = exception + "\n\t" + stackTrace[i].toString() + "\n";
else
completeTrace = completeTrace + "\t" + stackTrace[i] + "\n";
}
return completeTrace;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, e.toString());
return "";
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/utils/ExceptionUtils.java | Java | gpl3 | 1,572 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.mailmessages;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.util.Log;
import es.cesar.quitesleep.ddbb.CallLog;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Contact;
import es.cesar.quitesleep.ddbb.Mail;
import es.cesar.quitesleep.ddbb.Phone;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.utils.ByteArrayDataSource;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* @mostcodefrom http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-ap
*
*/
public class SendMail extends Authenticator implements Runnable {
private final String CLASS_NAME = getClass().getName();
private String user;
private String passwd;
private String subject;
private String body;
private String incomingCallNumber;
private List<String> receiverMailList;
private CallLog callLog;
//--------------- Getters & Setters --------------------------//
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getIncomingCallNumber() {
return incomingCallNumber;
}
public void setIncomingCallNumber(String incomingCallNumber) {
this.incomingCallNumber = incomingCallNumber;
}
public List<String> getReceiverMailList() {
return receiverMailList;
}
public void setReceiverMailList (List<String> receiverMailList) {
this.receiverMailList = receiverMailList;
}
public CallLog getCallLog() {
return callLog;
}
public void setCallLog(CallLog callLog) {
this.callLog = callLog;
}
//------------------------------------------------------------------------//
static {
Security.addProvider(new JSSEProvider());
}
/**
* Constructor with all parameters
*
* @param user
* @param passwd
* @param subject
* @param body
* @param incomingCallNumber
*/
public SendMail (
String user,
String passwd,
String subject,
String body,
String incomingCallNumber) {
this.user = user;
this.passwd = passwd;
this.subject = subject;
this.body = body;
this.incomingCallNumber = incomingCallNumber;
getReceiverMailList(incomingCallNumber);
}
/**
* Constructor empty
*/
public SendMail (String incomingCallNumber, CallLog callLog) {
this.incomingCallNumber = incomingCallNumber;
this.callLog = callLog;
getAllData();
getReceiverMailList(incomingCallNumber);
}
/**
* Get all mail data form the ddbb. Assume that previously have been check
* if mail service is activated.
*/
private void getAllData () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
user = settings.getUser();
passwd = settings.getPasswd();
subject = settings.getSubject();
body = settings.getBody();
}
clientDDBB.close();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Function that obtains the mail asociated to the phone number passed
*
* @param incomingCallNumber
*/
private void getReceiverMailList (String incomingCallNumber){
try {
ClientDDBB clientDDBB = new ClientDDBB();
Phone phone = clientDDBB.getSelects().selectPhoneForPhoneNumber(incomingCallNumber);
if (phone != null) {
Contact contact = phone.getContact();
List<Mail> mailList =
clientDDBB.getSelects().selectAllContactMailForContact(contact);
clientDDBB.close();
//We don't check if is a banned contact because previously must be done
receiverMailList = new ArrayList<String>();
boolean findAtLeastOne = false;
for (int i=0; i<mailList.size(); i++) {
Mail mail = mailList.get(i);
if (mail.isUsedToSend()) {
receiverMailList.add(mail.getContactMail());
findAtLeastOne = true;
}
}
if (!findAtLeastOne)
receiverMailList = null;
//--- Used when only one of all mail list was used for send email ----/
/*
int i=0;
boolean find = false;
Mail mail = null;
while (i<mailList.size() && !find) {
mail = mailList.get(i);
if (mail.isUsedToSend())
find = true;
i++;
}
if (find)
receiverMailList = mail.getContactMail();
else
receiverMailList = null;
*/
//------------------------------------------------------------//
}
/* The else case mustn't be never, because previously we have check
* that this receiver is in the banned list
*/
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
receiverMailList = null;
}
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, passwd);
}
@Override
public void run () {
int numShipments = sendMail();
saveNumShipments(numShipments);
}
/**
* Send an email to the receiver associated to the phone number who has been
* do the call.
*
* @return true or false depends of the result action
* @see boolean
*/
public synchronized int sendMail () {
try {
if (receiverMailList != null) {
if (MailConfig.getProperties() == null)
MailConfig.initProperties();
int numShipments = 0;
Properties properties = MailConfig.getProperties();
Session session = Session.getDefaultInstance(properties, this);
MimeMessage message = new MimeMessage(session);
DataHandler dataHandler = new DataHandler(
new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(user));
message.setSubject(subject);
message.setDataHandler(dataHandler);
for (int i=0; i<receiverMailList.size(); i++) {
String mailToSend = receiverMailList.get(i);
message.setRecipient(
Message.RecipientType.TO, new InternetAddress(mailToSend));
Transport.send(message);
numShipments ++;
}
return numShipments;
}
return 0;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return -1;
}
}
/**
* Save the CallLog object if the numShipments is greater than 0.
* @param numShipments
*/
private void saveNumShipments (int numShipments) {
try {
if (numShipments > 0) {
/*
ClientDDBB clientDDBB = new ClientDDBB();
clientDDBB.getUpdates().insertCallLog(callLog);
clientDDBB.commit();
clientDDBB.close();
*/
//Use when join all threads finish
callLog.setNumSendMail(numShipments);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/mailmessages/SendMail.java | Java | gpl3 | 8,602 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at *
* http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
package es.cesar.quitesleep.mailmessages;
import java.security.AccessController;
import java.security.Provider;
/**
* @author Alexander Y. Kleymenov
* @version $Revision$
*
* @codefrom http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-ap
*/
public final class JSSEProvider extends Provider {
/**
* Constructor
*/
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
| 120301csr038-description | src/es/cesar/quitesleep/mailmessages/JSSEProvider.java | Java | gpl3 | 1,978 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.mailmessages;
import java.util.Properties;
import android.util.Log;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class MailConfig {
private static String CLASS_NAME = "es.cesar.quitesleep.sendmessages.MailConfig";
private static Properties properties = null;
//------------- Getters & Setters ------------------------------//
public static Properties getProperties() {
return properties;
}
public static void setProperties(Properties properties) {
MailConfig.properties = properties;
}
//------------------------------------------------------------------------//
public static void initProperties () {
try {
properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.host", "smtp.gmail.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smpt.port", "465");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.smtp.quitwait", "false");
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/mailmessages/MailConfig.java | Java | gpl3 | 2,219 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.staticValues;
public class DDBBValues {
//------ Contact -------------------------------//
public static final String CONTACT_ID = "contactId";
public static final String CONTACT_NAME = "contactName";
public static final String BANNED = "banned";
//-------- Phone -----------------------------------//
public static final String CONTACT = "contact";
public static final String CONTACT_PHONE = "contactPhone";
public static final String USED_TO_SEND = "usedToSend";
//-------- Mail --------------------------------//
public static final String CONTACT_MAIL = "contactMail";
//Also used here: CONTACT and USED_TO_SEND
//-------- Schedule --------------------------------//
public static final String START_SCHEDULE = "startSchedule";
public static final String END_SCHEDULE = "endSchedule";
public static final String START_FORMAT_SCHEDULE = "startFormatSchedule";
public static final String END_FORMAT_SCHEDULE = "endFormatSchedule";
//-------- Banned --------------------------------------//
public static final String SCHEDULE = "schedule";
//Also used here: CONTACT
//-------- CallLog ---------------------------------//
public static final String PHONE = "phone";
public static final String NUM_ORDER = "numOrder";
public static final String NUM_SEND_SMS = "numSendSms";
public static final String NUM_SEND_MAIL = "numSendMail";
}
| 120301csr038-description | src/es/cesar/quitesleep/staticValues/DDBBValues.java | Java | gpl3 | 2,138 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.staticValues;
import java.util.concurrent.Semaphore;
import android.content.Context;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ConfigAppValues {
//------------- FINAL VALUES (Constants) --------------------------//
public static final String CONTACT_NAME = "CONTACT_NAME";
//--------------- req Codes for return activities ------------------//
public static final int REQCODE_ADD_BANNED = 1;
public static final int REQCODE_DELETE_BANNED = 2;
public static final int REQCODE_SMS_SETTINGS = 3;
public static final int REQCODE_MAIL_SETTINGS = 4;
public static final int REQCODE_SYNC_CONTACTS = 5;
public static final int REQCODE_CONTACT_DETAILS = 6;
public static final int REQCODE_EDIT_CONTACT = 7;
public static final int reqTest = 100;
//------------------------------------------------------------------------//
//------------ Codes for dialog actions ------------------------------//
public static final int WARNING_SYNC_CONTACTS = 1;
public static final int WARNING_ADD_ALL_CONTACTS = 2;
public static final int WARNING_REMOVE_ALL_CONTACTS = 3;
public static final int WARNING_SMS_ACTION = 4;
public static final int WARNING_MAIL_ACTION = 5;
public static final int WARNING_REMOVE_ALL_CALL_LOGS = 6;
public static final int WARNING_REFRESH_CALL_LOG = 7;
//------------------------------------------------------------------------//
//---------- Codes for informaton through intents ----------//
public static final String NUM_REMOVE_CONTACTS = "NUM_REMOVE_CONTACTS";
public static final String NUM_REMOVE_CALL_LOGS = "NUM_REMOVE_CALL_LOGS";
public static final String REFRESH_CALL_LOG = "REFRESH_CALL_LOG";
//------------ Other response codes ------------------------------//
public static final int LAUNCH_ABOUT = 1;
public static final int LAUNCH_HELP = 2;
//Min Api level used in this app
private static int minApiLevel = 1;
//General context used in this app
private static Context context = null;
/* Used for check without need to use the ddbb if the service
* QuiteSleep must be running or not.
*/
private static Boolean quiteSleepServiceState = null;
private static Boolean mailServiceState = null;
private static Boolean smsServiceState = null;
//Constant string for get the incomingCallNumber
public static String INCOMING_CALL_NUMBER = "INCOMING_CALL_NUMBER";
//For use as semaphores in a producer-consumer way
public static boolean processRingCall = false;
public static boolean processIdleCall = false;
//---------- Getters & Setters -----------------------------------//
public static int getMinApiLevel() {
return minApiLevel;
}
public static void setMinApiLevel(int minApiLevel) {
ConfigAppValues.minApiLevel = minApiLevel;
}
public static Context getContext () {
return context;
}
public static void setContext (Context context) {
ConfigAppValues.context = context;
}
public static Boolean getQuiteSleepServiceState() {
return quiteSleepServiceState;
}
public static void setQuiteSleepServiceState(Boolean quiteSleepServiceState) {
ConfigAppValues.quiteSleepServiceState = quiteSleepServiceState;
}
public static Boolean getMailServiceState() {
return mailServiceState;
}
public static void setMailServiceState(Boolean mailServiceState) {
ConfigAppValues.mailServiceState = mailServiceState;
}
public static Boolean getSmsServiceState() {
return smsServiceState;
}
public static void setSmsServiceState(Boolean smsServiceState) {
ConfigAppValues.smsServiceState = smsServiceState;
}
//------------------------------------------------------------------------//
}
| 120301csr038-description | src/es/cesar/quitesleep/staticValues/ConfigAppValues.java | Java | gpl3 | 4,498 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import android.util.Log;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class SmsOperations {
private static final String CLASS_NAME = "es.cesar.quitesleep.operations.SmsOperations";
/**
* Save the smsText body in the ddbb.
* @param smsText
* @return true or false if depends of the successfully operation
*/
public static boolean saveSmsSettings (String smsText) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null)
settings.setSmsText(smsText);
else {
settings = new Settings(false);
settings.setSmsText(smsText);
}
clientDDBB.getInserts().insertSettings(settings);
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/SmsOperations.java | Java | gpl3 | 1,957 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import java.util.List;
import android.util.Log;
import android.widget.CheckBox;
import es.cesar.quitesleep.ddbb.Banned;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Contact;
import es.cesar.quitesleep.ddbb.Mail;
import es.cesar.quitesleep.ddbb.Phone;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class ContactOperations {
private final static String CLASS_NAME = "es.cesar.quitesleep.operations.AddContact";
/**
* Update the contact object, create the associated Banned object and
* updates the phones and mail objects putting the flag useToSend to true
* or false for send messages when incoming calls that not respond.
*
* @param contactName
* @param phoneCheckboxList
* @param mailCheckboxList
* @return true or false depends for the operation successfully
* @see boolean
*/
public static boolean addContact (
String contactName,
List<CheckBox> phoneCheckboxList,
List<CheckBox> mailCheckboxList) {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "EN addContact");
ClientDDBB clientDDBB = new ClientDDBB();
//-------- Update Contact --------------------------//
Contact contact = clientDDBB.getSelects().selectContactForName(contactName);
contact.setBanned(true);
clientDDBB.getUpdates().insertContact(contact);
//---------- Create and insert Banned ------------------//
Schedule schedule = clientDDBB.getSelects().selectSchedule();
Banned banned = new Banned(contact, schedule);
clientDDBB.getInserts().insertBanned(banned);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Updated Contact and Banned");
//--------------- Update Phone --------------------------//
List<Phone> phoneList =
clientDDBB.getSelects().selectAllContactPhonesForName(contactName);
for (int i=0; i<phoneList.size(); i++) {
Phone phone = phoneList.get(i);
int j=0;
boolean find = false;
while (j<phoneCheckboxList.size() && !find) {
CheckBox checkbox = phoneCheckboxList.get(j);
if (checkbox.getText().equals(phone.getContactPhone())) {
phone.setUsedToSend(checkbox.isChecked());
clientDDBB.getUpdates().insertPhone(phone);
find = true;
}
j++;
}
}
//----------------- Update Mail --------------------------//
List<Mail> mailList =
clientDDBB.getSelects().selectAllContactMailsForName(contactName);
for (int i=0; i<mailList.size(); i++) {
Mail mail = mailList.get(i);
int j=0;
boolean find = false;
while (j<mailCheckboxList.size() && !find) {
CheckBox checkbox = mailCheckboxList.get(j);
if (checkbox.getText().equals(mail.getContactMail())) {
mail.setUsedToSend(checkbox.isChecked());
clientDDBB.getUpdates().insertMail(mail);
find = true;
}
j++;
}
}
//---------- Commit and close --------------------------//
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Remove contact from the banned list, updating the contact object and
* remove the banned object.
*
* @param contactName
* @return true or false depends for the operation successfully
* @see boolean
*/
public static boolean removeContact (String contactName) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
//--------- Update Contact ------------------------------//
Contact contact = clientDDBB.getSelects().selectContactForName(contactName);
contact.setBanned(false);
clientDDBB.getUpdates().insertContact(contact);
//--------- Delete Banned --------------------------//
Banned banned = clientDDBB.getSelects().selectBannedContactForName(contactName);
clientDDBB.getDeletes().deleteBanned(banned);
//---------- Commit and close ----------------------//
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Update all edit attributes from the contact passed as its phone numbers
* and mail addresses used for send messages when incomig call is here
* and the contact is banned.
*
* @param contactName
* @param phoneCheckboxList
* @param mailCheckboxList
*
* @return true or false depends for the operation successfully
* @see boolean
*/
public static boolean editContact (
String contactName,
List<CheckBox> phoneCheckboxList,
List<CheckBox> mailCheckboxList) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
//----------------- Update all edit phones ------------------//
List<Phone> phoneList =
clientDDBB.getSelects().selectAllContactPhonesForName(contactName);
for (int i=0; i<phoneList.size(); i++) {
Phone phone = phoneList.get(i);
int j=0;
boolean find = false;
while (j<phoneCheckboxList.size() && !find) {
CheckBox checkbox = phoneCheckboxList.get(j);
if (checkbox.getText().equals(phone.getContactPhone())) {
phone.setUsedToSend(checkbox.isChecked());
clientDDBB.getUpdates().insertPhone(phone);
find = true;
}
j++;
}
}
//------------- Update all edit mails ------------------//
List<Mail> mailList =
clientDDBB.getSelects().selectAllContactMailsForName(contactName);
for (int i=0; i<mailList.size(); i++) {
Mail mail = mailList.get(i);
int j=0;
boolean find = false;
while (j<mailCheckboxList.size() && !find) {
CheckBox checkbox = mailCheckboxList.get(j);
if (checkbox.getText().equals(mail.getContactMail())) {
mail.setUsedToSend(checkbox.isChecked());
clientDDBB.getUpdates().insertMail(mail);
find = true;
}
j++;
}
}
//---------------- Commit and close ------------------//
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/ContactOperations.java | Java | gpl3 | 7,294 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import android.util.Log;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class MailOperations {
private final static String CLASS_NAME = "es.cesar.quitesleep.operations.MailOperations";
/**
* Function that save the mail settings into Settings object from the ddbb,
* if the Settings object doesn't exists we create it, and if it exists,
* update one.
*
* @param user
* @param passwd
* @param subject
* @param body
*
* @return true or false if the operation was sucessfully or not
* @see boolean
*/
public static boolean saveMailSettings (
String user,
String passwd,
String subject,
String body) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
/* ------- Save the mail settings, both if Settings object not
* exists or if exists ------------------------------------- */
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
settings.setUser(user);
settings.setPasswd(passwd);
settings.setSubject(subject);
settings.setBody(body);
clientDDBB.getUpdates().insertSettings(settings);
}
/* Never must be used this else because in onCreate, if the Settings
* object isn't created previously, then there we create it.
* But we i leave post because previously i already coded it.
*/
else {
settings = new Settings(false);
settings.setUser(user);
settings.setPasswd(passwd);
settings.setSubject(subject);
settings.setBody(body);
clientDDBB.getInserts().insertSettings(settings);
}
//------------ Commit & close -------------------------//
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Function that save the mailService sending state, in both, the Settings
* object in the ddbb and the static variable for more fast access later.
*
* @param mailServiceState
*
* @return true or false depends of sucessfully operation
* @see boolean
*/
public static boolean saveMailServiceState (boolean mailServiceState) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
settings.setMailService(mailServiceState);
clientDDBB.getUpdates().insertSettings(settings);
}
/* Never must be used this else because in onCreate, if the Settings
* object isn't created previously, then there we create it.
* But we i leave post because previously i already coded it.
*/
else {
settings = new Settings(false);
settings.setMailService(mailServiceState);
clientDDBB.getUpdates().insertSettings(settings);
}
//Update the global static variable for fast access later
ConfigAppValues.setMailServiceState(mailServiceState);
//Comit & close
clientDDBB.commit();
clientDDBB.close();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/MailOperations.java | Java | gpl3 | 4,330 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.content.Context;
import android.media.AudioManager;
import android.os.Vibrator;
import es.cesar.quitesleep.ddbb.CallLog;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Contact;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.mailmessages.SendMail;
import es.cesar.quitesleep.smsmessages.SendSMSThread;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.TokenizerUtils;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class IncomingCallOperations extends Thread {
private static final String CLASS_NAME = "es.cesar.quitesleep.utils.operations.IncomingCallOperations";
private String incomingCallNumber;
//---------------- Getters & Setters ----------------------------------//
public String getIncomingCallNumber() {
return incomingCallNumber;
}
public void setIncomingCallNumber(String incomingCallNumber) {
this.incomingCallNumber = incomingCallNumber;
}
//------------------------------------------------------------------------//
/**
* Constructor
* @param incomingCallNumber
*/
public IncomingCallOperations(String incomingCallNumber) {
this.incomingCallNumber = incomingCallNumber;
}
@Override
public void run () {
silentIncomingCall();
}
/**
* Function that check if the incoming call number is from a banned contact,
* if is true, put the mobile to silent mode (sound and vibrate), if is
* false do nothing.
*
* UPDATE 05-05-2010: now, we puts always the phone in silent mode when incoming
* call, but, then, quitesleep check if the contact is banned and if is in the
* schedule time, if is true, creates a new CallLog object, and we don't nothing
* with the phone mode, so it was put in silent mode at beginning.
* But if the incoming phone not is from a banned contact and/or if not
* is in the schedule time, put the mobile phone in normal mode.
* I have done this, because, is the only manner i get, that the phone never ring
* one sec when an incoming call from a banned contact arrives and the only way
* to put the mobile phone with vibrator off, one time the mobile phone is in normal
* mode the ring is too on.
* The inconvenience is that whatever incoming call the first tone the mobile
* phone silence it, not is the perfect way but is the only and the best way
* that i have reached with >Android 2.0 at day.
*
*/
public void silentIncomingCall () {
try {
/* Put the mobile phone in silent mode (sound+vibration)
* Here i put this for silent all incoming call for salomonic decision
* that silent all calls for later if the contact is banned let this
* silent mode and if the contact isn't banned put in normal mode.
* I use this because sometimes a ring second sound when an incoming call.
*/
//putRingerModeSilent();
ClientDDBB clientDDBB = new ClientDDBB();
String phoneNumberWhithoutDashes =
TokenizerUtils.tokenizerPhoneNumber(incomingCallNumber, null);
Contact contactBanned =
clientDDBB.getSelects().selectBannedContactForPhoneNumber(
phoneNumberWhithoutDashes);
//If the contact is in the banned list
if (contactBanned != null) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Contact: " + contactBanned.getContactName() +
"\t isBanned: " + contactBanned.isBanned());
//create the CallLog object for log calls.
CallLog callLog = new CallLog();
//check if the call is in the interval time
boolean isInInterval = checkSchedule(callLog, clientDDBB);
if (isInInterval) {
//Put the mobile phone in silent mode (sound+vibration)
putRingerModeSilent();
/* Check if the mail service is running, if it is true
* create a SendMail object for try to send one or more
* email to the contact with the incoming number
*/
sendMail(incomingCallNumber, callLog, clientDDBB);
/* Check if the sms service is running, if it is true
* create a SendSMS object for try to send a SMS to
* the contact with the incoming number
*/
sendSMS(incomingCallNumber, callLog, clientDDBB);
//get the nomOrder for the new CallLog
int numOrder = clientDDBB.getSelects().countCallLog();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "CallLog numOrder: " + numOrder);
//Set the parameters and save it
callLog.setPhoneNumber(phoneNumberWhithoutDashes);
callLog.setContact(contactBanned);
callLog.setNumOrder(numOrder+1);
clientDDBB.getInserts().insertCallLog(callLog);
clientDDBB.commit();
clientDDBB.close();
}
//If the call isn't in the interval time
else {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "No está en el intervalo");
//putRingerModeNormal();
clientDDBB.close();
}
}
//If the incoming call number isn't of the any banned contact
else {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "ContactBanned == NULL!!!!");
//putRingerModeNormal();
clientDDBB.close();
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Compare the present time with the schedule start and end times (interval)
*
* @return true if the present time is in the interval or false
* if isn't
* @see boolean
*/
private boolean checkSchedule (CallLog callLog, ClientDDBB clientDDBB) {
try {
//ClientDDBB clientDDBB = new ClientDDBB();
Schedule schedule = clientDDBB.getSelects().selectSchedule();
//clientDDBB.close();
if (schedule != null && CheckSettingsOperations.checkDayWeek(schedule)) {
return isInInterval(callLog, schedule);
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Function that check if the call incoming with the now time, is between the
* twho hours specified as start and end of the interval specified by the user.
*
* @param callLog
* @param schedule
* @return true or false if the incoming call with the actual hour
* is in an interval delimit by the start and end hours
* @see boolean
*/
private boolean isInInterval (CallLog callLog, Schedule schedule) {
try {
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
Calendar dateAndTime = Calendar.getInstance();
String timeNow = timeFormat.format(dateAndTime.getTime());
String timeStart = schedule.getStartFormatTime();
String timeEnd = schedule.getEndFormatTime();
String timeNowComplete = getCompleteDate(dateAndTime);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "time now: " + timeNowComplete);
callLog.setTimeCall(timeNowComplete);
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date start = parser.parse(timeStart);
Date end = parser.parse(timeEnd);
Date now = parser.parse(timeNow);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "start: " + start + "\ttimeStart: " + timeStart);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "end: " + end + "\ttimeEnd: " + timeEnd);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "now: " + now + "\timeNow: " + timeNow);
String dayCompleteString = "24:00";
Date dayComplete = parser.parse(dayCompleteString);
String dayInitString = "00:00";
Date dayInit = parser.parse(dayInitString);
final int INCREASE = 24;
boolean isInInterval;
//If both times are equals (24h) (si 8:00 = 8:00)
if (start.compareTo(end) == 0)
isInInterval = true;
//(Si start=10:00 end=21:00))
//If end time is after than start time (ie: start=10:00 end=21:00)
else if (end.after(start) && (now.after(start) && now.before(end)))
isInInterval = true;
/* If end time is before than start time (ie: start=22:00 end=3:00)
* then, we must be add 24 to the end time. (so ie: start=22:00 end:27:00)
*/
//(Si start=22:00 end=3:00 ==> newEnd=3:00+24=27:00)
else if (end.before(start)) {
String newEndTimeString = TokenizerUtils.addIncreaseDate(
timeEnd,
INCREASE,
null);
Date newEndTime = parser.parse(newEndTimeString);
/* (Si start=22:00 now=23:00 dayComplete=24:00, antes
* hemos comprobado que end<start==> end: 3:00)
*/
if (now.after(start) && now.before(dayComplete))
isInInterval = true;
/* (Si now>00:00==> now=2:00 now<newEnd(27:00) ==> now=2:00+24=26:00)
* así que ahora queda start=23:00 end=27:00 y now=26:00
*/
else if (now.after(dayInit) && now.before(newEndTime)) {
String newNowTimeString = TokenizerUtils.addIncreaseDate(
timeNow,
INCREASE,
null);
Date newNowTime = parser.parse(newNowTimeString);
if (newNowTime.after(start) && newNowTime.before(newEndTime))
isInInterval = true;
else
isInInterval = false;
}else
isInInterval = false;
}else
isInInterval = false;
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Está en el intervalo: " + isInInterval);
return isInInterval;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Get the compelte format date in English mode
*
* @param now
* @return the complete format date
* @see String
*/
private String getCompleteDate (Calendar now) {
try {
return (now.get(Calendar.MONTH) + 1) + "-"
+ now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR) + " "
+ now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":"
+ now.get(Calendar.SECOND);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
/**
* Put the vibrator in mode off
*/
private void vibrateOff () {
try {
String vibratorService = Context.VIBRATOR_SERVICE;
Vibrator vibrator = (Vibrator)ConfigAppValues.getContext().
getSystemService(vibratorService);
vibrator.cancel();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Send mail to the contact caller
* @param incomingNumber
* @param callLog
* @param clientDDBB
*/
private void sendMail (String incomingNumber, CallLog callLog, ClientDDBB clientDDBB) {
try {
if (CheckSettingsOperations.checkMailService(clientDDBB)) {
//------------------------------------------------------------//
//Send mail using Threads
SendMail sendMail = new SendMail(incomingNumber, callLog);
Thread threadMail = new Thread(sendMail);
threadMail.start();
threadMail.join();
//------------------------------------------------------------//
//------------------------------------------------------------//
//Send mail without use Threads
/*
SendMail sendMail = new SendMail(incomingNumber, callLog);
sendMail.sendMail();
*/
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Send SMS message to the contact caller
*
* @param incomingNumber
* @param callLog
* @param clientDDBB
*/
private void sendSMS (String incomingNumber, CallLog callLog, ClientDDBB clientDDBB) {
try {
if (CheckSettingsOperations.checkSmsService(clientDDBB)) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "antes de enviar el sms");
//-- If u choose use Android Service for send SMS use this --//
/*
ConfigAppValues.getContext().startService(
new Intent(
ConfigAppValues.getContext(),
SendSMSService.class).putExtra(
ConfigAppValues.RECEIVER,
incomingNumber));
*/
//------------------------------------------------------------//
//----- If u choose Java Thread for send SMS use this -----//
SendSMSThread sendSMS = new SendSMSThread(incomingNumber, callLog);
sendSMS.start();
sendSMS.join();
//------------------------------------------------------------//
//------------------------------------------------------------//
//Use without using threads
/*
SendSMSThread sendSMS = new SendSMSThread(incomingNumber);
sendSMS.sendSms();
*/
//------------------------------------------------------------//
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Put the mobile in silence mode (audio and vibrate)
*
*/
private void putRingerModeSilent () {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Poniendo el movil en modo silencio");
AudioManager audioManager =
(AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
private void putRingerModeNormal () {
try {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Poniendo el movil en modo normal");
AudioManager audioManager =
(AudioManager)ConfigAppValues.getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/IncomingCallOperations.java | Java | gpl3 | 15,269 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.dialogs.AddAllDialog;
import es.cesar.quitesleep.dialogs.CallLogDialog;
import es.cesar.quitesleep.dialogs.RemoveAllDialog;
import es.cesar.quitesleep.dialogs.SyncContactsDialog;
import es.cesar.quitesleep.menus.AddAllMenu;
import es.cesar.quitesleep.menus.RefreshCallLogMenu;
import es.cesar.quitesleep.menus.RemoveAllMenu;
import es.cesar.quitesleep.menus.RemoveCallLogMenu;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.syncData.SyncContactsRefresh;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class DialogOperations {
private final static String CLASS_NAME = "es.cesar.quitesleep.operations.DialogOperations";
/**
* Sync the contacts data between SQLite and DB4O databases the first time
* if the db4o database is empty.
* It is done used one thread for it.
*/
public static void syncContactsRefresh () {
try {
SyncContactsDialog syncDialog = new SyncContactsDialog();
SyncContactsRefresh syncContacts =
new SyncContactsRefresh(ConfigAppValues.getContext(), syncDialog);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Refreshing the database");
syncDialog.showDialogRefreshList(ConfigAppValues.getContext());
syncContacts.start();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error();
}
}
/**
* Function that add all contacts to the banned list in one separated thread,
* and show a progressDialog fow wait for it, and an handler for clear the
* arrayAdapter one habe been finished.
*/
public static void addAllContacts (
Context context,
ArrayAdapter<String> arrayAdapter,
Handler handler) {
try {
/* Only can selectAll contacts if the arrayAdapter is != null and
* have content, that is the state of it when prevously we add all
* contacts.
*/
if (arrayAdapter != null && arrayAdapter.getCount()>0) {
//Create the progressDialog used while the system add all contacts
AddAllDialog addAllDialog = new AddAllDialog();
//Create the object that this thread will do the process
AddAllMenu addAllMenu = new AddAllMenu(arrayAdapter, addAllDialog, handler);
//Show the progress dialog and run the thread for add all contacts
addAllDialog.showDialog(context);
addAllMenu.start();
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error();
}
}
/**
* Function that start the remove banned contacts from the banned list
* in a separated thread and use a progressDialog for wait for it, and
* handler for clear the arrayAdapter once have finished.
*/
public static void removeAllContacts (
Context context,
ArrayAdapter<String> arrayAdapter,
Handler handler) {
try {
/* Only can selectAll contacts if the arrayAdapter is != null and
* have content, that is the state of it when prevously we add all
* contacts.
*/
if (arrayAdapter != null && arrayAdapter.getCount()>0) {
//Create the progressDialog used while the system add all contacts
RemoveAllDialog removeAllDialog = new RemoveAllDialog();
//Create the object that this thread will do the process
RemoveAllMenu removeAllMenu =
new RemoveAllMenu(arrayAdapter, removeAllDialog, handler);
//Show the progress dialog and run the thread for add all contacts
removeAllDialog.showDialog(context);
removeAllMenu.start();
}
}catch (Exception e) {
Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error();
}
}
/**
* Function that does the operations about start and stop the sms service
*/
public static void checkSmsService (Context context, boolean isChecked) {
try {
boolean result = StartStopServicesOperations.startStopSmsService(isChecked);
if (isChecked) {
if (result)
//All right, start the service was ok!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.smssettings_toast_start_service),
Toast.LENGTH_SHORT);
else
//An error has ocurred!!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.smssettings_toast_fail_service),
Toast.LENGTH_SHORT);
}else {
if (result)
//All right, stop the service was ok!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.smssettings_toast_stop_service),
Toast.LENGTH_SHORT);
else
//An error has ocurred!!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.smssettings_toast_fail_service),
Toast.LENGTH_SHORT);
}
}catch (Exception e) {
Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Function that does the operations about start and stop the mail service
*/
public static void checkMailService (Context context, boolean isChecked) {
try {
boolean result = StartStopServicesOperations.startStopMailService(isChecked);
if (isChecked) {
if (result)
//All right, start the service was ok!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.mailsettings_toast_start_service),
Toast.LENGTH_SHORT);
else
//An error has ocurred!!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.mailsettings_toast_fail_service),
Toast.LENGTH_SHORT);
}else {
if (result)
//All right, stop the service was ok!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.mailsettings_toast_stop_service),
Toast.LENGTH_SHORT);
else
//An error has ocurred!!
if (QSToast.RELEASE) QSToast.r(
context,
context.getString(
R.string.mailsettings_toast_fail_service),
Toast.LENGTH_SHORT);
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Remove all call log objects from the ddbb for clean the call log information
* list.
*
* @param context
* @param arrayAdapter
* @param handler
*/
public static void removeAllCallLogs (
Context context,
ArrayAdapter<String> arrayAdapter,
Handler handler) {
try {
/* Only can selectAll contacts if the arrayAdapter is != null and
* have content, that is the state of it when prevously we add all
* contacts.
*/
if (arrayAdapter != null && arrayAdapter.getCount()>0) {
//Create the progressDialog used while the system add all contacts
CallLogDialog callLogDialog = new CallLogDialog();
//Create the object that this thread will do the process
RemoveCallLogMenu callLogMenu =
new RemoveCallLogMenu(arrayAdapter, callLogDialog, handler);
//Show the progress dialog and run the thread for add all contacts
callLogDialog.showDialog(context, ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS);
callLogMenu.start();
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error();
}
}
public static void refreshAllCallLogs (
Context context,
ArrayAdapter<String> arrayAdapter,
Handler handler) {
try {
//Create the progressDialog used while the system add all contacts
CallLogDialog callLogDialog = new CallLogDialog();
//Create the object that this thread will do the process
RefreshCallLogMenu refreshCallLogMenu =
new RefreshCallLogMenu(arrayAdapter, callLogDialog, handler);
//Show the progress dialog and run the thread for add all contacts
callLogDialog.showDialog(context, ConfigAppValues.WARNING_REFRESH_CALL_LOG);
refreshCallLogMenu.start();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/DialogOperations.java | Java | gpl3 | 10,071 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import java.util.Calendar;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class CheckSettingsOperations {
private static final String CLASS_NAME = "es.cesar.quitesleep.operations.CheckServicesOperations";
/**
* Check if the Settings object is created in the ddbb. If it's created
* check this attribute serviceState for check if the service is up
* or is down.
*
* @return true if the service is running or false if not.
*/
public static boolean checkQuiteSleepServiceState () {
try {
boolean serviceState = false;
if (ConfigAppValues.getQuiteSleepServiceState() != null)
serviceState = ConfigAppValues.getQuiteSleepServiceState();
else {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
clientDDBB.close();
if (settings != null)
serviceState = settings.isQuiteSleepServiceState();
}
return serviceState;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Check if today is a selected day for use the banned contacts list and schedule.
*
* @param schedule
* @return true if today is one "banned day" or false if isn't
* @see boolean
*/
public static boolean checkDayWeek (Schedule schedule) {
try {
Calendar dateAndTime = Calendar.getInstance();
int dayWeek = dateAndTime.get(Calendar.DAY_OF_WEEK);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Day Week: " + dayWeek);
switch (dayWeek) {
case Calendar.SUNDAY:
return schedule.isSunday();
case Calendar.MONDAY:
return schedule.isMonday();
case Calendar.TUESDAY:
return schedule.isTuesday();
case Calendar.WEDNESDAY:
return schedule.isWednesday();
case Calendar.THURSDAY:
return schedule.isThursday();
case Calendar.FRIDAY:
return schedule.isFriday();
case Calendar.SATURDAY:
return schedule.isSaturday();
}
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Check if the mail service for send email is activated or not
*
* @param clientDDBB
* @return true or false if it is activated or not
*/
public static boolean checkMailService (ClientDDBB clientDDBB) {
try {
if (ConfigAppValues.getMailServiceState() != null)
return ConfigAppValues.getMailServiceState();
else {
//ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
ConfigAppValues.setMailServiceState(settings.isMailService());
//clientDDBB.close();
return ConfigAppValues.getMailServiceState();
}
/* Mustn't be never this case because previously the settings object
* must be created
*/
else {
settings = new Settings(false);
clientDDBB.getInserts().insertSettings(settings);
clientDDBB.commit();
//clientDDBB.close();
return false;
}
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(
CLASS_NAME,
ExceptionUtils.exceptionTraceToString(e.toString(), e.getStackTrace()));
return false;
}
}
/**
* Check if the sms service for send sms is activated or not
*
* @param clientDDBB
* @return true or false depends of the state
* @see boolean
*/
public static boolean checkSmsService (ClientDDBB clientDDBB) {
try {
if (ConfigAppValues.getSmsServiceState() != null)
return ConfigAppValues.getSmsServiceState();
else {
//ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
ConfigAppValues.setSmsServiceState(settings.isSmsService());
//clientDDBB.close();
return ConfigAppValues.getSmsServiceState();
}else {
settings = new Settings(false);
clientDDBB.getInserts().insertSettings(settings);
clientDDBB.commit();
//clientDDBB.close();
return false;
}
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/CheckSettingsOperations.java | Java | gpl3 | 5,544 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.operations;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class StartStopServicesOperations {
private static final String CLASS_NAME = "es.cesar.quitesleep.operations.StartStopService";
/**
* Start or Stop the QuiteSleep incoming call service. If the service is already started
* nothing to do and return true, if the service isn't active, return true
* saving the state in the Settings object in the ddbb.
*
* @param stateQuiteSleepService
* @return True if the operation was sucessfully. False if an exception occurred.
* @see boolean
*/
public static boolean startStopQuiteSleepService (
boolean stateQuiteSleepService) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null) {
settings.setQuiteSleepServiceState(stateQuiteSleepService);
}else {
settings = new Settings();
settings.setQuiteSleepServiceState(stateQuiteSleepService);
}
clientDDBB.getUpdates().insertSettings(settings);
clientDDBB.commit();
clientDDBB.close();
//Put true or false if the start service was ok
ConfigAppValues.setQuiteSleepServiceState(stateQuiteSleepService);
//IncomingCallOperations.vibrateOff();
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Function that update the ddbb with the state of mailService
*
* @param mailServiceState
* @return true if the operation was sucessfully or false if some
* exception occurred
* @see boolean
*/
public static boolean startStopMailService (boolean mailServiceState) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null)
settings.setMailService(mailServiceState);
else {
settings = new Settings(false);
settings.setMailService(mailServiceState);
}
clientDDBB.getUpdates().insertSettings(settings);
clientDDBB.commit();
clientDDBB.close();
//Put the mail state service in the static attribute
ConfigAppValues.setMailServiceState(mailServiceState);
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Function that update the ddbb with the state of smsService
*
* @param smsServiceState
* @return true if the operation was sucessfully or false if not
* @see boolean
*/
public static boolean startStopSmsService (boolean smsServiceState) {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null)
settings.setSmsService(smsServiceState);
else {
settings = new Settings(false);
settings.setSmsService(smsServiceState);
}
clientDDBB.getInserts().insertSettings(settings);
clientDDBB.commit();
clientDDBB.close();
//Put the sms state service in the static attribute
ConfigAppValues.setSmsServiceState(smsServiceState);
return true;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/operations/StartStopServicesOperations.java | Java | gpl3 | 4,551 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import android.app.ProgressDialog;
import android.content.Context;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class CallLogDialog {
private String CLASS_NAME = getClass().getName();
private ProgressDialog progressDialog;
//-------- Getters & Setters --------------------------------------//
public ProgressDialog getProgressDialog() {
return progressDialog;
}
public void setProgressDialog(ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
//--------------------------------------------------------------------//
/**
* Constructor without parameters.
*/
public CallLogDialog () {
}
/**
* Show the synchronization message
*/
public void showDialog (Context context, int typeDialog) {
if (typeDialog == ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS)
progressDialog = ProgressDialog.show(
context,
"",
context.getString(R.string.calllogdialog_dialog_remove_label),
true);
else if (typeDialog == ConfigAppValues.WARNING_REFRESH_CALL_LOG)
progressDialog = ProgressDialog.show(
context,
"",
context.getString(R.string.calllogdialog_dialog_refresh_label),
true);
}
/**
* Hide and dismiss the synchronization message
* @param context
*/
public void stopDialog (Context context) {
//progressDialog.cancel();
progressDialog.dismiss();
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/CallLogDialog.java | Java | gpl3 | 2,282 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.operations.DialogOperations;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class WarningDialog {
private final String CLASS_NAME = getClass().getName();
private int alertDialogImage = R.drawable.dialog_warning;
private AlertDialog alertDialog;
private int operationType;
//Use for addAll, removeAll, smsService and mailService
private Context context;
//Use for addAll and removeAll
private ArrayAdapter<String> arrayAdapter;
private Handler handler;
//Use for smsService and mailService
private boolean toggleButtonIsChecked;
private int title;
private int message;
//------------------ Getters & Setters ----------------------//
public AlertDialog getAlertDialog() {
return alertDialog;
}
public void setAlertDialog(AlertDialog alertDialog) {
this.alertDialog = alertDialog;
}
public int getOperationType() {
return operationType;
}
public void setOperationType(int operationType) {
this.operationType = operationType;
}
public int getTitle() {
return title;
}
public void setTitle(int title) {
this.title = title;
}
public int getMessage() {
return message;
}
public void setMessage(int message) {
this.message = message;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public ArrayAdapter<String> getArrayAdapter() {
return arrayAdapter;
}
public void setArrayAdapter(ArrayAdapter<String> arrayAdapter) {
this.arrayAdapter = arrayAdapter;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public boolean isToggleButtonIsChecked() {
return toggleButtonIsChecked;
}
public void setToggleButtonIsChecked(boolean toggleButtonIsChecked) {
this.toggleButtonIsChecked = toggleButtonIsChecked;
}
//------------------------------------------------------------------------//
/**
* Get the title and message for each type of operation
*/
private void getLabelsOperationType () {
try {
title = R.string.warningdialog_caution_label;
switch (operationType) {
case ConfigAppValues.WARNING_ADD_ALL_CONTACTS:
message = R.string.warningdialog_contactOperations_label;
break;
case ConfigAppValues.WARNING_REMOVE_ALL_CONTACTS:
message = R.string.warningdialog_contactOperations_label;
break;
case ConfigAppValues.WARNING_SYNC_CONTACTS:
message = R.string.warningdialog_synccontact_label;
break;
case ConfigAppValues.WARNING_SMS_ACTION:
message = R.string.warningdialog_sms_label;
break;
case ConfigAppValues.WARNING_MAIL_ACTION:
message = R.string.warningdialog_mail_label;
break;
case ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS:
message = R.string.warningdialog_calllog_remove_label;
break;
case ConfigAppValues.WARNING_REFRESH_CALL_LOG:
message = R.string.warningdialog_calllog_refresh_label;
break;
default:
break;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
*
*/
private void callOperationType () {
try {
switch (operationType) {
case ConfigAppValues.WARNING_ADD_ALL_CONTACTS:
DialogOperations.addAllContacts(context, arrayAdapter, handler);
break;
case ConfigAppValues.WARNING_REMOVE_ALL_CONTACTS:
DialogOperations.removeAllContacts(context, arrayAdapter, handler);
break;
case ConfigAppValues.WARNING_SYNC_CONTACTS:
DialogOperations.syncContactsRefresh();
break;
case ConfigAppValues.WARNING_SMS_ACTION:
DialogOperations.checkSmsService(context, toggleButtonIsChecked);
break;
case ConfigAppValues.WARNING_MAIL_ACTION:
DialogOperations.checkMailService(context, toggleButtonIsChecked);
break;
case ConfigAppValues.WARNING_REMOVE_ALL_CALL_LOGS:
DialogOperations.removeAllCallLogs(context, arrayAdapter, handler);
break;
case ConfigAppValues.WARNING_REFRESH_CALL_LOG:
DialogOperations.refreshAllCallLogs(context, arrayAdapter, handler);
break;
default:
break;
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Constructor with the basic parameter
* @param activity
*/
public WarningDialog (final Activity activity, int operationType) {
this.operationType = operationType;
getLabelsOperationType();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setIcon(alertDialogImage);
builder.setTitle(title)
.setMessage(message);
if ((operationType != ConfigAppValues.WARNING_SMS_ACTION) &&
(operationType != ConfigAppValues.WARNING_MAIL_ACTION)) {
builder.setCancelable(false);
builder.setPositiveButton(
R.string.warningdialog_yes_label,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d(CLASS_NAME, "YES");
callOperationType();
}
});
builder.setNegativeButton(
R.string.warningdialog_no_label,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d(CLASS_NAME, "NO");
dialog.cancel();
//no debemos hacer nada extra.
}
});
}else {
builder.setNeutralButton(
R.string.warningdialog_ok_label,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d(CLASS_NAME, "OK");
callOperationType();
}
});
}
alertDialog = builder.create();
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/WarningDialog.java | Java | gpl3 | 7,413 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import android.app.ProgressDialog;
import android.content.Context;
import es.cesar.quitesleep.R;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class RemoveAllDialog {
private String CLASS_NAME = getClass().getName();
private ProgressDialog progressDialog;
//-------- Getters & Setters --------------------------------------//
public ProgressDialog getProgressDialog() {
return progressDialog;
}
public void setProgressDialog(ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
//--------------------------------------------------------------------//
/**
* Constructor without parameters.
*/
public RemoveAllDialog () {
}
/**
* Show the synchronization message
*/
public void showDialog (Context context) {
progressDialog = ProgressDialog.show(
context,
"",
context.getString(R.string.removealldialog_dialog_label),
true);
}
/**
* Hide and dismiss the synchronization message
* @param context
*/
public void stopDialog (Context context) {
//progressDialog.cancel();
progressDialog.dismiss();
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/RemoveAllDialog.java | Java | gpl3 | 1,920 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import android.app.ProgressDialog;
import android.content.Context;
import es.cesar.quitesleep.R;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class SyncContactsDialog {
private String CLASS_NAME = getClass().getName();
final int FIRST_TIME_SYNC = R.string.synccontactsdialog_message_firsttime_label;
final int ANY_TIME_SYNC = R.string.synccontactsdialog_message_anytime_label;
final int REFRESH_LIST = R.string.synccontactsdialog_message_refresh_label;
private ProgressDialog progressDialog;
private String messageDialog = "";
//-------- Getters & Setters --------------------------------------//
public ProgressDialog getProgressDialog() {
return progressDialog;
}
public void setProgressDialog(ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
public String getMessageDialog () {
return messageDialog;
}
public void setMessageDialog (String messageDialog) {
this.messageDialog = messageDialog;
}
//--------------------------------------------------------------------//
/**
* Constructor without parameters.
*/
public SyncContactsDialog () {
}
/**
* Show the dialog with the first time synchronization message
* @param context
*/
public void showDialogFirstTime (Context context) {
messageDialog = context.getString(FIRST_TIME_SYNC);
showDialog(context);
}
/**
* Show the dialog with the any time synchronization message
* @param context
*/
public void showDialogAnyTime (Context context) {
messageDialog = context.getString(ANY_TIME_SYNC);
showDialog(context);
}
public void showDialogRefreshList (Context context) {
messageDialog = context.getString(REFRESH_LIST);
showDialog(context);
}
/**
* Show the dialog with other synchronization message that we like
* @param context
* @param messageDialg
*/
public void showDialogOtherMessage (Context context, String messageDialg) {
this.messageDialog = messageDialg;
showDialog(context);
}
/**
* Show the synchronization message
* @param context
*/
private void showDialog (Context context) {
progressDialog = ProgressDialog.show(context, "", messageDialog, true);
}
/**
* Hide and dismiss the synchronization message
* @param context
*/
public void stopDialog (Context context) {
//progressDialog.cancel();
progressDialog.dismiss();
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/SyncContactsDialog.java | Java | gpl3 | 3,171 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.util.Log;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
*
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class EndTimeDialog {
private String CLASS_NAME = getClass().getName();
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
Calendar dateAndTime = Calendar.getInstance();
private TimePickerDialog timePickerDialog;
private TextView endTimeLabel;
private Activity activity;
//-------------- Getters & Setters -----------------------//
public TimePickerDialog getTimePickerDialog() {
return timePickerDialog;
}
public void setTimePickerDialog(TimePickerDialog timePickerDialog) {
this.timePickerDialog = timePickerDialog;
}
public TextView getEndTimeLabel() {
return endTimeLabel;
}
public void setEndTimeLabel(TextView endTimeLabel) {
this.endTimeLabel = endTimeLabel;
}
//-----------------------------------------------------------------------//
TimePickerDialog.OnTimeSetListener timerPickerEnd =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
view.setIs24HourView(true);
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
//Update operations
updateSchedule();
updateEndTimeLabel();
}
};
/**
* Constructor
*
* @param activity
*/
public EndTimeDialog (Activity activity) {
timePickerDialog = new TimePickerDialog(
activity,
timerPickerEnd,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE),
true);
this.activity = activity;
//If we have redefine the time picker dialog title
//timePickerDialog.setTitle(R.string.endtimedialog_message_label);
}
/**
* Update the endTimeLabel located in the activity ScheduleTab, with the
* selected by user endTime.
*/
private void updateEndTimeLabel () {
try {
if (endTimeLabel != null)
endTimeLabel.setText(timeFormat.format(dateAndTime.getTime()));
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Update the Schedule object from the database with the end time objects
* that have been used in the dialog and specified by the user.
*
* @throws Exception
*/
private void updateSchedule () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Schedule schedule = clientDDBB.getSelects().selectSchedule();
/* If the Schedule object is null, then never have been created before
* so, we have to create here.
*/
if (schedule == null)
schedule = new Schedule();
schedule.setAllEndTime(
dateAndTime.getTime(),
timeFormat.format(dateAndTime.getTime()));
clientDDBB.getUpdates().insertSchedule(schedule);
clientDDBB.commit();
clientDDBB.close();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Schedule saved with the end time!!");
if (QSToast.RELEASE) QSToast.r(
activity,
activity.getString(
R.string.schedule_toast_endTime),
Toast.LENGTH_SHORT);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error(e.toString());
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/EndTimeDialog.java | Java | gpl3 | 4,659 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import android.app.ProgressDialog;
import android.content.Context;
import es.cesar.quitesleep.R;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class AddAllDialog {
private String CLASS_NAME = getClass().getName();
private ProgressDialog progressDialog;
//-------- Getters & Setters --------------------------------------//
public ProgressDialog getProgressDialog() {
return progressDialog;
}
public void setProgressDialog(ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
//--------------------------------------------------------------------//
/**
* Constructor without parameters.
*/
public AddAllDialog () {
}
/**
* Show the synchronization message
*/
public void showDialog (Context context) {
progressDialog = ProgressDialog.show(
context,
"",
context.getString(R.string.addalldialog_dialog_label),
true);
}
/**
* Hide and dismiss the synchronization message
* @param context
*/
public void stopDialog (Context context) {
//progressDialog.cancel();
progressDialog.dismiss();
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/AddAllDialog.java | Java | gpl3 | 1,911 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.dialogs;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.util.Log;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import es.cesar.quitesleep.R;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Schedule;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
import es.cesar.quitesleep.utils.QSToast;
/**
* Custom alert dialog for setup the start time for control the contacts calls
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
*/
public class StartTimeDialog {
private String CLASS_NAME = getClass().getName();
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
Calendar dateAndTime = Calendar.getInstance();
private TimePickerDialog timePickerDialog;
private TextView startTimeLabel;
private Activity activity;
//-------------- Getters & Setters ------------------------------//
public TimePickerDialog getTimePickerDialog() {
return timePickerDialog;
}
public void setTimePickerDialog(TimePickerDialog timePickerDialog) {
this.timePickerDialog = timePickerDialog;
}
public TextView getStartTimeLabel() {
return startTimeLabel;
}
public void setStartTimeLabel(TextView startTimeLabel) {
this.startTimeLabel = startTimeLabel;
}
//----------------------------------------------------------------------//
TimePickerDialog.OnTimeSetListener timerPickerStart =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
view.setIs24HourView(true);
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
//Update operations
updateSchedule();
updateStartTimeLabel();
}
};
/**
* Constructor with one parameter
*
* @param activity
*/
public StartTimeDialog (Activity activity) {
timePickerDialog = new TimePickerDialog(
activity,
timerPickerStart,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE),
true);
this.activity = activity;
//If we have redefine the time picker dialog title
//timePickerDialog.setTitle(R.string.starttimedialog_message_label);
}
/**
* Update the startTimeLabel located in the activity ScheduleTab, with the
* selected by user startTime.
*/
private void updateStartTimeLabel () {
try {
if (startTimeLabel != null)
startTimeLabel.setText(timeFormat.format(dateAndTime.getTime()));
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Update the Schedule object from the database with the start time objects
* that have been used in the dialog and specified by the user.
*
* @throws Exception
*/
private void updateSchedule () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Schedule schedule = clientDDBB.getSelects().selectSchedule();
/* If the Schedule object is null, then never have been created before
* so, we have to create here.
*/
if (schedule == null)
schedule = new Schedule();
schedule.setAllStartTime(
dateAndTime.getTime(),
timeFormat.format(dateAndTime.getTime()));
clientDDBB.getUpdates().insertSchedule(schedule);
clientDDBB.commit();
clientDDBB.close();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Schedule saved with the start time!!");
if (QSToast.RELEASE) QSToast.r(
activity,
activity.getString(
R.string.schedule_toast_startTime),
Toast.LENGTH_SHORT);
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
throw new Error(e.toString());
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/dialogs/StartTimeDialog.java | Java | gpl3 | 4,808 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.smsmessages;
import java.util.ArrayList;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Phone;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* Class that implements Android Service for send sms to the incoming caller
*
*/
public class SendSMSService extends Service {
private final String CLASS_NAME = getClass().getName();
private String smsText;
private String incomingCallNumber;
//-------------- Getters & Setters --------------------------//
public String getSmsText() {
return smsText;
}
public void setSmsText(String smsText) {
this.smsText = smsText;
}
public String getIncomingCallNumber() {
return incomingCallNumber;
}
public void setIncomingCallNumber(String incomingCallNumber) {
this.incomingCallNumber = incomingCallNumber;
}
//------------------------------------------------------------------------//
//------------ Inherited method re-implement ----------------------//
@Override
public void onCreate () {
}
@Override
public IBinder onBind (Intent intent) {
return null;
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
String incomingCallNumber =
intent.getExtras().getString(ConfigAppValues.INCOMING_CALL_NUMBER);
SendSMSService sendSMS = new SendSMSService(incomingCallNumber);
sendSMS.sendSms();
return Service.START_STICKY;
}
//------------------------------------------------------------------------//
/**
* Constructor without parameters
*/
public SendSMSService () {
}
/**
* Constructor with the phonenumber of the receiver sms
*/
public SendSMSService (String incomingCallNumber) {
init(incomingCallNumber);
}
/**
* Function that is called for onStartCommand Service method start
* @param incomingCallNumber
*/
public void init (String incomingCallNumber) {
this.incomingCallNumber = incomingCallNumber;
getAllData();
}
/**
* Get all data of SMS settings
*/
private void getAllData () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null)
smsText = settings.getSmsText();
clientDDBB.close();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Check if the receiver phone number have permission to use for send SMS
* message
*
* @return true or false if the phone number (receiver) can or not receive
* messages
*/
private boolean checkSendPhoneNumber () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Phone phone = clientDDBB.getSelects().selectPhoneForPhoneNumber(incomingCallNumber);
clientDDBB.close();
if (phone != null)
return phone.isUsedToSend();
else
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
/**
* Send one SMS message to the receiver
*
*/
private void sendSms () {
try {
if (checkSendPhoneNumber()) {
final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
//Create the setIntent parameter
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(
ConfigAppValues.getContext(),
0,
sentIntent,
0);
//Create the deliveryIntetn parameter
Intent deliveryIntent = new Intent(DELIVERED_SMS_ACTION);
PendingIntent deliverPI = PendingIntent.getBroadcast(
ConfigAppValues.getContext(),
0,
deliveryIntent,
0);
SmsManager smsManager = SmsManager.getDefault();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SmsText: " + smsText);
/* In Nexus One there is a bug (how in htc tatoo) that sent sms
* using sendTextMessage not found, so i try to send sms by
* cut into parts (if its necessary) and send using sendMultipartMessage
*/
ArrayList<String> multipartSmsText = smsManager.divideMessage(smsText);
int smsSize = multipartSmsText.size();
//Create the arraylist PendingIntents for use it.
ArrayList<PendingIntent> sentPiList =
new ArrayList<PendingIntent>(smsSize);
ArrayList<PendingIntent> deliverPiList =
new ArrayList<PendingIntent>(smsSize);
for (int i=0; i<smsSize; i++) {
sentPiList.add(sentPI);
deliverPiList.add(deliverPI);
}
//Try to send the sms message
smsManager.sendMultipartTextMessage(
incomingCallNumber,
null,
multipartSmsText,
sentPiList,
deliverPiList);
}
}catch (Exception e) {
Log.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/smsmessages/SendSMSService.java | Java | gpl3 | 6,199 |
/*
Copyright 2010 Cesar Valiente Gordo
This file is part of QuiteSleep.
QuiteSleep is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QuiteSleep is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QuiteSleep. If not, see <http://www.gnu.org/licenses/>.
*/
package es.cesar.quitesleep.smsmessages;
import java.util.ArrayList;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.telephony.SmsManager;
import es.cesar.quitesleep.ddbb.CallLog;
import es.cesar.quitesleep.ddbb.ClientDDBB;
import es.cesar.quitesleep.ddbb.Phone;
import es.cesar.quitesleep.ddbb.Settings;
import es.cesar.quitesleep.staticValues.ConfigAppValues;
import es.cesar.quitesleep.utils.ExceptionUtils;
import es.cesar.quitesleep.utils.QSLog;
/**
*
* @author Cesar Valiente Gordo
* @mail cesar.valiente@gmail.com
*
* Class that implements Java Thread for send sms to the incoming caller
*
*/
public class SendSMSThread extends Thread {
private final String CLASS_NAME = getClass().getName();
private String smsText;
private String incomingCallNumber;
private CallLog callLog;
//-------------- Getters & Setters --------------------------//
public String getSmsText() {
return smsText;
}
public void setSmsText(String smsText) {
this.smsText = smsText;
}
public String getIncomingCallNumber() {
return incomingCallNumber;
}
public void setIncomingCallNumber(String incomingCallNumber) {
this.incomingCallNumber = incomingCallNumber;
}
public CallLog getCallLog() {
return callLog;
}
public void setCallLog(CallLog callLog) {
this.callLog = callLog;
}
//------------------------------------------------------------------------//
/**
* Constructor with the phonenumber of the receiver sms
*/
public SendSMSThread (String incomingCallNumber, CallLog callLog) {
init(incomingCallNumber, callLog);
}
/**
* Function that is called for the constructor
* @param incomingCallNumber
*/
public void init (String incomingCallNumber, CallLog callLog) {
this.incomingCallNumber = incomingCallNumber;
this.callLog = callLog;
getAllData();
}
/**
* Get all data of SMS settings
*/
private void getAllData () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Settings settings = clientDDBB.getSelects().selectSettings();
if (settings != null)
smsText = settings.getSmsText();
clientDDBB.close();
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
/**
* Check if the receiver phone number have permission to use for send SMS
* message
*
* @return true or false if the phone number (receiver) can or not receive
* messages
*/
private boolean checkSendPhoneNumber () {
try {
ClientDDBB clientDDBB = new ClientDDBB();
Phone phone = clientDDBB.getSelects().selectPhoneForPhoneNumber(incomingCallNumber);
clientDDBB.close();
if (phone != null)
return phone.isUsedToSend();
else
return false;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return false;
}
}
@Override
public void run () {
sendSms();
}
/**
* Send one SMS message to the receiver
*
*/
public void sendSms () {
try {
if (checkSendPhoneNumber()) {
final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
//Create the setIntent parameter
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(
ConfigAppValues.getContext(),
0,
sentIntent,
0);
//Create the deliveryIntetn parameter
Intent deliveryIntent = new Intent(DELIVERED_SMS_ACTION);
PendingIntent deliverPI = PendingIntent.getBroadcast(
ConfigAppValues.getContext(),
0,
deliveryIntent,
0);
SmsManager smsManager = SmsManager.getDefault();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "SmsText: " + smsText);
/* In Nexus One there is a bug (how in htc tatoo) that sent sms
* using sendTextMessage not found, so i try to send sms by
* cut into parts (if its necessary) and send using sendMultipartMessage
*/
ArrayList<String> multipartSmsText = smsManager.divideMessage(smsText);
int multipartSize = multipartSmsText.size();
//Create the arraylist PendingIntents for use it.
ArrayList<PendingIntent> sentPiList =
new ArrayList<PendingIntent>(multipartSize);
ArrayList<PendingIntent> deliverPiList =
new ArrayList<PendingIntent>(multipartSize);
for (int i=0; i<multipartSize; i++) {
sentPiList.add(sentPI);
deliverPiList.add(deliverPI);
}
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "MultipartSize: " + multipartSize);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "MultpartMessage: " + multipartSmsText);
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Send sms to: " + incomingCallNumber);
String operator = getOperator();
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "Operator: " + operator);
smsManager.sendMultipartTextMessage(
incomingCallNumber,
operator,
multipartSmsText,
sentPiList,
deliverPiList);
/* In the smssettings.xml layout i specified only 160 character,
* one message, so if the send have been done, setSendSms is true
*/
if (multipartSize > 0) {
if (QSLog.DEBUG_D)QSLog.d(CLASS_NAME, "MEssage send!!!");
callLog.setSendSms(true);
}
}
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
}
}
private String getOperator () {
try {
final Uri SMS_CONTENT_URI = Uri.parse("content://sms");
final String REPLY_PATH_PRESENT = "reply_path_present";
final String SERVICE_CENTER = "service_center";
final int COLUMN_REPLY_PATH_PRESENT = 0;
final int COLUMN_SERVICE_CENTER = 1;
final String[] SERVICE_CENTER_PROJECTION =
new String[] {REPLY_PATH_PRESENT, SERVICE_CENTER,};
Cursor cursor =
ConfigAppValues.getContext().getContentResolver().query(SMS_CONTENT_URI,
SERVICE_CENTER_PROJECTION, "thread_id = " + 0, null, "date DESC");
// cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(),
// Sms.CONTENT_URI, SERVICE_CENTER_PROJECTION,
// "thread_id = " + threadId, null, "date DESC");
if ((cursor == null) || !cursor.moveToFirst()) {
return null;
}
boolean replyPathPresent = (1 == cursor.getInt(COLUMN_REPLY_PATH_PRESENT));
if (cursor != null)
cursor.close();
return replyPathPresent ? cursor.getString(COLUMN_SERVICE_CENTER) : null;
}catch (Exception e) {
if (QSLog.DEBUG_E)QSLog.e(CLASS_NAME, ExceptionUtils.exceptionTraceToString(
e.toString(),
e.getStackTrace()));
return null;
}
}
}
| 120301csr038-description | src/es/cesar/quitesleep/smsmessages/SendSMSThread.java | Java | gpl3 | 7,805 |