Ejemplo n.º 1
0
 /**
  * @param $tag
  * @param $query
  * @return mixed
  * @throws \Desarrolla2\Cache\Exception\FileCacheException
  */
 public function cache($tag, $query)
 {
     $adapter = new File(__DIR__ . '/../../../../../../src/Storage/cache');
     $adapter->setOption('ttl', $this->duration);
     $cache = new Cache($adapter);
     $cache->set($tag, $query, $this->duration);
     return $cache->get($tag);
 }
Ejemplo n.º 2
0
 public static function write($arreglo, $root, $archivo)
 {
     if (!self::$instance instanceof self) {
         self::$instance = new self();
     }
     $_xml = new \SimpleXMLElement("<?xml version=\"1.0\"?><" . $root . "></" . $root . ">");
     self::array_to_xml($arreglo, $_xml);
     $adapter = new File(PATH_CACHE);
     $adapter->setOption('ttl', 86400);
     $cache = new Cache($adapter);
     $cache->set('config', $arreglo, 86400);
     return $_xml->asXML($archivo);
 }
Ejemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 public function getProducts($rentGuaranteeOfferingType, $propertyLettingType)
 {
     $parameters = array('rentGuaranteeOfferingType' => (int) $rentGuaranteeOfferingType, 'propertyLettingType' => (int) $propertyLettingType);
     // Always merge context parameters as this cache is unique per agent branch
     $cacheKey = $this->buildCacheKey(array_merge($parameters, $this->context->getParameters()));
     if ($this->cache->has($cacheKey)) {
         return $this->cache->get($cacheKey);
     }
     /** @var \Guzzle\Common\Collection $products */
     $products = $this->context->getProductClient()->getProducts($parameters);
     $this->cache->set($cacheKey, $products, 500);
     // Longer TTL for products
     return $products;
 }
Ejemplo n.º 4
0
 /**
  * Return a category of lookup items as a choice
  * array for use in form types
  *
  * @param string $categoryName
  * @return array
  */
 public function getCategoryAsChoices($categoryName)
 {
     $cacheKey = $this->buildCompoundCacheKey(array($categoryName));
     if ($this->cache->has($cacheKey)) {
         return $this->cache->get($cacheKey);
     }
     $choices = array();
     $items = $this->lookup->getCategoryByName($categoryName)->getItems();
     /** @var \Barbondev\IRISSDK\IndividualApplication\Lookup\Model\LookupItem $item */
     foreach ($items as $item) {
         $choices[$item->getId()] = $item->getName();
     }
     $this->cache->set($cacheKey, $choices);
     return $choices;
 }
Ejemplo n.º 5
0
 /**
  * @param string $name
  * @return IAttribute
  */
 public function delete($name)
 {
     if ($this->cache) {
         $this->cache->delete($name);
     }
     return $this;
 }
Ejemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function getProductPrice($agentSchemeNumber, $productId, $propertyLetType, $rentGuaranteeOfferingType, $shareOfRent, $policyLengthInMonths)
 {
     $parameters = array('productId' => (int) $productId, 'agentSchemeNumber' => (int) $agentSchemeNumber, 'propertyLetType' => (int) $propertyLetType, 'rentGuaranteeOfferingType' => (int) $rentGuaranteeOfferingType, 'shareOfRent' => (double) $shareOfRent, 'policyLengthInMonths' => (int) ($policyLengthInMonths ?: 0), 'guarantorSequenceNumber' => (int) 0, 'isRenewal' => (int) false);
     // Always merge context parameters as this cache is unique per agent branch
     $cacheKey = $this->buildCacheKey(array_merge($parameters, $this->context->getParameters()));
     if ($this->cache->has($cacheKey)) {
         return $this->cache->get($cacheKey);
     }
     /** @var \Barbondev\IRISSDK\IndividualApplication\Product\Model\ProductPrice $productPrice */
     try {
         $productPrice = $this->context->getProductClient()->getProductPrice($parameters);
     } catch (NotFoundException $e) {
         throw new ProductPriceNotFoundException(sprintf('Product price not found using parameters: ', print_r($parameters, true)));
     }
     $this->cache->set($cacheKey, $productPrice, 120);
     // Short TTL for this cache
     return $productPrice;
 }
Ejemplo n.º 7
0
 private function _token($type)
 {
     if ($type == 'Generic') {
         $adapter = new File(PATH_CACHE);
         $adapter->setOption('ttl', 10800);
         $cache = new Cache($adapter);
         $token = $cache->get('token');
         if (is_null($token)) {
             $token = Tokenizer::create(['GENERIC_API' => true], APP_KEY, 180);
             $cache->set('token', $token, 10800);
         }
         return $token;
     }
     if ($type == 'User') {
         //var_dump(Session::get());
         return Session::get('sincco\\login\\token');
     }
 }
Ejemplo n.º 8
0
 public function testHasWithTtlExpired()
 {
     $key = 'key1';
     $value = 'value1';
     $ttl = 1;
     $this->cache->set($key, $value, $ttl);
     sleep($ttl + 1);
     $this->assertFalse($this->cache->has($key));
 }
Ejemplo n.º 9
0
 public function query($query, $params = null, $fetchmode = self::FETCH_ASSOC)
 {
     $response = false;
     $query = trim(str_replace("\r", " ", $query));
     $idQuery = md5($query . serialize($params));
     $adapter = new File(PATH_CACHE);
     $cache = new Cache($adapter);
     $rawStatement = explode(" ", preg_replace("/\\s+|\t+|\n+/", " ", $query));
     $statement = strtolower($rawStatement[0]);
     if (!defined('DEV_CACHE')) {
         if (!is_null($cache->get($this->connectionData['type'] . $idQuery))) {
             $reponse = $cache->get($this->connectionData['type'] . $idQuery);
         }
     }
     if (!$response) {
         $this->Init($query, $params);
         switch ($statement) {
             case 'select':
             case 'show':
                 $response = $this->sQuery->fetchAll($fetchmode);
                 break;
             case 'insert':
                 $response = $this->insertId();
                 break;
             case 'update':
             case 'delete':
                 $response = $this->sQuery->rowCount();
             default:
                 $response = NULL;
                 break;
         }
     }
     if (!defined('DEV_CACHE')) {
         $cache->set($this->connectionData['type'] . $idQuery, $response);
     }
     return $response;
 }
Ejemplo n.º 10
0
 /**
  * Attach a user session to a broker session
  */
 public function attach()
 {
     $this->detectReturnType();
     if (empty($_REQUEST['broker'])) {
         return $this->fail("No broker specified", 400);
     }
     if (empty($_REQUEST['token'])) {
         return $this->fail("No token specified", 400);
     }
     if (!$this->returnType) {
         return $this->fail("No return url specified", 400);
     }
     $checksum = $this->generateAttachChecksum($_REQUEST['broker'], $_REQUEST['token']);
     if (empty($_REQUEST['checksum']) || $checksum != $_REQUEST['checksum']) {
         return $this->fail("Invalid checksum", 400);
     }
     $this->startUserSession();
     $sid = $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
     $this->cache->set($sid, $this->getSessionData('id'));
     $this->outputAttachSuccess();
 }
Ejemplo n.º 11
0
 /**
  * Check for a new version
  *
  * @return int|bool
  *         true: New version is available
  *         false: Error while checking for update
  *         int: Status code (i.e. AutoUpdate::NO_UPDATE_AVAILABLE)
  */
 public function checkUpdate()
 {
     $this->_log->addNotice('Checking for a new update...');
     // Reset previous updates
     $this->_latestVersion = new version('0.0.0');
     $this->_updates = [];
     $versions = $this->_cache->get('update-versions');
     // Check if cache is empty
     if ($versions === false) {
         // Create absolute url to update file
         $updateFile = $this->_updateUrl . '/' . $this->_updateFile;
         if (!empty($this->_branch)) {
             $updateFile .= '.' . $this->_branch;
         }
         $this->_log->addDebug(sprintf('Get new updates from %s', $updateFile));
         // Read update file from update server
         $update = @file_get_contents($updateFile, $this->_useBasicAuth());
         if ($update === false) {
             $this->_log->addInfo(sprintf('Could not download update file "%s"!', $updateFile));
             return false;
         }
         // Parse update file
         $updateFileExtension = substr(strrchr($this->_updateFile, '.'), 1);
         switch ($updateFileExtension) {
             case 'ini':
                 $versions = @parse_ini_string($update, true);
                 if (!is_array($versions)) {
                     $this->_log->addInfo('Unable to parse ini update file!');
                     return false;
                 }
                 $versions = array_map(function ($block) {
                     return isset($block['url']) ? $block['url'] : false;
                 }, $versions);
                 break;
             case 'json':
                 $versions = (array) @json_decode($update);
                 if (!is_array($versions)) {
                     $this->_log->addInfo('Unable to parse json update file!');
                     return false;
                 }
                 break;
             default:
                 $this->_log->addInfo(sprintf('Unknown file extension "%s"', $updateFileExtension));
                 return false;
         }
         $this->_cache->set('update-versions', $versions);
     } else {
         $this->_log->addDebug('Got updates from cache');
     }
     // Check for latest version
     foreach ($versions as $versionRaw => $updateUrl) {
         $version = new version($versionRaw);
         if ($version->valid() === null) {
             $this->_log->addInfo(sprintf('Could not parse version "%s" from update server "%s"', $versionRaw, $updateFile));
             continue;
         }
         if (version::gt($version, $this->_currentVersion)) {
             if (version::gt($version, $this->_latestVersion)) {
                 $this->_latestVersion = $version;
             }
             $this->_updates[] = ['version' => $version, 'url' => $updateUrl];
         }
     }
     // Sort versions to install
     usort($this->_updates, function ($a, $b) {
         return version::compare($a['version'], $b['version']);
     });
     if ($this->newVersionAvailable()) {
         $this->_log->addDebug(sprintf('New version "%s" available', $this->_latestVersion));
         return true;
     } else {
         $this->_log->addDebug('No new version available');
         return self::NO_UPDATE_AVAILABLE;
     }
 }
Ejemplo n.º 12
0
function buildChain($cert, $certPath, $includeRoot = false)
{
    if (isExpired($cert)) {
        throw new Exception("Certificate has expired");
    }
    if (areCertsLinked($cert, $cert)) {
        throw new Exception("Self-signed or CA cert");
    }
    $uris = $cert["issuers"];
    if (!$uris) {
        throw new Exception("Certificate doesn't specify issuers");
    }
    $c = $cert;
    $chain = [];
    while (sizeof($uris) > 0) {
        $old = $c;
        $uri = array_shift($uris);
        $path = downloadIssuer($uri);
        list($inform, $format) = detectCertFormat($path);
        $c = parseFormattedCert(readCertificate($path, $inform, $format));
        if (isExpired($c)) {
            throw new Exception("Expired intermediate in the chain");
        }
        if (areCertsLinked($c, $c)) {
            break;
        }
        if (!areCertsLinked($c, $old)) {
            $msg = "Intermediate doesn't match previous certificate in the chain";
            throw new Exception($msg);
        }
        $chain[] = $path;
        if (isset($c["issuers"])) {
            foreach ($c["issuers"] as $i) {
                $uris[] = $i;
                // we don't currently have a good way of handling multiple
                // issuers
                break;
            }
        }
    }
    // we are at the end of the chain, see if there's matching root CA
    $cacheDir = __DIR__ . '/cache';
    $adapter = new File($cacheDir);
    $adapter->setOption('ttl', 600);
    $cache = new Cache($adapter);
    if (!$cache->get(md5($path) . "-root")) {
        $root = findMatchingRoot($c);
        $chain[] = $root;
        $cache->set(md5($path) . "-root", $root);
    } else {
        $chain[] = $cache->get(md5($path) . "-root");
    }
    // build certificate bundle
    foreach ($chain as $i => $path) {
        list($inform, $format) = detectCertFormat($path);
        $cmd = sprintf("openssl x509 -inform %s -outform pem -in %s -out %s", escapeshellarg($inform), escapeshellarg($path), escapeshellarg(__DIR__ . "/tmp/" . sha1($cert["subject"]) . "-{$i}.pem"));
        exec($cmd);
    }
    unlink(__DIR__ . "/tmp/bundle.crt");
    foreach ($chain as $i => $path) {
        file_put_contents(__DIR__ . "/tmp/bundle.crt", file_get_contents(__DIR__ . "/tmp/" . sha1($cert["subject"]) . "-{$i}.pem"), FILE_APPEND);
    }
    // verify the chain is valid
    $cmd = sprintf("openssl verify -verbose -purpose sslserver -CAfile %s/tmp/bundle.crt %s", __DIR__, escapeshellarg($certPath));
    try {
        execute($cmd);
    } catch (Exception $e) {
        $err = implode("\n", $e->output);
        throw new Exception("Can't verify the bundle: {$err}");
    }
    // extract the original cert (it might contain some, or all, parts of the
    // chain already)
    $cmd = sprintf("openssl x509 -inform pem -outform pem -in %s", $certPath);
    $out = implode("\n", execute($cmd));
    $out .= "\n";
    if (!$includeRoot) {
        array_pop($chain);
    }
    foreach ($chain as $i => $path) {
        $out .= file_get_contents(__DIR__ . "/tmp/" . sha1($cert["subject"]) . "-{$i}.pem");
        unlink(__DIR__ . "/tmp/" . sha1($cert["subject"]) . "-{$i}.pem");
    }
    return $out;
}
Ejemplo n.º 13
0
 /**
  * @expectedException \Desarrolla2\Cache\Exception\AdapterNotSetException
  */
 public function testGetAdapterThrowsException()
 {
     $this->cache->getAdapter();
 }
Ejemplo n.º 14
0
 public function testHasWithTtlExpired()
 {
     $this->cache->set('key1', 'value1', 1);
     sleep(2);
     $this->assertFalse($this->cache->has('key1'));
 }
Ejemplo n.º 15
0
 /**
  * @dataProvider dataProvider
  */
 public function testSetOption()
 {
     $this->cache->setOption('ttl', 3600);
 }