/**
  * Come here to get your number in the requests line!
  *
  * @param Position $pos position object to populate with prev position and new position
  * @return bool sucess of getting the position in the queue
  */
 public function getPositionInLine(Position &$pos)
 {
     if ($this->_positionQueue->acquire()) {
         $pos->setup(MemoryData::getLastPosition(), MemoryData::getNewPosition());
         $this->_positionQueue->release();
         return true;
     } else {
         return false;
     }
 }
 function getValuesFromXML()
 {
     $xml_location = $this->get('xml_location');
     if (General::validateURL($xml_location) != '') {
         // is a URL, check cache
         $cache_id = md5($xml_location);
         $cache = new Cacheable($this->_Parent->_Parent->Database);
         $cachedData = $cache->check($cache_id);
         $creation = DateTimeObj::get('c');
         if (!$cachedData || time() - $cachedData['creation'] > 5 * 60) {
             if (Mutex::acquire($cache_id, 6, TMP)) {
                 $ch = new Gateway();
                 $ch->init();
                 $ch->setopt('URL', $xml_location);
                 $ch->setopt('TIMEOUT', 6);
                 $xml = $ch->exec();
                 $writeToCache = true;
                 Mutex::release($cache_id, TMP);
                 $xml = trim($xml);
                 if (empty($xml) && $cachedData) {
                     $xml = $cachedData['data'];
                 }
             } elseif ($cachedData) {
                 $xml = $cachedData['data'];
             }
         } else {
             $xml = $cachedData['data'];
         }
         $xml = simplexml_load_string($xml);
     } elseif (substr($xml_location, 0, 1) == '/') {
         // relative to DOCROOT
         $xml = simplexml_load_file(DOCROOT . $this->get('xml_location'));
     } else {
         // in extension's /xml folder
         $xml = simplexml_load_file(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location'));
     }
     if (!$xml) {
         return;
     }
     $items = $xml->xpath($this->get('item_xpath'));
     $options = array();
     foreach ($items as $item) {
         $option = array();
         $text_xpath = $item->xpath($this->get('text_xpath'));
         $option['text'] = General::sanitize((string) $text_xpath[0]);
         if ($this->get('value_xpath') != '') {
             $value_xpath = $item->xpath($this->get('value_xpath'));
             $option['value'] = General::sanitize((string) $value_xpath[0]);
         }
         if ((string) $option['value'] == '') {
             $option['value'] = $option['text'];
         }
         $options[] = $option;
     }
     return $options;
 }
 /**
  * Verifies that another process can successfully block this one.
  */
 public function testBlock()
 {
     $mutex = new Mutex(self::$_mutexID);
     $bootstrapFile = realpath(__DIR__ . '/../classLoader.inc.php');
     $this->assertNotFalse($bootstrapFile);
     $cmd = 'env phpunit --bootstrap=' . $bootstrapFile . ' --filter=testBlockInSeparateProcess ' . __FILE__ . ' > /dev/null';
     $startTime = time();
     pclose(popen($cmd, 'r'));
     $mutex->acquire();
     $mutex->release();
     $this->assertGreaterThanOrEqual(2, time() - $startTime);
 }
 public function write($hash, $data, $ttl = NULL)
 {
     if (!Mutex::acquire($hash, 2, TMP)) {
         return;
     }
     $creation = time();
     $expiry = NULL;
     $ttl = intval($ttl);
     if ($ttl > 0) {
         $expiry = $creation + $ttl * 60;
     }
     if (!($data = $this->compressData($data))) {
         return false;
     }
     $this->forceExpiry($hash);
     $this->Database->insert(array('hash' => $hash, 'creation' => $creation, 'expiry' => $expiry, 'data' => $data), 'tbl_cache');
     Mutex::release($hash, TMP);
 }
 public function execute(array &$param_pool = null)
 {
     $result = new XMLElement($this->dsParamROOTELEMENT);
     $this->dsParamURL = $this->parseParamURL($this->dsParamURL);
     if (isset($this->dsParamXPATH)) {
         $this->dsParamXPATH = $this->__processParametersInString($this->dsParamXPATH, $this->_env);
     }
     $stylesheet = new XMLElement('xsl:stylesheet');
     $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform'));
     $output = new XMLElement('xsl:output');
     $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes'));
     $stylesheet->appendChild($output);
     $template = new XMLElement('xsl:template');
     $template->setAttribute('match', '/');
     $instruction = new XMLElement('xsl:copy-of');
     // Namespaces
     if (isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS)) {
         foreach ($this->dsParamFILTERS as $name => $uri) {
             $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri);
         }
     }
     // XPath
     $instruction->setAttribute('select', $this->dsParamXPATH);
     $template->appendChild($instruction);
     $stylesheet->appendChild($template);
     $stylesheet->setIncludeHeader(true);
     $xsl = $stylesheet->generate(true);
     $cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH);
     $cache = new Cacheable(Symphony::Database());
     $cachedData = $cache->read($cache_id);
     $writeToCache = false;
     $valid = true;
     $creation = DateTimeObj::get('c');
     $timeout = isset($this->dsParamTIMEOUT) ? (int) max(1, $this->dsParamTIMEOUT) : 6;
     // Execute if the cache doesn't exist, or if it is old.
     if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) {
         if (Mutex::acquire($cache_id, $timeout, TMP)) {
             $ch = new Gateway();
             $ch->init($this->dsParamURL);
             $ch->setopt('TIMEOUT', $timeout);
             $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*'));
             $data = $ch->exec();
             $info = $ch->getInfoLast();
             Mutex::release($cache_id, TMP);
             $data = trim($data);
             $writeToCache = true;
             // Handle any response that is not a 200, or the content type does not include XML, plain or text
             if ((int) $info['http_code'] !== 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) {
                 $writeToCache = false;
                 $result->setAttribute('valid', 'false');
                 // 28 is CURLE_OPERATION_TIMEOUTED
                 if ($info['curl_error'] == 28) {
                     $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout)));
                 } else {
                     $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type'])));
                 }
                 return $result;
                 // Handle where there is `$data`
             } elseif (strlen($data) > 0) {
                 // If the XML doesn't validate..
                 if (!General::validateXML($data, $errors, false, new XsltProcess())) {
                     $writeToCache = false;
                 }
                 // If the `$data` is invalid, return a result explaining why
                 if ($writeToCache === false) {
                     $element = new XMLElement('errors');
                     $result->setAttribute('valid', 'false');
                     $result->appendChild(new XMLElement('error', __('Data returned is invalid.')));
                     foreach ($errors as $e) {
                         if (strlen(trim($e['message'])) == 0) {
                             continue;
                         }
                         $element->appendChild(new XMLElement('item', General::sanitize($e['message'])));
                     }
                     $result->appendChild($element);
                     return $result;
                 }
                 // If `$data` is empty, set the `force_empty_result` to true.
             } elseif (strlen($data) == 0) {
                 $this->_force_empty_result = true;
             }
             // Failed to acquire a lock
         } else {
             $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock, check that %s exists and is writable.', array('<code>Mutex</code>', '<code>' . TMP . '</code>'))));
         }
         // The cache is good, use it!
     } else {
         $data = trim($cachedData['data']);
         $creation = DateTimeObj::get('c', $cachedData['creation']);
     }
     // If `$writeToCache` is set to false, invalidate the old cache if it existed.
     if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) {
         $data = trim($cachedData['data']);
         $valid = false;
         $creation = DateTimeObj::get('c', $cachedData['creation']);
         if (empty($data)) {
             $this->_force_empty_result = true;
         }
     }
     // If `force_empty_result` is false and `$result` is an instance of
     // XMLElement, build the `$result`.
     if (!$this->_force_empty_result && is_object($result)) {
         $proc = new XsltProcess();
         $ret = $proc->process($data, $xsl);
         if ($proc->isErrors()) {
             $result->setAttribute('valid', 'false');
             $error = new XMLElement('error', __('Transformed XML is invalid.'));
             $result->appendChild($error);
             $element = new XMLElement('errors');
             foreach ($proc->getError() as $e) {
                 if (strlen(trim($e['message'])) == 0) {
                     continue;
                 }
                 $element->appendChild(new XMLElement('item', General::sanitize($e['message'])));
             }
             $result->appendChild($element);
         } elseif (strlen(trim($ret)) == 0) {
             $this->_force_empty_result = true;
         } else {
             if ($writeToCache) {
                 $cache->write($cache_id, $data, $this->dsParamCACHE);
             }
             $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret));
             $result->setAttribute('status', $valid === true ? 'fresh' : 'stale');
             $result->setAttribute('creation', $creation);
         }
     }
     return $result;
 }
 public function execute(array &$param_pool = null)
 {
     $result = new XMLElement($this->dsParamROOTELEMENT);
     // When DS is called out of the Frontend context, this will enable
     // {$root} and {$workspace} parameters to be evaluated
     if (empty($this->_env)) {
         $this->_env['env']['pool'] = array('root' => URL, 'workspace' => WORKSPACE);
     }
     try {
         require_once TOOLKIT . '/class.gateway.php';
         require_once TOOLKIT . '/class.xsltprocess.php';
         require_once CORE . '/class.cacheable.php';
         $this->dsParamURL = $this->parseParamURL($this->dsParamURL);
         if (isset($this->dsParamXPATH)) {
             $this->dsParamXPATH = $this->__processParametersInString(stripslashes($this->dsParamXPATH), $this->_env);
         }
         // Builds a Default Stylesheet to transform the resulting XML with
         $stylesheet = new XMLElement('xsl:stylesheet');
         $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform'));
         $output = new XMLElement('xsl:output');
         $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes'));
         $stylesheet->appendChild($output);
         $template = new XMLElement('xsl:template');
         $template->setAttribute('match', '/');
         $instruction = new XMLElement('xsl:copy-of');
         // Namespaces
         if (isset($this->dsParamNAMESPACES) && is_array($this->dsParamNAMESPACES)) {
             foreach ($this->dsParamNAMESPACES as $name => $uri) {
                 $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri);
             }
         }
         // XPath
         $instruction->setAttribute('select', $this->dsParamXPATH);
         $template->appendChild($instruction);
         $stylesheet->appendChild($template);
         $stylesheet->setIncludeHeader(true);
         $xsl = $stylesheet->generate(true);
         // Check for an existing Cache for this Datasource
         $cache_id = self::buildCacheID($this);
         $cache = Symphony::ExtensionManager()->getCacheProvider('remotedatasource');
         $cachedData = $cache->check($cache_id);
         $writeToCache = null;
         $isCacheValid = true;
         $creation = DateTimeObj::get('c');
         // Execute if the cache doesn't exist, or if it is old.
         if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) {
             if (Mutex::acquire($cache_id, $this->dsParamTIMEOUT, TMP)) {
                 $ch = new Gateway();
                 $ch->init($this->dsParamURL);
                 $ch->setopt('TIMEOUT', $this->dsParamTIMEOUT);
                 // Set the approtiate Accept: headers depending on the format of the URL.
                 if ($this->dsParamFORMAT == 'xml') {
                     $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*'));
                 } elseif ($this->dsParamFORMAT == 'json') {
                     $ch->setopt('HTTPHEADER', array('Accept: application/json, */*'));
                 } elseif ($this->dsParamFORMAT == 'csv') {
                     $ch->setopt('HTTPHEADER', array('Accept: text/csv, */*'));
                 }
                 self::prepareGateway($ch);
                 $data = $ch->exec();
                 $info = $ch->getInfoLast();
                 Mutex::release($cache_id, TMP);
                 $data = trim($data);
                 $writeToCache = true;
                 // Handle any response that is not a 200, or the content type does not include XML, JSON, plain or text
                 if ((int) $info['http_code'] != 200 || !preg_match('/(xml|json|csv|plain|text)/i', $info['content_type'])) {
                     $writeToCache = false;
                     $result->setAttribute('valid', 'false');
                     // 28 is CURLE_OPERATION_TIMEOUTED
                     if ($info['curl_error'] == 28) {
                         $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout)));
                     } else {
                         $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type'])));
                     }
                     return $result;
                 } else {
                     if (strlen($data) > 0) {
                         // Handle where there is `$data`
                         // If it's JSON, convert it to XML
                         if ($this->dsParamFORMAT == 'json') {
                             try {
                                 require_once TOOLKIT . '/class.json.php';
                                 $data = JSON::convertToXML($data);
                             } catch (Exception $ex) {
                                 $writeToCache = false;
                                 $errors = array(array('message' => $ex->getMessage()));
                             }
                         } elseif ($this->dsParamFORMAT == 'csv') {
                             try {
                                 require_once EXTENSIONS . '/remote_datasource/lib/class.csv.php';
                                 $data = CSV::convertToXML($data);
                             } catch (Exception $ex) {
                                 $writeToCache = false;
                                 $errors = array(array('message' => $ex->getMessage()));
                             }
                         } elseif ($this->dsParamFORMAT == 'txt') {
                             $txtElement = new XMLElement('entry');
                             $txtElement->setValue(General::wrapInCDATA($data));
                             $data = $txtElement->generate();
                             $txtElement = null;
                         } else {
                             if (!General::validateXML($data, $errors, false, new XsltProcess())) {
                                 // If the XML doesn't validate..
                                 $writeToCache = false;
                             }
                         }
                         // If the `$data` is invalid, return a result explaining why
                         if ($writeToCache === false) {
                             $error = new XMLElement('errors');
                             $error->setAttribute('valid', 'false');
                             $error->appendChild(new XMLElement('error', __('Data returned is invalid.')));
                             foreach ($errors as $e) {
                                 if (strlen(trim($e['message'])) == 0) {
                                     continue;
                                 }
                                 $error->appendChild(new XMLElement('item', General::sanitize($e['message'])));
                             }
                             $result->appendChild($error);
                             return $result;
                         }
                     } elseif (strlen($data) == 0) {
                         // If `$data` is empty, set the `force_empty_result` to true.
                         $this->_force_empty_result = true;
                     }
                 }
             } else {
                 // Failed to acquire a lock
                 $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock.', array('<code>Mutex</code>'))));
             }
         } else {
             // The cache is good, use it!
             $data = trim($cachedData['data']);
             $creation = DateTimeObj::get('c', $cachedData['creation']);
         }
         // Visit the data
         $this->exposeData($data);
         // If `$writeToCache` is set to false, invalidate the old cache if it existed.
         if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) {
             $data = trim($cachedData['data']);
             $isCacheValid = false;
             $creation = DateTimeObj::get('c', $cachedData['creation']);
             if (empty($data)) {
                 $this->_force_empty_result = true;
             }
         }
         // If `force_empty_result` is false and `$result` is an instance of
         // XMLElement, build the `$result`.
         if (!$this->_force_empty_result && is_object($result)) {
             $proc = new XsltProcess();
             $ret = $proc->process($data, $xsl);
             if ($proc->isErrors()) {
                 $result->setAttribute('valid', 'false');
                 $error = new XMLElement('error', __('Transformed XML is invalid.'));
                 $result->appendChild($error);
                 $errors = new XMLElement('errors');
                 foreach ($proc->getError() as $e) {
                     if (strlen(trim($e['message'])) == 0) {
                         continue;
                     }
                     $errors->appendChild(new XMLElement('item', General::sanitize($e['message'])));
                 }
                 $result->appendChild($errors);
                 $result->appendChild(new XMLElement('raw-data', General::wrapInCDATA($data)));
             } elseif (strlen(trim($ret)) == 0) {
                 $this->_force_empty_result = true;
             } else {
                 if ($this->dsParamCACHE > 0 && $writeToCache) {
                     $cache->write($cache_id, $data, $this->dsParamCACHE);
                 }
                 $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret));
                 $result->setAttribute('status', $isCacheValid === true ? 'fresh' : 'stale');
                 $result->setAttribute('cache-id', $cache_id);
                 $result->setAttribute('creation', $creation);
             }
         }
     } catch (Exception $e) {
         $result->appendChild(new XMLElement('error', $e->getMessage()));
     }
     if ($this->_force_empty_result) {
         $result = $this->emptyXMLSet();
     }
     $result->setAttribute('url', General::sanitize($this->dsParamURL));
     return $result;
 }
$cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH);
$cache = new Cacheable($this->_Parent->Database);
$cachedData = $cache->check($cache_id);
$writeToCache = false;
$valid = true;
$result = NULL;
$creation = DateTimeObj::get('c');
if (!$cachedData || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) {
    if (Mutex::acquire($cache_id, 6, TMP)) {
        $ch = new Gateway();
        $ch->init();
        $ch->setopt('URL', $this->dsParamURL);
        $ch->setopt('TIMEOUT', 6);
        $xml = $ch->exec();
        $writeToCache = true;
        Mutex::release($cache_id, TMP);
        $xml = trim($xml);
        if (!empty($xml)) {
            $valid = General::validateXML($xml, $errors, false, $proc);
            if (!$valid) {
                if ($cachedData) {
                    $xml = $cachedData['data'];
                } else {
                    $result = new XMLElement($this->dsParamROOTELEMENT);
                    $result->setAttribute('valid', 'false');
                    $result->appendChild(new XMLElement('error', __('XML returned is invalid.')));
                }
            }
        } else {
            $this->_force_empty_result = true;
        }
 public function write($key, $data, $ttl = NULL)
 {
     if (!Mutex::acquire(md5($key), 2, TMP)) {
         return;
     }
     $data = new CacheResult(trim($data), $key, time());
     file_put_contents(CACHE . '/' . md5($key) . '.cache', self::__compress($data));
     Mutex::release(md5($key), TMP);
 }
 /**
  * Not a test, but facilitates mutex testing.
  *
  * @group meta
  */
 public function testMutexInSeparateProcess()
 {
     $mutex = new Mutex('Logger');
     $mutex->acquire();
     sleep(2);
     $mutex->release();
 }
 /**
  * This function will compress data for storage in `tbl_cache`.
  * It is left to the user to define a unique hash for this data so that it can be
  * retrieved in the future. Optionally, a `$ttl` parameter can
  * be passed for this data. If this is omitted, it data is considered to be valid
  * forever. This function utilizes the Mutex class to act as a crude locking
  * mechanism.
  *
  * @see toolkit.Mutex
  * @throws DatabaseException
  * @param string $hash
  *  The hash of the Cached object, as defined by the user
  * @param string $data
  *  The data to be cached, this will be compressed prior to saving.
  * @param integer $ttl
  *  A integer representing how long the data should be valid for in minutes.
  *  By default this is null, meaning the data is valid forever
  * @param string $namespace
  *  The namespace allows data to be grouped and saved so it can be
  *  retrieved later.
  * @return boolean
  *  If an error occurs, this function will return false otherwise true
  */
 public function write($hash, $data, $ttl = null, $namespace = null)
 {
     if (!Mutex::acquire($hash, 2, TMP)) {
         return false;
     }
     $creation = time();
     $expiry = null;
     $ttl = intval($ttl);
     if ($ttl > 0) {
         $expiry = $creation + $ttl * 60;
     }
     if (!($data = Cacheable::compressData($data))) {
         return false;
     }
     $this->delete($hash, $namespace);
     $this->Database->insert(array('hash' => $hash, 'creation' => $creation, 'expiry' => $expiry, 'data' => $data, 'namespace' => $namespace), 'tbl_cache');
     Mutex::release($hash, TMP);
     return true;
 }
 public function render(Register $ParameterOutput)
 {
     $result = null;
     $doc = new XMLDocument();
     if (isset($this->parameters()->url)) {
         $this->parameters()->url = self::replaceParametersInString($this->parameters()->url, $ParameterOutput);
     }
     if (isset($this->parameters()->xpath)) {
         $this->parameters()->xpath = self::replaceParametersInString($this->parameters()->xpath, $ParameterOutput);
     }
     $cache_id = md5($this->parameters()->url . serialize($this->parameters()->namespaces) . $this->parameters()->xpath);
     $cache = Cache::instance();
     $cachedData = $cache->read($cache_id);
     $writeToCache = false;
     $force_empty_result = false;
     $valid = true;
     $result = NULL;
     $creation = DateTimeObj::get('c');
     if (isset($this->parameters()->timeout)) {
         $timeout = (int) max(1, $this->parameters()->timeout);
     }
     if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->parameters()->{'cache-timeout'} * 60) {
         if (Mutex::acquire($cache_id, $timeout, TMP)) {
             $start = precision_timer();
             $ch = new Gateway();
             $ch->init();
             $ch->setopt('URL', $this->parameters()->url);
             $ch->setopt('TIMEOUT', $this->parameters()->timeout);
             $xml = $ch->exec();
             $writeToCache = true;
             $end = precision_timer('STOP', $start);
             $info = $ch->getInfoLast();
             Mutex::release($cache_id, TMP);
             $xml = trim($xml);
             if ((int) $info['http_code'] != 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) {
                 $writeToCache = false;
                 if (is_array($cachedData) && !empty($cachedData)) {
                     $xml = trim($cachedData['data']);
                     $valid = false;
                     $creation = DateTimeObj::get('c', $cachedData['creation']);
                 } else {
                     $result = $doc->createElement($this->parameters()->{'root-element'});
                     $result->setAttribute('valid', 'false');
                     if ($end > $timeout) {
                         $result->appendChild($doc->createElement('error', sprintf('Request timed out. %d second limit reached.', $timeout)));
                     } else {
                         $result->appendChild($doc->createElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type'])));
                     }
                     return $result;
                 }
             } elseif (strlen($xml) > 0 && !General::validateXML($xml, $errors)) {
                 $writeToCache = false;
                 if (is_array($cachedData) && !empty($cachedData)) {
                     $xml = trim($cachedData['data']);
                     $valid = false;
                     $creation = DateTimeObj::get('c', $cachedData['creation']);
                 } else {
                     $result = $doc->createElement($this->parameters()->{'root-element'}, $doc->createElement('error', __('XML returned is invalid.')), array('valid' => 'false'));
                     return $result;
                 }
             } elseif (strlen($xml) == 0) {
                 $force_empty_result = true;
             }
         } elseif (is_array($cachedData) && !empty($cachedData)) {
             $xml = trim($cachedData['data']);
             $valid = false;
             $creation = DateTimeObj::get('c', $cachedData['creation']);
             if (empty($xml)) {
                 $force_empty_result = true;
             }
         } else {
             $force_empty_result = true;
         }
     } else {
         $xml = trim($cachedData['data']);
         $creation = DateTimeObj::get('c', $cachedData['creation']);
     }
     if (!$force_empty_result) {
         $result = new XMLDocument();
         $root = $result->createElement($this->parameters()->{'root-element'});
         //XPath Approach, saves Transforming the Document.
         $xDom = new XMLDocument();
         $xDom->loadXML($xml);
         if ($xDom->hasErrors()) {
             $root->setAttribute('valid', 'false');
             $root->appendChild($result->createElement('error', __('XML returned is invalid.')));
             $messages = $result->createElement('messages');
             foreach ($xDom->getErrors() as $e) {
                 if (strlen(trim($e->message)) == 0) {
                     continue;
                 }
                 $messages->appendChild($result->createElement('item', General::sanitize($e->message)));
             }
             $root->appendChild($messages);
         } else {
             if ($writeToCache) {
                 $cache->write($cache_id, $xml);
             }
             $xpath = new DOMXPath($xDom);
             ## Namespaces
             if (is_array($this->parameters()->namespaces) && !empty($this->parameters()->namespaces)) {
                 foreach ($this->parameters()->namespaces as $index => $namespace) {
                     $xpath->registerNamespace($namespace['name'], $namespace['uri']);
                 }
             }
             $xpath_list = $xpath->query($this->parameters()->xpath);
             foreach ($xpath_list as $node) {
                 if ($node instanceof XMLDocument) {
                     $root->appendChild($result->importNode($node->documentElement, true));
                 } else {
                     $root->appendChild($result->importNode($node, true));
                 }
             }
             $root->setAttribute('status', $valid === true ? 'fresh' : 'stale');
             $root->setAttribute('creation', $creation);
         }
     }
     if (!$root->hasChildNodes() || $force_empty_result) {
         $this->emptyXMLSet($root);
     }
     $result->appendChild($root);
     return $result;
 }
 public function send_update($etva_node, $all = false, $shared = true)
 {
     $mutex = new Mutex();
     $mutex->init(self::MUTEX_UPDATE_ID);
     $mutex->acquire();
     /*
      * update other nodes..... storages
      *
      */
     $etva_cluster = $etva_node->getEtvaCluster();
     $bulk_responses = array();
     $bulk_response_dtable = array();
     if ($shared) {
         if ($all) {
             $bulk_responses = $etva_cluster->soapSend(self::GET_SYNC_LOGICALVOLUMES, array('force' => 1));
         } else {
             $bulk_responses = $etva_cluster->soapSend(self::GET_SYNC_LOGICALVOLUMES, array('force' => 1), $etva_node);
         }
         $bulk_response_dtable = $etva_cluster->soapSend(self::GET_SYNC_DEVICESTABLE);
     } else {
         $node_id = $etva_node->getId();
         $bulk_responses[$node_id] = $etva_node->soapSend(self::GET_SYNC_LOGICALVOLUMES, array('force' => 1));
         $bulk_response_dtable[$node_id] = $etva_node->soapSend(self::GET_SYNC_DEVICESTABLE);
     }
     $errors = array();
     foreach ($bulk_responses as $node_id => $node_response) {
         if ($node_response['success']) {
             //response received ok
             $node = EtvaNodePeer::retrieveByPK($node_id);
             $dtable = array();
             $response_dtable = (array) $bulk_response_dtable[$node_id];
             if ($response_dtable['success']) {
                 $dtable = (array) $response_dtable['response'];
             }
             //try initialize data from response
             $node_init = $this->initialize($node, (array) $node_response['response'], $dtable, $bulk_response_dtable);
             if (!$node_init['success']) {
                 $errors[$node_id] = $node_init;
             } else {
                 //notify system log
                 $message = Etva::getLogMessage(array(), EtvaLogicalvolumePeer::_OK_SOAPREFRESH_);
                 sfContext::getInstance()->getEventDispatcher()->notify(new sfEvent($node_response['agent'], 'event.log', array('message' => $message)));
             }
         } else {
             //response not received
             $message = Etva::getLogMessage(array('info' => $node_response['info']), EtvaLogicalvolumePeer::_ERR_SOAPREFRESH_);
             sfContext::getInstance()->getEventDispatcher()->notify(new sfEvent($node_response['agent'], 'event.log', array('message' => $message, 'priority' => EtvaEventLogger::ERR)));
         }
     }
     $mutex->release();
     return $errors;
 }
 public function write($key, $data, $encode = true, $ttl = NULL)
 {
     if ($encode) {
         $ekey = md5($key);
     } else {
         $ekey = $key;
     }
     if (!Mutex::acquire($ekey, 2, TMP)) {
         return;
     }
     $data = new CacheResult($data, $key, time());
     $cache_file = CACHE . '/' . $ekey . '.cache';
     file_put_contents($cache_file, self::__compress($data, $ttl));
     Mutex::release($ekey, TMP);
 }
Exemple #14
0
 /**
  * @description Releasing lock through mutex->release()
  */
 function mutexreleasemtd()
 {
     $m = new Mutex('lunitlock', 100);
     $m->release();
 }