Plugin Directory

Changeset 593084


Ignore:
Timestamp:
08/31/2012 06:08:13 PM (14 years ago)
Author:
wordpress@…
Message:

moved over version2.0 api

Location:
tinypass/branches/silver_bullet/api
Files:
12 added
9 deleted
14 edited

Legend:

Unmodified
Added
Removed
  • tinypass/branches/silver_bullet/api/TPClientMsgBuilder.php

    r461624 r593084  
    1919    }
    2020
    21     public function buildTicketRequest($tickets) {
    22         return $this->builder->buildTicketRequest($tickets);
     21    public function buildPurchaseRequest($tickets) {
     22        return $this->builder->buildPurchaseRequest($tickets);
    2323    }
    2424
  • tinypass/branches/silver_bullet/api/TPOffer.php

    r461567 r593084  
    77    private $pricing;
    88    private $policies = array();
     9    private $tags = array();
    910
    1011    public function __construct(TPResource $resource, $priceOptions) {
    1112        $this->resource = $resource;
    1213
    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   
    1722    }
    1823
     
    2530    }
    2631
    27     public function isMetered() {
    28         foreach ($this->policies as $policy) {
    29             if ($policy instanceof TPMeteredPolicyImpl)
    30                 return true;
    31         }
    32         return false;
    33     }
    34 
    3532    public function addPolicy($policy) {
    3633        $this->policies[] = $policy;
     
    4037    public function getPolicies() {
    4138        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();
    5039    }
    5140
     
    6049        }
    6150    }
     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
    6270}
    6371?>
  • tinypass/branches/silver_bullet/api/TPPriceOption.php

    r461567 r593084  
    88    protected $price;
    99    protected $accessPeriod;
    10     protected $initAccessPeriod;
    1110    protected $startDateInSecs;
    1211    protected $endDateInSecs;
    1312    protected $caption;
     13    protected $trialPeriod;
     14    protected $recurring = false;
    1415
    1516    protected $splitPay = array();
    1617
    17     private static $EXPIRE_PARSER = '/(\d+)\s*(\w+)/';
    1818
    1919    public function __construct($price = null, $acessPeriod = null, $startDateInSecs = null, $endDateInSecs = null) {
     
    2121        $this->accessPeriod = $acessPeriod;
    2222        if($startDateInSecs)
    23             $this->startDateInSecs = TPToken::convertToEpochSeconds($startDateInSecs);
     23            $this->startDateInSecs = TPTokenData::convertToEpochSeconds($startDateInSecs);
    2424        if($endDateInSecs)
    25             $this->endDateInSecs = TPToken::convertToEpochSeconds($endDateInSecs);
     25            $this->endDateInSecs = TPTokenData::convertToEpochSeconds($endDateInSecs);
    2626    }
    2727
     
    4040
    4141    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);
    4743    }
    4844
    4945    public function getAccessPeriodInSecs() {
    5046        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);
    8347    }
    8448
     
    12488
    12589    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);
    12892        $this->caption = $caption;
    12993        return $this;
     
    13195
    13296    public function isActive($timestampSecs) {
    133         $timestampSecs = TPToken::convertToEpochSeconds($timestampSecs);
     97        $timestampSecs = TPTokenData::convertToEpochSeconds($timestampSecs);
    13498        if ($this->getStartDateInSecs() != null && $this->getStartDateInSecs() > $timestampSecs) return false;
    13599        if ($this->getEndDateInSecs() != null && $this->getEndDateInSecs() < $timestampSecs) return false;
     
    137101    }
    138102
     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    }
    139122
    140123    public function __toString() {
    141124        $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());
    144128
    145129        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()));
    147131        }
    148132
    149133        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()));
    151135        }
    152136
    153137        if ($this->getCaption() != null) {
    154             sb.("\tCaption:").($this->getCaption());
     138            $sb.("\tCaption:").($this->getCaption());
    155139        }
    156140
    157141        if ($this->splitPay != null) {
    158142            foreach ($this->splitPay as $key => $value)
    159                 sb.("\tSplit:").($key).(":").($value);
     143                $sb.("\tSplit:").($key).(":").($value);
    160144        }
     145
     146        if($this->isRecurring()) {
     147            $sb.("\n\tBilling Period:").($this->getBillingPeriod());
     148            $sb.("\tTrial Period:").($this->getTrialPeriod());
     149        }
     150   
    161151        return $sb;
    162152    }
  • tinypass/branches/silver_bullet/api/TPRIDHash.php

    r461567 r593084  
    11<?php
    22
    3 class TPRIDHash {
     3class TPRID {
    44
    5     public static $ENCODER = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
    6     private $hash;
     5    private $id;
    76
    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;
    149    }
    1510
    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;
    2313    }
    2414
    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;
    2720    }
    2821
    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;
    5429        }
    5530    }
    5631
    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}
    8433
    8534
    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 character
    104         for($i = 0; $i < mb_strlen($str,"UCS-4BE"); $i++) {
    105 // Now we have 4 bytes. Find their total
    106 // 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 
    11735?>
  • tinypass/branches/silver_bullet/api/TinyPass.php

    r461624 r593084  
    44require_once "policies/Policies.php";
    55require_once "TPRIDHash.php";
     6require_once "TinyPassGateway.php";
    67require_once "TPResource.php";
    78require_once "TPOffer.php";
    89require_once "TinyPassException.php";
    9 require_once "TPVersion.php";
    1010require_once "TPPriceOption.php";
    11 require_once "ui/TPTicket.php";
    12 require_once "ui/TPWebWidget.php";
    13 require_once "ui/TPWebRequest.php";
     11require_once "TPUtils.php";
     12require_once "ui/TPPurchaseRequest.php";
     13require_once "ui/TPHtmlWidget.php";
    1414require_once "TPClientMsgBuilder.php";
    1515require_once "builder/TPClientBuilder.php";
    1616require_once "builder/TPClientParser.php";
     17require_once "builder/TPCookieParser.php";
    1718require_once "builder/TPSecureEncoder.php";
    1819require_once "builder/TPOpenEncoder.php";
    1920require_once "builder/TPJsonMsgBuilder.php";
    2021require_once "builder/TPSecurityUtils.php";
    21 require_once "token/TPTokenWrapper.php";
    22 require_once "token/TPMeterDetails.php";
     22require_once "token/TPAccessTokenStore.php";
     23require_once "token/TPMeterStore.php";
     24require_once "token/TPMeter.php";
    2325require_once "token/TPAccessToken.php";
    2426require_once "token/TPAccessTokenList.php";
    25 require_once "token/TPToken.php";
     27require_once "token/TPTokenData.php";
    2628
    2729
    2830class TinyPass {
    2931
    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 = "";
    3335
    34     protected $accessTokenList;
    35     protected $localAccessTokenList;
    36     protected $localBindList;
     36    public static $AID = "";
     37    public static $PRIVATE_KEY = "";
     38    public static $SANDBOX = false;
    3739
    38     protected $aid;
    39     protected $privateKey;
    40     protected $apiEndpoint;
    41     protected $msgbuilder;
     40    public static $CONNECTION_TIMEOUT = 5000;
     41    public static $READ_TIMEOUT = 10000;
    4242
    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);
    6647    }
    6748
    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);
    8651    }
    8752
    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);
    10955    }
    11056
    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);
    13559    }
    13660
    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);
    16963    }
    17064
    171     public function __generateLocalCookie() {
     65}
    17266
     67class TPConfig {
    17368
    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";
    17771
    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";
    18074
    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;
    18286    }
    18387
    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;
    20495        }
    20596    }
    20697
    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;
    217100    }
    218101
     
    221104    }
    222105
    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 
    261106}
    262107
    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 }
    275108?>
  • tinypass/branches/silver_bullet/api/TinyPassException.php

    r461567 r593084  
    33class TinyPassException extends Exception {
    44
    5     public function __construct($message) {
     5    public $code = 0;
     6
     7    public function __construct($message, $code = 0) {
    68        parent::__construct($message);
     9        $this->code = 0;
    710    }
     11
    812
    913}
  • tinypass/branches/silver_bullet/api/builder/TPClientBuilder.php

    r461624 r593084  
    88    const ENCODING_OPEN = 'o';
    99
     10    const STD_ENC = "{jax}";
     11    const ZIP_ENC = "{jzx}";
     12    const OPEN_ENC = "{jox}";
     13
    1014    private $builder;
    1115    private $encoder;
     
    1519    private $mask = "";
    1620
    17     function __construct($privateKey, $settings = null) {
    18         $this->privateKey = $privateKey;
     21    function __construct($settings = null) {
     22        $this->privateKey = TinyPass::$PRIVATE_KEY;
    1923        $this->mask.=("{");
    2024        switch ($settings!=null && strlen($settings)>1 ? $settings{1} : self::TYPE_JSON) {
     
    3842    }
    3943
    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));
    4257    }
    4358
    44     public function buildTicketRequest($tickets) {
     59    public function buildPurchaseRequest($tickets) {
    4560
    46         if($tickets instanceof TPTicket) {
     61        if($tickets instanceof TPPurchaseRequest) {
    4762            $tickets = array($tickets);
    4863        }
    4964
    50         return $this->mask . $this->encoder->encode($this->builder->buildTicketRequest($tickets));
     65        return $this->mask . $this->encoder->encode($this->builder->buildPurchaseRequest($tickets));
    5166    }
    5267
  • tinypass/branches/silver_bullet/api/builder/TPClientParser.php

    r461566 r593084  
    33class TPClientParser {
    44
    5     private $privateKey;
    6     private $builder;
     5    private $parser;
    76    private $encoder;
    87
    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();
    1113    }
    1214
    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    }
    1425
    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) {
    1660
    1761            case TPClientBuilder::TYPE_JSON:
    1862            default:
    19                 $this->builder = new TPJsonMsgBuilder();
     63                $this->parser = new TPJsonMsgBuilder();
    2064
    2165        }
    22         switch ($str!=null && strlen($str)>2 ? $str{2} : TPClientBuilder::ENCODING_AES) {
     66        switch (strlen($str)>2 ? $str{2} : TPClientBuilder::ENCODING_AES) {
    2367
    2468            case TPClientBuilder::ENCODING_OPEN:
     
    2872            case TPClientBuilder::ENCODING_AES:
    2973            default:
    30                 $this->encoder = new TPSecureEncoder($this->privateKey);
     74                $this->encoder = new TPSecureEncoder($this->config->PRIVATE_KEY);
    3175        }
    3276        return preg_replace('/^{...}/','', $str);
    3377    }
    3478
    35     public function parseAccessTokenList($message) {
    36         $s = $this->checkSettings($message);
    37         return $this->builder->parseAccessTokenList($this->encoder->decode($s));
    38     }
     79
    3980
    4081}
  • tinypass/branches/silver_bullet/api/builder/TPJsonMsgBuilder.php

    r461624 r593084  
    33class TPJsonMsgBuilder {
    44
    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) {
    662        $list = array();
    763
    8         foreach($tickets as $ticket) {
    9             $list[] = $this->buildTicket($ticket);
     64        foreach($requestData as $request) {
     65            $list[] = $this->buildRequest($request);
    1066        }
    1167
     
    1369    }
    1470
    15     public function buildTicket(TPTicket $ticket) {
     71    public function buildRequest(TPPurchaseRequest $request) {
    1672
    1773        $ticketMap = array();
    1874
    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();
    2479
     80        if($request->getClientIP())
     81            $ticketMap["ip"] =  $request->getClientIP();
    2582
    26         if ($ticket->getOptions() != null && count($ticket->getOptions()) > 0)
    27             $ticketMap["opts"] =  $ticket->getOptions();
     83        if($request->getUserRef() != null)
     84            $ticketMap["uref"] = $request->getUserRef();
    2885
    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());
    3191        }
    3292
    3393
    3494        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;
    4795
    4896    }
     
    55103        $map["rurl"] = $offer->getResource()->getURL();
    56104
    57         if ($options != null)
    58             $map["opts"] = $options;
     105        if ($offer->getTags())
     106            $map["tags"] = $offer->getTags();
    59107
    60108        $pos = array();
     
    75123    }
    76124
    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) {
    85126        $tokens = array();
    86127
    87         foreach($list->getTokens() as $rid => $token) {
    88             array_push($tokens, $token->getValues());
     128        foreach($list->getTokens() as $token) {
     129            $tokens[] = $token->getTokenData()->getValues();
    89130        }
     131        return json_encode($tokens);
     132    }
    90133
    91         $map["tokens"] = $tokens;
    92         return json_encode($map);
     134    public function buildAccessToken($accessToken) {
     135        return json_encode($accessToken->getTokenData()->getValues());
    93136    }
    94137
     
    108151            $map["ed"] = $this->nuller($po->getEndDateInSecs());
    109152
     153        if ($po->isRecurring()) {
     154            $map["recur"] = "true";
     155        }
    110156
    111157        $map["cpt"] =  $this->nuller($po->getCaption());
     
    121167    }
    122168
    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             else
    144                 $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 
    173169}
    174170
  • tinypass/branches/silver_bullet/api/builder/TPSecurityUtils.php

    r461566 r593084  
    22
    33class TPSecurityUtils {
    4 
    5     //private static $LONG_MAX = "9223372036854775807";
    6     //private static $LONG_MIN = "-9223372036854775808";
    74
    85    public static function hashCode($s) {
     
    121118        return $string;
    122119    }
     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
    123139}
    124140
  • tinypass/branches/silver_bullet/api/policies/Policies.php

    r541448 r593084  
    1616}
    1717
    18 class TPMeteredPolicyImpl extends TPPolicy {
    19 
    20 }
    21 class TPReminderMeteredPricing extends TPMeteredPolicyImpl {
     18class TPReminderMeteredPricing extends TPPolicy {
    2219
    2320    public static function createByAccessCount($trialCount, $lockoutPeriod) {
     
    2522        $meter = new TPReminderMeteredPricing();
    2623
    27         $meter->set(TPToken::METER_LOCKOUT_PERIOD, $lockoutPeriod);
     24        $meter->set(TPTokenData::METER_LOCKOUT_PERIOD, $lockoutPeriod);
    2825        $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);
    3229        return $meter;
    3330
     
    3835        $meter = new TPReminderMeteredPricing();
    3936
    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);
    4340        $meter->set(TPPolicy::POLICY_TYPE, TPPolicy::REMINDER_METER_BY_TIME);
    4441
    45         $parsed = TPPriceOption::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)));
    4946        return $meter;
    5047    }
     
    5451 * Metered Pricing
    5552 */
    56 class TPStrictMeteredPricing extends TPMeteredPolicyImpl {
     53class TPStrictMeteredPricing extends TPPolicy {
    5754
    5855    public static function createByPeriod($trialPeriod, $lockoutPeriod) {
    5956        $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);
    6360        $meter->set(TPPolicy::POLICY_TYPE, TPPolicy::STRICT_METER_BY_TIME);
    6461        return $meter;
     
    9693        $r->set(TPPolicy::POLICY_TYPE, TPPolicy::RESTRICT_MAX_PURCHASES);
    9794        $r->set("amount", $maxAmount);
    98         $r->set("withInPeriod", $withInPeriod);
     95        $r->set("withinPeriod", $withInPeriod);
    9996        if($linkWithDetails)
    10097            $r->set("linkWithDetails", $linkWithDetails);
  • tinypass/branches/silver_bullet/api/policies/TPPolicy.php

    r461567 r593084  
    2727class TPPricingPolicy {
    2828
    29     public static function createBasic(array $priceOptions) {
     29    public static function createBasic(array $priceOptions = null) {
     30        if($priceOptions == null)
     31                $priceOptions = array();
    3032        return new TPBasicPricing($priceOptions);
    3133    }
  • tinypass/branches/silver_bullet/api/token/TPAccessToken.php

    r461567 r593084  
    1010 * cURL with HTTPS support
    1111 */
    12 class TPAccessToken extends TPTokenWrapper {
     12class TPAccessToken {
     13
     14    private $token;
     15    private $accessState;
    1316
    1417    public function __construct() {
    15         parent::__construct();
    1618
    1719        $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) {
    2023            $this->token = func_get_arg(0);
    2124            return;
    2225        }
    2326
     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
    2433        if($numargs == 2) {
    25             $ridhash = func_get_arg(0);
     34            $rid = TPRID::parse(func_get_arg(0));
    2635            $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);
    2938            return;
    3039        }
    3140
    3241        if($numargs == 3) {
    33             $ridhash = func_get_arg(0);
     42            $rid = TPRID::parse(func_get_arg(0));
    3443            $expiration = func_get_arg(1);
    3544            $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());
    4364    }
    4465
    4566    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);
    4772    }
    4873
    4974    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
    56204
    57205    /**
     
    60208
    61209    public function isExpired() {
    62         $time = $this->getPreExpirationInSeconds();
     210        $time = $this->getEarlyExpirationInSeconds();
    63211
    64212        if ($time == null || $time == 0)
    65             $time = $this->getExpirationInSeconds();
     213            $time = $this->getExpirationInSecs();
    66214
    67215        if ($time == null || $time == 0)
     
    70218        return $time <= time();
    71219    }
    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
     270class 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;
    73281
    74282
  • tinypass/branches/silver_bullet/api/token/TPAccessTokenList.php

    r461567 r593084  
    44
    55    public static $MAX = 20;
    6     private $aid;
    7     private $uid;
    86    private $tokens = array();
    9     private $rawToken = "";
    10     private $buildTime = 0;
    11     private $ips = array();
    12     private $lastError = 0;
    137
    148
    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
    1816    }
    1917
    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;
    2620    }
    2721
     
    3024    }
    3125
    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);
    3429    }
    3530
    36     function setUID($uid) {
    37         $this->uid = $uid;
     31    public function remove($rid) {
     32        $rid = TPRID::parse($rid);
     33        unset($this->tokens[$rid->toString()]);
    3834    }
    3935
    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;
    4341    }
    4442
    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        }
    4847    }
    4948
    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     }
    10249
    10350    /**
     
    10552     * @param <String> $rid String RID
    10653     */
    107     public function getToken($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()];
    11158        }
    11259        return null;
    11360    }
    11461
    115     public function setBuildTime($time) {
    116         $this->buildTime = $time;
    117     }
    11862
    11963    public function isEmpty() {
     
    12569    }
    12670
    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());
    12974    }
    13075
    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());
    15079    }
    15180
Note: See TracChangeset for help on using the changeset viewer.