Changeset 593084
- Timestamp:
- 08/31/2012 06:08:13 PM (14 years ago)
- Location:
- tinypass/branches/silver_bullet/api
- Files:
-
- 12 added
- 9 deleted
- 14 edited
-
TPClientMsgBuilder.php (modified) (1 diff)
-
TPOffer.php (modified) (4 diffs)
-
TPPriceOption.php (modified) (6 diffs)
-
TPRIDHash.php (modified) (1 diff)
-
TPSettings.php (deleted)
-
TPUtils.php (added)
-
TPVersion.php (deleted)
-
TinyPass.php (modified) (2 diffs)
-
TinyPassException.php (modified) (1 diff)
-
TinyPassGateway.php (added)
-
builder/TPClientBuilder.php (modified) (3 diffs)
-
builder/TPClientParser.php (modified) (2 diffs)
-
builder/TPCookieParser.php (added)
-
builder/TPJsonMsgBuilder.php (modified) (6 diffs)
-
builder/TPSecurityUtils.php (modified) (2 diffs)
-
policies/Policies.php (modified) (5 diffs)
-
policies/TPPolicy.php (modified) (1 diff)
-
token/TPAccessToken.php (modified) (3 diffs)
-
token/TPAccessTokenList.php (modified) (4 diffs)
-
token/TPAccessTokenStore.php (added)
-
token/TPMeter.php (added)
-
token/TPMeterDetails.php (deleted)
-
token/TPMeterStore.php (added)
-
token/TPToken.php (deleted)
-
token/TPTokenData.php (added)
-
token/TPTokenWrapper.php (deleted)
-
ui/TPHtmlWidget.php (added)
-
ui/TPPurchaseRequest.php (added)
-
ui/TPTicket.php (deleted)
-
ui/TPWebRequest.php (deleted)
-
ui/TPWebWidget.php (deleted)
-
ui/widget.html (deleted)
-
util (added)
-
util/TPPaySettings.php (added)
-
util/TPSettings.php (added)
Legend:
- Unmodified
- Added
- Removed
-
tinypass/branches/silver_bullet/api/TPClientMsgBuilder.php
r461624 r593084 19 19 } 20 20 21 public function build TicketRequest($tickets) {22 return $this->builder->build TicketRequest($tickets);21 public function buildPurchaseRequest($tickets) { 22 return $this->builder->buildPurchaseRequest($tickets); 23 23 } 24 24 -
tinypass/branches/silver_bullet/api/TPOffer.php
r461567 r593084 7 7 private $pricing; 8 8 private $policies = array(); 9 private $tags = array(); 9 10 10 11 public function __construct(TPResource $resource, $priceOptions) { 11 12 $this->resource = $resource; 12 13 13 if(!is_array($priceOptions)) 14 $priceOptions = array($priceOptions); 15 16 $this->pricing = TPPricingPolicy::createBasic($priceOptions); 14 if($priceOptions instanceof TPBasicPricing) { 15 $this->pricing = $priceOptions; 16 } else { 17 if(!is_array($priceOptions)) 18 $priceOptions = array($priceOptions); 19 $this->pricing = TPPricingPolicy::createBasic($priceOptions); 20 } 21 17 22 } 18 23 … … 25 30 } 26 31 27 public function isMetered() {28 foreach ($this->policies as $policy) {29 if ($policy instanceof TPMeteredPolicyImpl)30 return true;31 }32 return false;33 }34 35 32 public function addPolicy($policy) { 36 33 $this->policies[] = $policy; … … 40 37 public function getPolicies() { 41 38 return $this->policies; 42 }43 44 public function getMeteredPolicy() {45 foreach ($this->policies as $policy) {46 if ($policy instanceof TPMeteredPolicyImpl)47 return $policy;48 }49 return new TPPolicy();50 39 } 51 40 … … 60 49 } 61 50 } 51 52 public function hasActivePrices() { 53 return $this->getPricing()->hasActiveOptions(); 54 } 55 56 public function addTags($tags) { 57 if(!is_array($tags)) { 58 $tags = func_get_args(); 59 } 60 $this->tags = array_merge($this->tags, $tags); 61 return $this; 62 } 63 64 public function getTags() { 65 return $this->tags; 66 } 67 68 69 62 70 } 63 71 ?> -
tinypass/branches/silver_bullet/api/TPPriceOption.php
r461567 r593084 8 8 protected $price; 9 9 protected $accessPeriod; 10 protected $initAccessPeriod;11 10 protected $startDateInSecs; 12 11 protected $endDateInSecs; 13 12 protected $caption; 13 protected $trialPeriod; 14 protected $recurring = false; 14 15 15 16 protected $splitPay = array(); 16 17 17 private static $EXPIRE_PARSER = '/(\d+)\s*(\w+)/';18 18 19 19 public function __construct($price = null, $acessPeriod = null, $startDateInSecs = null, $endDateInSecs = null) { … … 21 21 $this->accessPeriod = $acessPeriod; 22 22 if($startDateInSecs) 23 $this->startDateInSecs = TPToken ::convertToEpochSeconds($startDateInSecs);23 $this->startDateInSecs = TPTokenData::convertToEpochSeconds($startDateInSecs); 24 24 if($endDateInSecs) 25 $this->endDateInSecs = TPToken ::convertToEpochSeconds($endDateInSecs);25 $this->endDateInSecs = TPTokenData::convertToEpochSeconds($endDateInSecs); 26 26 } 27 27 … … 40 40 41 41 public function getAccessPeriodInMsecs() { 42 if ($this->initAccessPeriod != null) return $this->initAccessPeriod; 43 44 if ($this->accessPeriod == null) return null; 45 46 return $this->initAccessPeriod = $this->parseLoosePeriod($this->accessPeriod); 42 return TPUtils::parseLoosePeriodInMsecs($this->accessPeriod); 47 43 } 48 44 49 45 public function getAccessPeriodInSecs() { 50 46 return $this->getAccessPeriodInMsecs() / 1000; 51 }52 53 public static function parseLoosePeriod($period) {54 if (preg_match("/^-?\d+$/", $period)) {55 return (int)$period;56 }57 $matches = array();58 if (preg_match(TPPriceOption::$EXPIRE_PARSER, $period, $matches)) {59 $num = $matches[1];60 $str = $matches[2];61 switch ($str[0]) {62 case 's':63 return $num * 1000;64 case 'm':65 66 if (strlen($str) > 1 && $str[1] == 'i')67 return $num * 60 * 1000;68 else if (strlen($str) > 1 && $str[1] == 's')69 return $num * 60;70 else if (strlen($str) == 1 || $str[1] == 'o')71 return $num * 30 * 24 * 60 * 60 * 1000;72 73 case 'h':74 return $num * 60 * 60 * 1000;75 case 'd':76 return $num * 24 * 60 * 60 * 1000;77 case 'w':78 return $num * 7 * 24 * 60 * 60 * 1000;79 }80 }81 82 throw new TinyPassException("Cannot parse the specified period: " . $period);83 47 } 84 48 … … 124 88 125 89 public function setCaption($caption) { 126 if($caption!=null && strlen($caption) > 23)127 $caption = substr($caption, 0, 23);90 if($caption!=null && strlen($caption) > 50) 91 $caption = substr($caption, 0, 50); 128 92 $this->caption = $caption; 129 93 return $this; … … 131 95 132 96 public function isActive($timestampSecs) { 133 $timestampSecs = TPToken ::convertToEpochSeconds($timestampSecs);97 $timestampSecs = TPTokenData::convertToEpochSeconds($timestampSecs); 134 98 if ($this->getStartDateInSecs() != null && $this->getStartDateInSecs() > $timestampSecs) return false; 135 99 if ($this->getEndDateInSecs() != null && $this->getEndDateInSecs() < $timestampSecs) return false; … … 137 101 } 138 102 103 public function isRecurring() { 104 return $this->recurring; 105 } 106 107 public function getTrialPeriod() { 108 return $this->trialPeriod; 109 } 110 111 public function getBillingPeriod() { 112 return $this->accessPeriod; 113 } 114 115 public function setRecurringBilling($billingPeriod, $trialPeriod = null) { 116 $this->recurring = true; 117 $this->accessPeriod = $billingPeriod; 118 if ($trialPeriod) 119 $this->trialPeriod = $trialPeriod; 120 return $this; 121 } 139 122 140 123 public function __toString() { 141 124 $sb = ""; 142 sb.("Price:").($this->getPrice()); 143 sb.("\tPeriod:").($this->getAccessPeriod()); 125 $sb.("Price:").($this->getPrice()); 126 $sb.("\tPeriod:").($this->getAccessPeriod()); 127 $sb.("\tTrial Period:").($this->getAccessPeriod()); 144 128 145 129 if ($this->getStartDateInSecs() != null) { 146 sb.("\tStart:").($this->getStartDateInSecs()).(":").( date('D, d M Y H:i:s' , $this->getStartDateInSecs()));130 $sb.("\tStart:").($this->getStartDateInSecs()).(":").( date('D, d M Y H:i:s' , $this->getStartDateInSecs())); 147 131 } 148 132 149 133 if ($this->getEndDateInSecs() != null) { 150 sb.("\tEnd:").($this->getEndDateInSecs()).(":").(date('D, d M Y H:i:s', $this->getEndDateInSecs()));134 $sb.("\tEnd:").($this->getEndDateInSecs()).(":").(date('D, d M Y H:i:s', $this->getEndDateInSecs())); 151 135 } 152 136 153 137 if ($this->getCaption() != null) { 154 sb.("\tCaption:").($this->getCaption());138 $sb.("\tCaption:").($this->getCaption()); 155 139 } 156 140 157 141 if ($this->splitPay != null) { 158 142 foreach ($this->splitPay as $key => $value) 159 sb.("\tSplit:").($key).(":").($value);143 $sb.("\tSplit:").($key).(":").($value); 160 144 } 145 146 if($this->isRecurring()) { 147 $sb.("\n\tBilling Period:").($this->getBillingPeriod()); 148 $sb.("\tTrial Period:").($this->getTrialPeriod()); 149 } 150 161 151 return $sb; 162 152 } -
tinypass/branches/silver_bullet/api/TPRIDHash.php
r461567 r593084 1 1 <?php 2 2 3 class TPRID Hash{3 class TPRID { 4 4 5 public static $ENCODER = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"; 6 private $hash; 5 private $id; 7 6 8 9 /** 10 * @rid = String 11 */ 12 function __construct($rid = null) { 13 $this->hash = $this->hashCode($rid); 7 function __construct($id = null) { 8 $this->id = $id; 14 9 } 15 10 16 /** 17 * @return RIDHash 18 */ 19 public static function parse($hashCode) { 20 $hash = new TPRIDHash(); 21 $hash->hash = $hashCode; 22 return $hash; 11 public function getID() { 12 return $this->id; 23 13 } 24 14 25 public function getHash(){ 26 return $this->hash; 15 public function __toString() { 16 return $this->id; 17 } 18 public function toString() { 19 return $this->id; 27 20 } 28 21 29 public function __toString(){ 30 return $this->hash; 31 } 32 public function toString(){ 33 return $this->hash; 34 } 35 36 private static function addNum($a, $b) { 37 $dif = 2147483647 - $b; 38 if($dif>$a){ return $a+$b;} 39 return -2147483648 + ($a-$dif) - 1; 40 } 41 42 private static function multBy31($num) { 43 $res = ($num<<5) & 0xFFFFFFFF; 44 if($res>=0) { 45 if($num>=0) return $res-$num; 46 $dif = 2147483647 + $num; 47 if($dif>$res) return $res-$num; 48 return -2147483648 + ($res-$dif) - 1; 49 } else { 50 if($num<=0) return $res-$num; 51 $dif = -2147483648 + $num; 52 if($dif<$res) return $res-$num; 53 return 2147483647 - ($dif-$res) + 1; 22 public static function parse($s) { 23 if(is_numeric($s)) { 24 return new TPRID("" . $s); 25 } else if(is_string($s)) { 26 return new TPRID($s); 27 }else if(is_a($s, 'TPRID')) { 28 return $s; 54 29 } 55 30 } 56 31 57 public static function hashCode($s) { 58 if ($s == null || strlen($s) == 0) return "0"; 59 60 $h1 = 0; 61 $chars = TPRIDHash::unistr_to_ords($s); 62 $h2 = count($chars) * 31; 63 64 for ($i = 0; $i < count($chars); $i++) { 65 $h1 = self::addNum(self::multBy31($h1), $chars[$i]); 66 67 $charAt = $chars[$i]; 68 $adnum = self::addNum($h2, $chars[$i]); 69 70 $mult = self::multBy31($adnum); 71 $h2 = self::addNum($h2, $mult); 72 } 73 74 $bld = ""; 75 $bld.=(self::$ENCODER{($h1) & (0xF)}); 76 $bld.=(self::$ENCODER{($h1>>4) & (0x3F)}); 77 $bld.=(self::$ENCODER{($h1>>10) & (0x3F)}); 78 $bld.=(self::$ENCODER{($h1>>16) & (0x3F)}); 79 $bld.=(self::$ENCODER{($h1>>22) & (0x3F)}); 80 81 $bld.=(self::$ENCODER{((($h1>>28) & 0xF) | ($h2<<4)) & (0x3F)}); 82 83 $bld.=(self::$ENCODER{($h2=($h2>>2)&1073741823) & (0x3F)}); 32 } 84 33 85 34 86 while(($h2>>=6)!=0)87 $bld.=(self::$ENCODER{($h2 & (0x3F))});88 89 $leadzeros = -1;90 while(++$leadzeros<strlen($bld)){91 if($bld{$leadzeros}!='0') break;92 }93 94 return substr($bld, $leadzeros);95 }96 97 static function unistr_to_ords($str, $encoding = 'UTF-8') {98 // Turns a string of unicode characters into an array of ordinal values,99 // Even if some of those characters are multibyte.100 $str = mb_convert_encoding($str,"UCS-4BE",$encoding);101 $ords = array();102 103 // Visit each unicode character104 for($i = 0; $i < mb_strlen($str,"UCS-4BE"); $i++) {105 // Now we have 4 bytes. Find their total106 // numeric value.107 $s2 = mb_substr($str,$i,1,"UCS-4BE");108 $val = unpack("N",$s2);109 $ords[] = $val[1];110 }111 return($ords);112 }113 114 115 }116 117 35 ?> -
tinypass/branches/silver_bullet/api/TinyPass.php
r461624 r593084 4 4 require_once "policies/Policies.php"; 5 5 require_once "TPRIDHash.php"; 6 require_once "TinyPassGateway.php"; 6 7 require_once "TPResource.php"; 7 8 require_once "TPOffer.php"; 8 9 require_once "TinyPassException.php"; 9 require_once "TPVersion.php";10 10 require_once "TPPriceOption.php"; 11 require_once " ui/TPTicket.php";12 require_once "ui/TP WebWidget.php";13 require_once "ui/TP WebRequest.php";11 require_once "TPUtils.php"; 12 require_once "ui/TPPurchaseRequest.php"; 13 require_once "ui/TPHtmlWidget.php"; 14 14 require_once "TPClientMsgBuilder.php"; 15 15 require_once "builder/TPClientBuilder.php"; 16 16 require_once "builder/TPClientParser.php"; 17 require_once "builder/TPCookieParser.php"; 17 18 require_once "builder/TPSecureEncoder.php"; 18 19 require_once "builder/TPOpenEncoder.php"; 19 20 require_once "builder/TPJsonMsgBuilder.php"; 20 21 require_once "builder/TPSecurityUtils.php"; 21 require_once "token/TPTokenWrapper.php"; 22 require_once "token/TPMeterDetails.php"; 22 require_once "token/TPAccessTokenStore.php"; 23 require_once "token/TPMeterStore.php"; 24 require_once "token/TPMeter.php"; 23 25 require_once "token/TPAccessToken.php"; 24 26 require_once "token/TPAccessTokenList.php"; 25 require_once "token/TPToken .php";27 require_once "token/TPTokenData.php"; 26 28 27 29 28 30 class TinyPass { 29 31 30 public static $API_ PREPARE = "/jsapi/prepare.js";31 public static $API_ DATA = "/jsapi/data";32 public static $API_ AUTH = "/jsapi/auth.js";32 public static $API_ENDPOINT_PROD = "https://api.tinypass.com"; 33 public static $API_ENDPOINT_SANDBOX = "https://sandbox.tinypass.com"; 34 public static $API_ENDPOINT_DEV = ""; 33 35 34 p rotected $accessTokenList;35 p rotected $localAccessTokenList;36 p rotected $localBindList;36 public static $AID = ""; 37 public static $PRIVATE_KEY = ""; 38 public static $SANDBOX = false; 37 39 38 protected $aid; 39 protected $privateKey; 40 protected $apiEndpoint; 41 protected $msgbuilder; 40 public static $CONNECTION_TIMEOUT = 5000; 41 public static $READ_TIMEOUT = 10000; 42 42 43 private $clientIP; 44 private $lastState; 45 46 private $webRequest; 47 48 static $LOCAL_COOKIE_SUFFIX = "_TR"; 49 static $COOKIE_SUFFIX = "_TOKEN"; 50 static $COOKIE_PREFIX = "__TP_"; 51 52 public function __construct($apiEndpoint, $aid, $privateKey) { 53 $this->apiEndpoint = $apiEndpoint; 54 $this->aid = $aid; 55 $this->privateKey = $privateKey; 56 $this->localBindList = new TPAccessTokenList(); 57 58 $this->msgbuilder = new TPClientMsgBuilder($privateKey); 59 $this->setClientCookies($_COOKIE); 60 61 if($this->localAccessTokenList == null) 62 $this->localAccessTokenList = new TPAccessTokenList(); 63 64 if($this->accessTokenList == null) 65 $this->accessTokenList = new TPAccessTokenList(); 43 public static function config($aid = null, $privateKey = null, $sandbox = null) { 44 if($aid) 45 return new TPConfig($aid, $privateKey, $sandbox); 46 return new TPConfig(self::$AID, self::$PRIVATE_KEY, self::$SANDBOX); 66 47 } 67 48 68 public function setClientCookies(array $cookies) { 69 if(count($cookies) == 0) 70 return; 71 72 try { 73 $this->accessTokenList = $this->msgbuilder->parseAccessTokenList($this->aid, $cookies); 74 $this->accessTokenList->setAID($this->aid); 75 } catch (Exception $e) { 76 } 77 try { 78 $this->localAccessTokenList = $this->msgbuilder->parseLocalTokenList($this->aid, $cookies); 79 $this->localAccessTokenList->setAID($this->aid); 80 } catch (Exception $e) { 81 $this->localAccessTokenList = new TPAccessTokenList(); 82 $this->localAccessTokenList->setAID($this->aid); 83 } 84 $this->_cleanLocalTokens(); 85 49 public static function fetchAccessDetails($params, $page = 0, $pagesize = 500) { 50 return TinyPassGateway::fetchAccessDetails($params); 86 51 } 87 52 88 89 private function isAccessGrantedForRID($rid) { 90 $this->lastState = TPAccessState::ACCESS_GRANTED; 91 92 if ($this->accessTokenList == null) { 93 $this->lastState = TPAccessState::NO_TOKENS_FOUND; 94 return false; 95 } 96 97 if ($this->accessTokenList->hasIPs() && $this->isClientIPValid() && $this->accessTokenList->containsIP($this->clientIP) == false) { 98 $this->lastState = TPAccessState::CLIENT_IP_DOES_NOT_MATCH_TOKEN; 99 return false; 100 } 101 102 if ($this->accessTokenList->isAccessGranted($rid)) { 103 return true; 104 } else { 105 $this->lastState = $this->accessTokenList->getLastError(); 106 return false; 107 } 108 53 public static function fetchAccessDetail($params) { 54 return TinyPassGateway::fetchAccessDetail($params); 109 55 } 110 56 111 public function isAccessGranted($obj) { 112 if(is_string($obj)) { 113 return $this->isAccessGrantedForRID($obj); 114 } 115 116 if($obj instanceof TPResource) { 117 return $this->isAccessGrantedForRID($obj->getRID()); 118 } 119 120 if($obj instanceof TPOffer) { 121 $granted = $this->isAccessGrantedForRID($obj->getResource()->getRID()); 122 123 if ($granted) { 124 return true; 125 } else { 126 if ($obj->getPricing()->hasActiveOptions() == false) { 127 $this->lastState = TPAccessState::NO_ACTIVE_PRICES; 128 return true; 129 } 130 } 131 return false; 132 133 } 134 57 public static function revokeAccess($params) { 58 return TinyPassGateway::revokeAccess($params); 135 59 } 136 60 137 138 public function getMeterDetails($offer) { 139 $resource = $offer->getResource(); 140 $meterDetails = null; 141 142 /* 143 Check for token in both places. Because MeteredB from from the server we must check both places. 144 */ 145 if ($this->accessTokenList != null 146 && $this->accessTokenList->getToken($resource->getRID()) != null 147 && TPMeterDetails::is($this->accessTokenList->getToken($resource->getRID()))) { 148 $token = $this->accessTokenList->getToken($resource->getRID()); 149 $meterDetails = TPMeterDetails::createWithToken($token); 150 151 } else if ($this->localAccessTokenList == null || $this->localAccessTokenList->getToken($resource->getRID()) == null) { 152 153 $meterDetails = TPMeterDetails::createWithValues($resource->getRIDHash(), $offer->getMeteredPolicy()->toMap()); 154 $this->localBindList->add($resource->getRIDHash(), $meterDetails->getToken()); 155 156 } else { 157 158 $token = $this->localAccessTokenList->getToken($resource->getRID()); 159 $meterDetails = TPMeterDetails::createWithToken($token); 160 $this->localBindList->add($resource->getRIDHash(), $token); 161 } 162 try { 163 $meterDetails->touch(); 164 } catch (Exception $tokenUnparseable) { 165 //tokenUnparseable.printStackTrace(); 166 } 167 168 return $meterDetails; 61 public static function cancelSubscription($params) { 62 return TinyPassGateway::cancelSubscription($params); 169 63 } 170 64 171 public function __generateLocalCookie() { 65 } 172 66 67 class TPConfig { 173 68 174 foreach($this->localBindList->getTokens() as $key => $token) { 175 $this->localAccessTokenList->add($key, $token); 176 } 69 public static $VERSION = "2.0"; 70 public static $MSG_VERSION = "2.0p"; 177 71 178 if ($this->localAccessTokenList->size() > 0)179 return self::getAppPrefix($this->getAID()) . TinyPass::$LOCAL_COOKIE_SUFFIX . "=" . urlencode($this->getMsgbuilder()->buildAccessTokenList($this->getLocalAccessTokenList()));72 public static $CONTEXT = "/v2"; 73 public static $REST_CONTEXT = "/r2"; 180 74 181 return ""; 75 public static $COOKIE_SUFFIX = "_TOKEN"; 76 public static $COOKIE_PREFIX = "__TP_"; 77 78 public $AID; 79 public $PRIVATE_KEY; 80 public $SANDBOX; 81 82 public function __construct($aid, $privateKey, $sandbox) { 83 $this->AID = $aid; 84 $this->PRIVATE_KEY = $privateKey; 85 $this->SANDBOX = $sandbox; 182 86 } 183 87 184 public function __hasLocalTokenChanges() { 185 return $this->localBindList->isEmpty() == false; 186 } 187 188 private function _cleanLocalTokens() { 189 $tokens = $this->localAccessTokenList->getTokens(); 190 191 foreach($tokens as $rid => $token) { 192 193 if(TPMeterDetails::is($token)) { 194 $meterDetails = new TPMeterDetails($token); 195 if ($meterDetails->isDead()) 196 $this->localAccessTokenList->remove($rid); 197 198 } else { 199 $accessToken = new TPAccessToken($token); 200 if($accessToken->isExpired()) 201 $this->localAccessTokenList->remove($rid); 202 } 203 88 public function getEndPoint() { 89 if(TinyPass::$API_ENDPOINT_DEV != null && strlen(TinyPass::$API_ENDPOINT_DEV)>0) { 90 return TinyPass::$API_ENDPOINT_DEV; 91 } else if(TinyPass::$SANDBOX) { 92 return TinyPass::$API_ENDPOINT_SANDBOX; 93 } else { 94 return TinyPass::$API_ENDPOINT_PROD; 204 95 } 205 96 } 206 97 207 public function isClientIPValid() { 208 return $this->clientIP && preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}/", $this->clientIP); 209 } 210 211 public function getAID() { 212 return $this->aid; 213 } 214 215 protected function getPrivateKey() { 216 return $this->privateKey; 98 public static function getTokenCookieName($aid) { 99 return self::$COOKIE_PREFIX . $aid . self::$COOKIE_SUFFIX; 217 100 } 218 101 … … 221 104 } 222 105 223 public function getApiEndPoint() {224 return $this->apiEndpoint;225 }226 227 public function getMsgBuilder() {228 return $this->msgbuilder;229 }230 231 public function getAccessTokenList() {232 return $this->accessTokenList;233 }234 235 public function getWebRequest() {236 if(!isset($this->webRequest))237 $this->webRequest = new TPWebRequest($this);238 return $this->webRequest;239 }240 241 public function setClientIP($s) {242 $this->clientIP = $s;243 }244 245 public function getLocalAccessTokenList() {246 return $this->localAccessTokenList;247 }248 249 public function __getLocalBindingList() {250 return $this->localBindList;251 }252 253 public function getClientIP() {254 return $this->clientIP;255 }256 257 public function getAccessError() {258 return $this->lastState;259 }260 261 106 } 262 107 263 264 class TPAccessState {265 266 const ACCESS_GRANTED = 100;267 const CLIENT_IP_DOES_NOT_MATCH_TOKEN = 200;268 const RID_NOT_FOUND = 201;269 const NO_TOKENS_FOUND = 202;270 const METERED_TOKEN_ALWAYS_DENIED = 203;271 const EXPIRED = 204;272 const NO_ACTIVE_PRICES = 205;273 274 }275 108 ?> -
tinypass/branches/silver_bullet/api/TinyPassException.php
r461567 r593084 3 3 class TinyPassException extends Exception { 4 4 5 public function __construct($message) { 5 public $code = 0; 6 7 public function __construct($message, $code = 0) { 6 8 parent::__construct($message); 9 $this->code = 0; 7 10 } 11 8 12 9 13 } -
tinypass/branches/silver_bullet/api/builder/TPClientBuilder.php
r461624 r593084 8 8 const ENCODING_OPEN = 'o'; 9 9 10 const STD_ENC = "{jax}"; 11 const ZIP_ENC = "{jzx}"; 12 const OPEN_ENC = "{jox}"; 13 10 14 private $builder; 11 15 private $encoder; … … 15 19 private $mask = ""; 16 20 17 function __construct($ privateKey, $settings = null) {18 $this->privateKey = $privateKey;21 function __construct($settings = null) { 22 $this->privateKey = TinyPass::$PRIVATE_KEY; 19 23 $this->mask.=("{"); 20 24 switch ($settings!=null && strlen($settings)>1 ? $settings{1} : self::TYPE_JSON) { … … 38 42 } 39 43 40 public function buildAccessTokenList(TPAccessTokenList $accesstokenlist) { 41 return $this->mask . $this->encoder->encode($this->builder->buildAccessTokenList($accesstokenlist)); 44 /** 45 * 46 * @param <type> $tokens - can be a TPAccessTokne or TPAccessTokenList 47 * @return <type> 48 */ 49 public function buildAccessTokens($tokens) { 50 51 if($tokens instanceof TPAccessToken) { 52 // $tokens = array($tokens); 53 $tokens = new TPAccessTokenList(array($tokens)); 54 } 55 56 return $this->mask . $this->encoder->encode($this->builder->buildAccessTokens($tokens)); 42 57 } 43 58 44 public function build TicketRequest($tickets) {59 public function buildPurchaseRequest($tickets) { 45 60 46 if($tickets instanceof TP Ticket) {61 if($tickets instanceof TPPurchaseRequest) { 47 62 $tickets = array($tickets); 48 63 } 49 64 50 return $this->mask . $this->encoder->encode($this->builder->build TicketRequest($tickets));65 return $this->mask . $this->encoder->encode($this->builder->buildPurchaseRequest($tickets)); 51 66 } 52 67 -
tinypass/branches/silver_bullet/api/builder/TPClientParser.php
r461566 r593084 3 3 class TPClientParser { 4 4 5 private $privateKey; 6 private $builder; 5 private $parser; 7 6 private $encoder; 8 7 9 function __construct($privateKey) { 10 $this->privateKey = $privateKey; 8 const DATA_BLOCK_START_SIGNATURE = '/[{]\w\w\w[}]/'; 9 private $config; 10 11 function __construct() { 12 $this->config = TinyPass::config(); 11 13 } 12 14 13 private function checkSettings($str) { 15 public function parseAccessTokens($message) { 16 $tokens = array(); 17 $blocks = $this->splitMessageString($message); 18 foreach($blocks as $block) { 19 $s = $this->setupImpls($block); 20 $list = $this->parser->parseAccessTokens($this->encoder->decode($s)); 21 $tokens = array_merge($tokens, $list->getTokens()); 22 } 23 return new TPAccessTokenList($tokens); 24 } 14 25 15 switch ($str!=null && strlen($str)>1 ? $str{1} : TPClientBuilder::TYPE_JSON) { 26 function splitMessageString($message) { 27 $list = array(); 28 $start = -1; 29 30 $matches = array(); 31 preg_match_all(TPClientParser::DATA_BLOCK_START_SIGNATURE, $message, $matches, PREG_OFFSET_CAPTURE); 32 33 if(count($matches) == 0) 34 return $list; 35 36 $matches = $matches[0]; 37 38 39 foreach($matches as $match) { 40 if($start >= 0) { 41 $list[] = trim(substr($message, $start, ($match[1]-$start))); 42 } 43 $start = $match[1]; 44 } 45 46 if($start >= 0) { 47 $list[] = trim(substr($message, $start)); 48 } 49 50 return $list; 51 } 52 53 54 private function setupImpls($str) { 55 56 if(!$str) 57 $str = TPClientBuilder::STD_ENC; 58 59 switch (strlen($str)>1 ? $str{1} : TPClientBuilder::TYPE_JSON) { 16 60 17 61 case TPClientBuilder::TYPE_JSON: 18 62 default: 19 $this-> builder = new TPJsonMsgBuilder();63 $this->parser = new TPJsonMsgBuilder(); 20 64 21 65 } 22 switch ( $str!=null &&strlen($str)>2 ? $str{2} : TPClientBuilder::ENCODING_AES) {66 switch (strlen($str)>2 ? $str{2} : TPClientBuilder::ENCODING_AES) { 23 67 24 68 case TPClientBuilder::ENCODING_OPEN: … … 28 72 case TPClientBuilder::ENCODING_AES: 29 73 default: 30 $this->encoder = new TPSecureEncoder($this-> privateKey);74 $this->encoder = new TPSecureEncoder($this->config->PRIVATE_KEY); 31 75 } 32 76 return preg_replace('/^{...}/','', $str); 33 77 } 34 78 35 public function parseAccessTokenList($message) { 36 $s = $this->checkSettings($message); 37 return $this->builder->parseAccessTokenList($this->encoder->decode($s)); 38 } 79 39 80 40 81 } -
tinypass/branches/silver_bullet/api/builder/TPJsonMsgBuilder.php
r461624 r593084 3 3 class TPJsonMsgBuilder { 4 4 5 public function buildTicketRequest(array $tickets) { 5 public function parseAccessTokens($raw) { 6 7 if($raw == null || $raw == "") return null; 8 9 $json = (array)json_decode($raw); 10 $accessTokenList = array(); 11 12 if(!is_array($json)) { 13 $tokenMap = $json; 14 $ridHash = TPRIDHash::parse($tokenMap[TPTokenData::RID]); 15 $token = $this->parseAccessToken($ridHash, $tokenMap); 16 $accessToken = new TPAccessToken($token); 17 $accessTokenList[] = $accessToken; 18 }else { 19 foreach($json as $tokenMap) { 20 $tokenMap = (array)$tokenMap; 21 $rid = TPRID::parse($tokenMap[TPTokenData::RID]); 22 $token = $this->parseAccessToken($rid->toString(), $tokenMap); 23 $accessToken = new TPAccessToken($token); 24 $accessTokenList[] = $accessToken; 25 } 26 } 27 28 return new TPAccessTokenList($accessTokenList); 29 } 30 31 private function parseAccessToken($rid, $map) { 32 33 $token = new TPTokenData($rid); 34 35 $fields = array( 36 TPTokenData::ACCESS_ID, 37 TPTokenData::EX, 38 TPTokenData::IPS, 39 TPTokenData::UID, 40 TPTokenData::EARLY_EX, 41 TPTokenData::METER_TRIAL_ENDTIME, 42 TPTokenData::METER_LOCKOUT_PERIOD, 43 TPTokenData::METER_LOCKOUT_ENDTIME, 44 TPTokenData::METER_TRIAL_ACCESS_ATTEMPTS, 45 TPTokenData::METER_TRIAL_MAX_ACCESS_ATTEMPTS, 46 TPTokenData::METER_TYPE, 47 ); 48 49 50 foreach($fields as $f) { 51 if(isset($map[$f])) 52 $token->addField($f, $map[$f]); 53 } 54 55 56 return $token; 57 } 58 59 60 61 public function buildPurchaseRequest(array $requestData) { 6 62 $list = array(); 7 63 8 foreach($ tickets as $ticket) {9 $list[] = $this->build Ticket($ticket);64 foreach($requestData as $request) { 65 $list[] = $this->buildRequest($request); 10 66 } 11 67 … … 13 69 } 14 70 15 public function build Ticket(TPTicket $ticket) {71 public function buildRequest(TPPurchaseRequest $request) { 16 72 17 73 $ticketMap = array(); 18 74 19 $ticketMap["o1"] = $this->buildOffer($ticket->getPrimaryOffer()); 20 $ticketMap["t"] = $ticket->getTimestampSecs(); 21 $ticketMap["tags"] = $ticket->getTags(); 22 $ticketMap["v"] = $ticket->getVersion(); 23 $ticketMap["ip"] = $ticket->getClientIP(); 75 $ticketMap["o1"] = $this->buildOffer($request->getPrimaryOffer()); 76 $ticketMap["t"] = TPUtils::now(); 77 $ticketMap["v"] = TPConfig::$MSG_VERSION; 78 $ticketMap["cb"] = $request->getCallback(); 24 79 80 if($request->getClientIP()) 81 $ticketMap["ip"] = $request->getClientIP(); 25 82 26 if ($ticket->getOptions() != null && count($ticket->getOptions()) > 0)27 $ticketMap[" opts"] = $ticket->getOptions();83 if($request->getUserRef() != null) 84 $ticketMap["uref"] = $request->getUserRef(); 28 85 29 if ($ticket->getSecondaryOffer() != null) { 30 $ticketMap["o2"] = $this->buildOffer($ticket->getSecondaryOffer()); 86 if ($request->getOptions() != null && count($request->getOptions()) > 0) 87 $ticketMap["opts"] = $request->getOptions(); 88 89 if ($request->getSecondaryOffer() != null) { 90 $ticketMap["o2"] = $this->buildOffer($request->getSecondaryOffer()); 31 91 } 32 92 33 93 34 94 return $ticketMap; 35 36 // $ticketMap["rid"] = $ticket->getResource()->getRID();37 // $ticketMap["rnm"] = $ticket->getResource()->getResourceName();38 // $ticketMap["t"] = $ticket->getTimestamp()*1000;39 // $ticketMap["tags"] = $ticket->getTags();40 41 // $pos = array();42 // for ($i = 0; $i < count($ticket->getPriceOptions()); $i++) {43 // $options = $ticket->getPriceOptions();44 // $pos["opt" . $i] = $this->buildPriceOption($options[$i], $i);45 // }46 // $ticketMap["pos"] = $pos;47 95 48 96 } … … 55 103 $map["rurl"] = $offer->getResource()->getURL(); 56 104 57 if ($o ptions != null)58 $map[" opts"] = $options;105 if ($offer->getTags()) 106 $map["tags"] = $offer->getTags(); 59 107 60 108 $pos = array(); … … 75 123 } 76 124 77 public function buildAccessTokenList(TPAccessTokenList $list) { 78 $map = array(); 79 $map["aid"] = $list->getAID(); 80 $map["uid"] = $list->getUID(); 81 $map["built"] = time(); 82 $map["ips"] = $list->getIPs(); 83 84 125 public function buildAccessTokens(TPAccessTokenList $list) { 85 126 $tokens = array(); 86 127 87 foreach($list->getTokens() as $ rid => $token) {88 array_push($tokens, $token->getValues());128 foreach($list->getTokens() as $token) { 129 $tokens[] = $token->getTokenData()->getValues(); 89 130 } 131 return json_encode($tokens); 132 } 90 133 91 $map["tokens"] = $tokens;92 return json_encode($ map);134 public function buildAccessToken($accessToken) { 135 return json_encode($accessToken->getTokenData()->getValues()); 93 136 } 94 137 … … 108 151 $map["ed"] = $this->nuller($po->getEndDateInSecs()); 109 152 153 if ($po->isRecurring()) { 154 $map["recur"] = "true"; 155 } 110 156 111 157 $map["cpt"] = $this->nuller($po->getCaption()); … … 121 167 } 122 168 123 public function parseAccessTokenList($raw) {124 $json = (array)json_decode($raw);125 $tokenList = new TPAccessTokenList();126 127 $tokenList->setAID($json["aid"]);128 $tokenList->setUID($json["uid"]);129 $tokenList->setBuildTime($json["built"]);130 131 $ips = array();132 if(isset($json["ips"]))133 $ips = $json["ips"];134 $tokenList->setIPs($ips);135 136 $list = (array)$json["tokens"];137 for ($i = 0; $i < count($list); $i++) {138 $map = (array)$list[$i];139 140 141 if(!isset($map[TPToken::RID]))142 $ridHash = TPRIDHash::parse("");143 else144 $ridHash = TPRIDHash::parse($map["rid"]);145 146 $token = new TPToken($ridHash);147 148 149 $fields = array(150 TPToken::EX,151 TPToken::EARLY_EX,152 TPToken::METER_TRIAL_ENDTIME,153 TPToken::METER_LOCKOUT_PERIOD,154 TPToken::METER_LOCKOUT_ENDTIME,155 TPToken::METER_TRIAL_ACCESS_ATTEMPTS,156 TPToken::METER_TRIAL_MAX_ACCESS_ATTEMPTS,157 TPToken::METER_TYPE,158 );159 160 161 foreach($fields as $f) {162 if(isset($map[$f]))163 $token->addField($f, $map[$f]);164 }165 166 $tokenList->add($ridHash, $token);167 }168 169 return $tokenList;170 }171 172 173 169 } 174 170 -
tinypass/branches/silver_bullet/api/builder/TPSecurityUtils.php
r461566 r593084 2 2 3 3 class TPSecurityUtils { 4 5 //private static $LONG_MAX = "9223372036854775807";6 //private static $LONG_MIN = "-9223372036854775808";7 4 8 5 public static function hashCode($s) { … … 121 118 return $string; 122 119 } 120 121 public static function hashHmacSha1($key, $value) { 122 return self::urlensafe(hash_hmac('sha1', $value, $key, true)); 123 } 124 125 public static function hashHmacSha256($key, $value) { 126 return self::urlensafe(hash_hmac('sha256', $value, $key, true)); 127 } 128 129 public static function hashHmacSha($key, $value) { 130 if(in_array('sha256', hash_algos())) 131 return self::hashHmacSha256($key, $value); 132 else if(in_array('sha1', hash_algos())) 133 return self::hashHmacSha1($key, $value); 134 else 135 throw new Exception("Could not load hashing algorithm sha1/sha256"); 136 137 } 138 123 139 } 124 140 -
tinypass/branches/silver_bullet/api/policies/Policies.php
r541448 r593084 16 16 } 17 17 18 class TPMeteredPolicyImpl extends TPPolicy { 19 20 } 21 class TPReminderMeteredPricing extends TPMeteredPolicyImpl { 18 class TPReminderMeteredPricing extends TPPolicy { 22 19 23 20 public static function createByAccessCount($trialCount, $lockoutPeriod) { … … 25 22 $meter = new TPReminderMeteredPricing(); 26 23 27 $meter->set(TPToken ::METER_LOCKOUT_PERIOD, $lockoutPeriod);24 $meter->set(TPTokenData::METER_LOCKOUT_PERIOD, $lockoutPeriod); 28 25 $meter->set(TPPolicy::POLICY_TYPE, TPPolicy::REMINDER_METER_BY_COUNT); 29 $meter->set(TPToken ::METER_TYPE, TPMeterDetails::REMINDER);30 $meter->set(TPToken ::METER_TRIAL_MAX_ACCESS_ATTEMPTS, $trialCount);31 $meter->set(TPToken ::METER_TRIAL_ACCESS_ATTEMPTS, 0);26 $meter->set(TPTokenData::METER_TYPE, TPTokenData::METER_REMINDER); 27 $meter->set(TPTokenData::METER_TRIAL_MAX_ACCESS_ATTEMPTS, $trialCount); 28 $meter->set(TPTokenData::METER_TRIAL_ACCESS_ATTEMPTS, 0); 32 29 return $meter; 33 30 … … 38 35 $meter = new TPReminderMeteredPricing(); 39 36 40 $meter->set(TPToken ::METER_TRIAL_ACCESS_PERIOD, $trialPeriod);41 $meter->set(TPToken ::METER_LOCKOUT_PERIOD, $lockoutPeriod);42 $meter->set(TPToken ::METER_TYPE, TPMeterDetails::REMINDER);37 $meter->set(TPTokenData::METER_TRIAL_ACCESS_PERIOD, $trialPeriod); 38 $meter->set(TPTokenData::METER_LOCKOUT_PERIOD, $lockoutPeriod); 39 $meter->set(TPTokenData::METER_TYPE, TPTokenData::METER_REMINDER); 43 40 $meter->set(TPPolicy::POLICY_TYPE, TPPolicy::REMINDER_METER_BY_TIME); 44 41 45 $parsed = TP PriceOption::parseLoosePeriod($trialPeriod);46 $trialEndTime = (time()*1000) + $parsed;47 $meter->set(TPToken ::METER_TRIAL_ENDTIME, TPToken::convertToEpochSeconds($trialEndTime));48 $meter->set(TPToken ::METER_LOCKOUT_ENDTIME, TPToken::convertToEpochSeconds($trialEndTime + TPPriceOption::parseLoosePeriod($lockoutPeriod)));42 $parsed = TPUtils::parseLoosePeriodInSecs($trialPeriod); 43 $trialEndTime = time() + $parsed; 44 $meter->set(TPTokenData::METER_TRIAL_ENDTIME, TPTokenData::convertToEpochSeconds($trialEndTime)); 45 $meter->set(TPTokenData::METER_LOCKOUT_ENDTIME, TPTokenData::convertToEpochSeconds($trialEndTime + TPUtils::parseLoosePeriodInSecs($lockoutPeriod))); 49 46 return $meter; 50 47 } … … 54 51 * Metered Pricing 55 52 */ 56 class TPStrictMeteredPricing extends TP MeteredPolicyImpl{53 class TPStrictMeteredPricing extends TPPolicy { 57 54 58 55 public static function createByPeriod($trialPeriod, $lockoutPeriod) { 59 56 $meter = new TPStrictMeteredPricing(); 60 $meter->set(TPToken ::METER_TRIAL_ACCESS_PERIOD, $trialPeriod);61 $meter->set(TPToken ::METER_LOCKOUT_PERIOD, $lockoutPeriod);62 $meter->set(TPToken ::METER_TYPE, TPMeterDetails::STRICT);57 $meter->set(TPTokenData::METER_TRIAL_ACCESS_PERIOD, $trialPeriod); 58 $meter->set(TPTokenData::METER_LOCKOUT_PERIOD, $lockoutPeriod); 59 $meter->set(TPTokenData::METER_TYPE, TPTokenData::METER_STRICT); 63 60 $meter->set(TPPolicy::POLICY_TYPE, TPPolicy::STRICT_METER_BY_TIME); 64 61 return $meter; … … 96 93 $r->set(TPPolicy::POLICY_TYPE, TPPolicy::RESTRICT_MAX_PURCHASES); 97 94 $r->set("amount", $maxAmount); 98 $r->set("with InPeriod", $withInPeriod);95 $r->set("withinPeriod", $withInPeriod); 99 96 if($linkWithDetails) 100 97 $r->set("linkWithDetails", $linkWithDetails); -
tinypass/branches/silver_bullet/api/policies/TPPolicy.php
r461567 r593084 27 27 class TPPricingPolicy { 28 28 29 public static function createBasic(array $priceOptions) { 29 public static function createBasic(array $priceOptions = null) { 30 if($priceOptions == null) 31 $priceOptions = array(); 30 32 return new TPBasicPricing($priceOptions); 31 33 } -
tinypass/branches/silver_bullet/api/token/TPAccessToken.php
r461567 r593084 10 10 * cURL with HTTPS support 11 11 */ 12 class TPAccessToken extends TPTokenWrapper { 12 class TPAccessToken { 13 14 private $token; 15 private $accessState; 13 16 14 17 public function __construct() { 15 parent::__construct();16 18 17 19 $numargs = func_num_args(); 18 19 if($numargs == 1 && func_get_arg(0) instanceof TPToken) { 20 $this->token = new TPTokenData(); 21 22 if($numargs == 1 && func_get_arg(0) instanceof TPTokenData) { 20 23 $this->token = func_get_arg(0); 21 24 return; 22 25 } 23 26 27 if($numargs == 1 && func_get_arg(0) instanceof TPRID) { 28 $rid = TPRID::parse(func_get_arg(0)); 29 $this->token->addField(TPTokenData::RID,$rid->toString()); 30 return; 31 } 32 24 33 if($numargs == 2) { 25 $rid hash = func_get_arg(0);34 $rid = TPRID::parse(func_get_arg(0)); 26 35 $expiration = func_get_arg(1); 27 $this->token->addField(TPToken ::RID,$ridhash->toString());28 $this->token->addField(TPToken ::EX, $expiration != null ? TPToken::convertToEpochSeconds($expiration) : 0);36 $this->token->addField(TPTokenData::RID,$rid->toString()); 37 $this->token->addField(TPTokenData::EX, $expiration != null ? TPTokenData::convertToEpochSeconds($expiration) : 0); 29 38 return; 30 39 } 31 40 32 41 if($numargs == 3) { 33 $rid hash = func_get_arg(0);42 $rid = TPRID::parse(func_get_arg(0)); 34 43 $expiration = func_get_arg(1); 35 44 $eex = func_get_arg(2); 36 $this->token->addField(TPToken::RID,$ridhash->toString()); 37 $this->token->addField(TPToken::EX, $expiration != null ? TPToken::convertToEpochSeconds($expiration) : 0); 38 $this->token->addField(TPToken::EARLY_EX, $eex != null ? TPToken::convertToEpochSeconds($eex) : 0); 39 return; 40 } 41 42 45 $this->token->addField(TPTokenData::RID,$rid->toString()); 46 $this->token->addField(TPTokenData::EX, $expiration != null ? TPTokenData::convertToEpochSeconds($expiration) : 0); 47 $this->token->addField(TPTokenData::EARLY_EX, $eex != null ? TPTokenData::convertToEpochSeconds($eex) : 0); 48 return; 49 } 50 51 52 } 53 54 public function getTokenData() { 55 return $this->token; 56 } 57 58 public function getAccessID() { 59 return $this->token->getField(TPTokenData::ACCESS_ID); 60 } 61 62 public function getRID() { 63 return new TPRID($this->token->getRID()); 43 64 } 44 65 45 66 public function getExpirationInMillis() { 46 return $this->getExpirationInSeconds() * 1000; 67 return $this->getExpirationInSecs() * 1000; 68 } 69 70 public function getExpirationInSecs() { 71 return $this->token->getFromMap(TPTokenData::EX, 0); 47 72 } 48 73 49 74 public function getExpirationInSeconds() { 50 return $this->token->getFromMap(TPToken::EX, 0); 51 } 52 53 public function getPreExpirationInSeconds() { 54 return $this->token->getFromMap(TPToken::EARLY_EX, 0); 55 } 75 return $this->token->getFromMap(TPTokenData::EX, 0); 76 } 77 78 public function getEarlyExpirationInSecs() { 79 return $this->token->getFromMap(TPTokenData::EARLY_EX, 0); 80 } 81 82 public function getEarlyExpirationInSeconds() { 83 return $this->token->getFromMap(TPTokenData::EARLY_EX, 0); 84 } 85 86 public function isMetered() { 87 return array_key_exists(TPTokenData::METER_TYPE, $this->token->getValues()); 88 } 89 90 public function getMeterType() { 91 return $this->token->getFromMap(TPTokenData::METER_TYPE, 0); 92 } 93 94 public function isTrialPeriodActive() { 95 96 if($this->isMetered()) { 97 98 if ($this->getMeterType() == TPTokenData::METER_STRICT) { 99 100 $expires = $this->getTrialEndTimeSecs(); 101 if ($expires == null || $expires == 0) 102 return false; 103 return time() <= $expires; 104 105 } else { 106 107 if ($this->isMeterViewBased()) { 108 return $this->getTrialViewCount() <= $this->getTrialViewLimit(); 109 } else { 110 $expires = $this->getTrialEndTimeSecs(); 111 if ($expires == null || $expires == 0) 112 return true; 113 return time() <= $expires; 114 } 115 116 } 117 } 118 return false; 119 } 120 121 public function isMeterViewBased() { 122 return $this->isMetered() && array_key_exists(TPTokenData::METER_TRIAL_MAX_ACCESS_ATTEMPTS, $this->token->getValues()); 123 } 124 125 public function isMeterPeriodBased() { 126 return $this->isMetered() && !$this->isMeterViewBased(); 127 } 128 129 public function isLockoutPeriodActive() { 130 if($this->isMetered()) { 131 $expires = $this->getLockoutEndTimeSecs(); 132 133 if ($this->isTrialPeriodActive()) 134 return false; 135 136 if ($expires == null || $expires == 0) 137 return false; 138 139 return time() <= $expires; 140 } 141 return false; 142 } 143 144 public function _isTrialDead() { 145 return $this->isLockoutPeriodActive() == false && $this->isTrialPeriodActive() == false; 146 } 147 148 public function getTrialEndTimeSecs() { 149 return $this->token->getFromMap(TPTokenData::METER_TRIAL_ENDTIME, 0); 150 } 151 152 public function getLockoutEndTimeSecs() { 153 return $this->token->getFromMap(TPTokenData::METER_LOCKOUT_ENDTIME, 0); 154 } 155 156 public function getTrialViewCount() { 157 return $this->token->getFromMap(TPTokenData::METER_TRIAL_ACCESS_ATTEMPTS, 0); 158 } 159 160 public function getTrialViewLimit() { 161 return $this->token->getFromMap(TPTokenData::METER_TRIAL_MAX_ACCESS_ATTEMPTS, 0); 162 } 163 164 public function getUID() { 165 return $this->token->getFromMap(TPTokenData::UID, 0); 166 } 167 168 /* 169 public function incrementViewCount() { 170 if ($this->getMeterType() != TPAccessToken::METER_STRICT && $this->isMeterViewBased()) { 171 if ($this->getTrialViewCount() == $this->getTrialViewLimit()) { 172 $this->token->addField( 173 TPTokenData::METER_LOCKOUT_ENDTIME, 174 time() + 175 (TPUtils::parseLoosePeriodInMsecs( $this->token->getField(TPTokenData::METER_LOCKOUT_PERIOD))/1000) 176 ); 177 } 178 } 179 $this->token->addField(TPTokenData::METER_TRIAL_ACCESS_ATTEMPTS, $this->getTrialViewCount() + 1); 180 } 181 */ 182 183 public function containsIP($currentIP) { 184 $list = $this->token->getFromMap(TPTokenData::IPS, null); 185 if($list == null) return false; 186 return in_array(TPUtils::shortenIP($currentIP), $this->token->getField(TPTokenData::IPS)); 187 } 188 189 public function hasIPs() { 190 if($this->token->getFromMap(TPTokenData::IPS, null) == null) return false; 191 return count($this->getIPs()) > 0; 192 } 193 194 public function getIPs() { 195 $list = $this->token->getFromMap(TPTokenData::IPS, null); 196 $res = array(); 197 if($list==null) return $res; 198 foreach($list as $ip) { 199 $res[] = TPUtils::unshortenIP($ip); 200 } 201 return $res; 202 } 203 56 204 57 205 /** … … 60 208 61 209 public function isExpired() { 62 $time = $this->get PreExpirationInSeconds();210 $time = $this->getEarlyExpirationInSeconds(); 63 211 64 212 if ($time == null || $time == 0) 65 $time = $this->getExpirationInSec onds();213 $time = $this->getExpirationInSecs(); 66 214 67 215 if ($time == null || $time == 0) … … 70 218 return $time <= time(); 71 219 } 72 220 public function isAccessGranted($clientIP = null) { 221 if($this->getExpirationInSecs() == -1) { 222 //special case. RID_NOT_FOUND 223 if($this->accessState!=TPAccessState::NO_TOKENS_FOUND) $this->accessState = TPAccessState::RID_NOT_FOUND; 224 return false; 225 } 226 227 if(TPUtils::isIpValid($clientIP) && $this->hasIPs() && !$this->containsIP($clientIP)) { 228 $this->accessState = TPAccessState::CLIENT_IP_DOES_NOT_MATCH_TOKEN; 229 return false; 230 } 231 232 if ($this->isMetered()) { 233 if ($this->isTrialPeriodActive()) { 234 $this->accessState = TPAccessState::METERED_IN_TRIAL; 235 return true; 236 } else if ($this->isLockoutPeriodActive()) { 237 $this->accessState = TPAccessState::METERED_IN_LOCKOUT; 238 return false; 239 } else { 240 $this->accessState = TPAccessState::METERED_TRIAL_DEAD; 241 return false; 242 } 243 } else if ($this->isExpired()) { 244 $this->accessState = TPAccessState::EXPIRED; 245 return false; 246 } else { 247 $this->accessState = TPAccessState::ACCESS_GRANTED; 248 return true; 249 } 250 } 251 252 253 //V2-CHANGE moved from TinyPass class 254 public function setAccessState($accessState) { 255 $this->accessState = $accessState; 256 } 257 public function getAccessState() { 258 if($this->accessState==null) $this->isAccessGranted(); 259 return $this->accessState; 260 } 261 262 263 264 265 266 267 } 268 269 270 class TPAccessState { 271 272 const ACCESS_GRANTED = 100; 273 const CLIENT_IP_DOES_NOT_MATCH_TOKEN = 200; 274 const RID_NOT_FOUND = 201; 275 const NO_TOKENS_FOUND = 202; 276 const METERED_IN_TRIAL = 203; 277 const EXPIRED = 204; 278 const NO_ACTIVE_PRICES = 205; 279 const METERED_IN_LOCKOUT = 206; 280 const METERED_TRIAL_DEAD = 207; 73 281 74 282 -
tinypass/branches/silver_bullet/api/token/TPAccessTokenList.php
r461567 r593084 4 4 5 5 public static $MAX = 20; 6 private $aid;7 private $uid;8 6 private $tokens = array(); 9 private $rawToken = "";10 private $buildTime = 0;11 private $ips = array();12 private $lastError = 0;13 7 14 8 15 function __construct($aid = null, $uid = null) { 16 $this->aid = $aid; 17 $this->uid = $uid; 9 function __construct(array $tokens = null) { 10 if($tokens) { 11 foreach($tokens as $token) { 12 $this->add($token, false); 13 } 14 } 15 18 16 } 19 17 20 public function getAID() { 21 return $this->aid; 22 } 23 24 public function getUID() { 25 return $this->uid; 18 public function getAccessTokens() { 19 return $this->tokens; 26 20 } 27 21 … … 30 24 } 31 25 32 function setAID($aid) { 33 $this->aid= $aid; 26 public function contains($rid) { 27 $rid = TPRID::parse($rid); 28 return array_key_exists($rid->toString(), $this->tokens); 34 29 } 35 30 36 function setUID($uid) { 37 $this->uid = $uid; 31 public function remove($rid) { 32 $rid = TPRID::parse($rid); 33 unset($this->tokens[$rid->toString()]); 38 34 } 39 35 40 public function contains($rid) { 41 $ridHash = TPRIDHash::hashCode($rid); 42 return array_key_exists($ridHash, $this->tokens); 36 public function add(TPAccessToken $token, $checkLimit = true) { 37 if ($checkLimit && count($this->tokens) >= TPAccessTokenList::$MAX) { 38 array_pop($this->tokens); 39 } 40 $this->tokens[$token->getRID()->getID()] = $token; 43 41 } 44 42 45 /* 46 public function addResourceByHash($ridHash, $expiration) { 47 $this->add($ridHash, new TPAccessToken($ridHash, $expiration)); 43 public function addAll($tokens) { 44 foreach($tokens as $token) { 45 $this->add($token); 46 } 48 47 } 49 48 50 public function addResource($rid, $expiration) {51 $ridHash = TPRIDHash::hashCode($rid);52 $this->add($ridHash, new TPAccessToken($ridHash, $expiration));53 }54 */55 public function remove($key) {56 unset($this->tokens[$key]);57 }58 59 public function add($ridHash, $token) {60 if (count($this->tokens) >= TPAccessTokenList::$MAX) {61 array_pop($this->tokens);62 }63 if($ridHash instanceof TPRIDHash)64 $this->tokens[$ridHash->getHash()] = $token;65 else {66 $hash = TPRIDHash::hashCode($ridHash);67 $this->tokens[$hash] = $token;68 }69 70 }71 72 public function isAccessGranted($rid) {73 $this->lastError = TPAccessState::ACCESS_GRANTED;74 $hash = TPRIDHash::hashCode($rid);75 76 if (array_key_exists($hash, $this->tokens)) {77 $token = $this->tokens[$hash];78 if (TPMeterDetails::is($token) == false) {79 $accessToken = new TPAccessToken($token);80 $expired = $accessToken->isExpired();81 if ($expired) {82 $this->lastError = TPAccessState::EXPIRED;83 return false;84 }85 return true;86 } else {87 $this->lastError = TPAccessState::METERED_TOKEN_ALWAYS_DENIED;88 return false;89 }90 }91 $this->lastError = TPAccessState::RID_NOT_FOUND;92 return false;93 }94 95 public function setRawToken($rawToken) {96 $this->rawToken = $rawToken;97 }98 99 public function getRawToken() {100 return $this->rawToken;101 }102 49 103 50 /** … … 105 52 * @param <String> $rid String RID 106 53 */ 107 public function get Token($rid) {108 $ hash = TPRIDHash::hashCode($rid);109 if (array_key_exists($hash, $this->tokens)) {110 return $this->tokens[$ hash];54 public function getAccessTokenByRID($rid) { 55 $rid = TPRID::parse($rid); 56 if($this->contains($rid)) { 57 return $this->tokens[$rid->getID()]; 111 58 } 112 59 return null; 113 60 } 114 61 115 public function setBuildTime($time) {116 $this->buildTime = $time;117 }118 62 119 63 public function isEmpty() { … … 125 69 } 126 70 127 public function containsIP($currentIP) { 128 return in_array($currentIP, $this->ips); 71 public function testGetAID() { 72 $list = new TPAccessToken(new TPTokenData()); 73 $this->assertEquals("AID", $list->getAID()); 129 74 } 130 75 131 public function addIP($ip) { 132 $this->ips[] = $ip; 133 return $this; 134 } 135 136 public function getIPs() { 137 return $this->ips; 138 } 139 140 public function hasIPs() { 141 return $this->ips != null && count($this->ips) > 0; 142 } 143 144 public function setIPs($list) { 145 $this->ips = $list; 146 } 147 148 public function getLastError() { 149 return $this->lastError; 76 public function testGetUID() { 77 $list = new TPAccessToken("AID", "UID"); 78 $this->assertEquals("UID", $list->getUID()); 150 79 } 151 80
Note: See TracChangeset
for help on using the changeset viewer.