public function process($xml)
 {
     $this->step = 0;
     $xml = $this->preprocessXml($xml);
     $xml = $this->handleSimpleSnippets($xml);
     // Add a snippet to trigger a process
     $snippetCount = count($this->parseSnippetsInString($xml));
     if ($snippetCount == 0) {
         $xml .= "<filler>[str_replace('a','b','c')]</filler>";
     }
     // While we have snippets
     while ($snippetCount = count($this->parseSnippetsInString($xml))) {
         $this->step++;
         $xml = '<root>' . $xml . '</root>';
         $this->initVariables($xml);
         $root = $this->dom->getElementsByTagName("root");
         $this->dom->recover = true;
         $this->parseElement($root->item(0));
         $this->dom->preserveWhiteSpace = false;
         $this->dom->formatOutput = true;
         $response = $this->dom->saveXML($this->dom);
         $xml = $this->cleanResponse($xml, $response);
         if ($this->step > 8) {
             throw new WpaeTooMuchRecursionException('Too much recursion');
         }
     }
     $xml = $this->postProcessXml($xml);
     $xml = $this->decodeSpecialCharacters($xml);
     $xml = $this->encodeSpecialCharsInAttributes($xml);
     return $xml;
 }
 function hook_article_filter($article)
 {
     if (strpos($article["link"], "taz.de") !== FALSE) {
         $doc = new DOMDocument();
         @$doc->loadHTML(mb_convert_encoding(fetch_file_contents($article["link"]), 'HTML-ENTITIES', "UTF-8"));
         $basenode = false;
         if ($doc) {
             $xpath = new DOMXPath($doc);
             // first remove advertisement stuff
             $stuff = $xpath->query('(//script)|(//noscript)|(//iframe)|(//style)|(//div[@class="sectfoot"])|(//div[@id="tzi_paywall"])|(//div[contains(@class, "rack")])');
             foreach ($stuff as $removethis) {
                 _debug("Remove1: " . $doc->saveXML($removethis));
                 $removethis->parentNode->removeChild($removethis);
             }
             $entries = $xpath->query('(//div[@class="sectbody"])');
             foreach ($entries as $entry) {
                 $basenode = $entry;
                 break;
             }
             if ($basenode) {
                 _debug("Result: " . $doc->saveXML($basenode));
                 $article["content"] = $doc->saveXML($basenode);
             }
         }
     }
     return $article;
 }
Example #3
0
File: Form.php Project: Hywan/moxl
 public function __toString()
 {
     $xml = '<x xmlns="jabber:x:data" type="submit"></x>';
     $node = new \SimpleXMLElement($xml);
     foreach ($this->_data as $key => $value) {
         $field = $node->addChild('field');
         if ($value == 'true') {
             $value = '1';
         }
         if ($value == 'false') {
             $value = '0';
         }
         $field->addChild('value', trim($value->value));
         /*if(isset($value->attributes->required))
           $field->addChild('required', '');*/
         $field->addAttribute('var', $value->attributes->name);
         //$field->addAttribute('type', $value->attributes->type);
         //$field->addAttribute('label', $value->attributes->label);
     }
     $xml = $node->asXML();
     $doc = new \DOMDocument();
     $doc->loadXML($xml);
     $doc->formatOutput = true;
     return substr($doc->saveXML(), strpos($doc->saveXML(), "\n") + 1);
 }
Example #4
0
 public function Error($errorNo, $errorMessage = '')
 {
     header('Content-Type: text/xml; charset=utf8');
     Debug::LogEntry('audit', $errorMessage, 'RestXml', 'Error');
     // Roll back any open transactions if we are in an error state
     try {
         $dbh = PDOConnect::init();
         $dbh->rollBack();
     } catch (Exception $e) {
         Debug::LogEntry('audit', 'Unable to rollback');
     }
     // Output the error doc
     $xmlDoc = new DOMDocument('1.0');
     $xmlDoc->formatOutput = true;
     // Create the response node
     $rootNode = $xmlDoc->createElement('rsp');
     // Set the status to OK
     $rootNode->setAttribute('status', 'error');
     // Append the response node as the root
     $xmlDoc->appendChild($rootNode);
     // Create the error node
     $errorNode = $xmlDoc->createElement('error');
     $errorNode->setAttribute('code', $errorNo);
     $errorNode->setAttribute('message', $errorMessage);
     // Add the error node to the document
     $rootNode->appendChild($errorNode);
     // Log it
     Debug::LogEntry('audit', $xmlDoc->saveXML());
     // Return it as a string
     return $xmlDoc->saveXML();
 }
Example #5
0
 protected function pre_save(&$object)
 {
     $errors = array();
     libxml_use_internal_errors(TRUE);
     $cleaned = array();
     foreach ($object['registry'] as $section => $xml) {
         $dom = new DOMDocument('1.0');
         $dom->formatOutput = FALSE;
         if (strlen(trim($xml)) == 0) {
             kohana::log('debug', 'Section: ' . $section . ' Empty XML');
             unset($cleaned[$section]);
             continue;
         }
         try {
             if ($dom->loadXML('<root>' . trim($xml) . '</root>')) {
                 $cleaned[$section] = trim(str_replace('<?xml version="1.0"?>', '', $dom->saveXML()));
                 kohana::log('debug', 'Section: ' . $section . ' Cleaned XML: ' . $dom->saveXML());
                 continue;
             } else {
                 $errors[] = ucfirst($section);
             }
         } catch (Exception $e) {
             $errors[] = ucfirst($section);
         }
     }
     if (count($errors) > 0) {
         throw new Exception('Please correct the XML errors in these sections: ' . implode(', ', $errors));
     }
     $object['registry'] = $cleaned;
     kohana::log('debug', 'Successfully validated XML');
     parent::pre_save($object);
 }
 public function debugOutput()
 {
     $this->doc->preserveWhiteSpace = false;
     $this->doc->formatOutput = true;
     echo CHtml::encode($this->doc->saveXML());
     die;
 }
    /**
     * Copy ServiceConfiguration over to build directory given with target path
     * and modify some of the settings to point to development settings.
     *
     * @param string $targetPath
     * @return void
     */
    public function copyForDeployment($targetPath, $development = true)
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->loadXML($this->dom->saveXML());
        $xpath = new \DOMXpath($dom);
        $xpath->registerNamespace('sc', $dom->lookupNamespaceUri($dom->namespaceURI));
        $settings = $xpath->evaluate('//sc:ConfigurationSettings/sc:Setting[@name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"]');
        foreach ($settings as $setting) {
            if ($development) {
                $setting->setAttribute('value', 'UseDevelopmentStorage=true');
            } else {
                if (strlen($setting->getAttribute('value')) === 0) {
                    if ($this->storage) {
                        $setting->setAttribute('value', sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s', $this->storage['accountName'], $this->storage['accountKey']));
                    } else {
                        throw new \RuntimeException(<<<EXC
ServiceConfiguration.csdef: Missing value for
'Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString'.

You have to modify the app/azure/ServiceConfiguration.csdef to contain
a value for the diagnostics connection string or better configure
'windows_azure_distribution.diagnostics.accountName' and
'windows_azure_distribution.diagnostics.accountKey' in your
app/config/config.yml

If you don't want to enable diagnostics you should delete the
connection string elements from ServiceConfiguration.csdef file.
EXC
);
                    }
                }
            }
        }
        $dom->save($targetPath . '/ServiceConfiguration.cscfg');
    }
Example #8
0
function Write($title1, $title2, $author1, $author2, $publisher1, $publisher2)
{
    $books = array();
    $books[] = array('title' => $title1, 'author' => $author1, 'publisher' => $publisher1);
    $books[] = array('title' => $title2, 'author' => $author2, 'publisher' => $publisher2);
    $dom = new DOMDocument();
    $dom->formatOutput = true;
    $r = $dom->createElement("books");
    $dom->appendChild($r);
    foreach ($books as $book) {
        $b = $dom->createElement("book");
        $author = $dom->createElement("author");
        $author->appendChild($dom->createTextNode($book['author']));
        $b->appendChild($author);
        $title = $dom->createElement("title");
        $title->appendChild($dom->createTextNode($book['title']));
        $b->appendChild($title);
        $publisher = $dom->createElement("publisher");
        $publisher->appendChild($dom->createTextNode($book['publisher']));
        $b->appendChild($publisher);
        $r->appendChild($b);
    }
    global $diretorio;
    $fileSave = rand(100000000, 900000000) . ".xml";
    $dir_fileSave = $diretorio . $fileSave;
    $fp = fopen($dir_fileSave, "a");
    $escreve = fwrite($fp, $dom->saveXML());
    fclose($fp);
    echo "<div style='min-height:100px;background-color:rgba(255,255,255,0.2);margin-top:15px;padding:5px;border:1px solid gray;margin-bottom:15px;'>";
    echo "<div style='font-weight:bold;color:yellow;'>Xml gerado com sucesso!<br/>Nome do arquivo: {$fileSave}</div>";
    echo "<pre style='color:yellow;'>" . $dom->saveXML() . "</pre>";
    echo "</div>";
}
 /**
  * Load XML file
  *
  * @param string $filepath
  * @return void
  */
 protected function loadFile($filepath)
 {
     $this->xmlDoc = new \DOMDocument('1.0', 'utf-8');
     $this->xmlDoc->load($filepath);
     // @TODO: oliver@typo3.org: I guess this is not required here
     $this->xmlDoc->saveXML();
 }
 /**
  * test testGetProperties method
  */
 public function testGetProperties()
 {
     $body = '<?xml version="1.0" encoding="utf-8"?>
              <propfind xmlns="DAV:">
                 <prop>
                     <getlastmodified xmlns="DAV:"/>
                     <getcontentlength xmlns="DAV:"/>
                     <resourcetype xmlns="DAV:"/>
                     <getetag xmlns="DAV:"/>
                     <id xmlns="http://owncloud.org/ns"/>
                 </prop>
              </propfind>';
     $request = new Sabre\HTTP\Request(array('REQUEST_METHOD' => 'PROPFIND', 'REQUEST_URI' => '/remote.php/webdav/' . Tinebase_Core::getUser()->accountDisplayName, 'HTTP_DEPTH' => '0'));
     $request->setBody($body);
     $this->server->httpRequest = $request;
     $this->server->exec();
     //var_dump($this->response->body);
     $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status);
     $responseDoc = new DOMDocument();
     $responseDoc->loadXML($this->response->body);
     //$responseDoc->formatOutput = true; echo $responseDoc->saveXML();
     $xpath = new DomXPath($responseDoc);
     $xpath->registerNamespace('owncloud', 'http://owncloud.org/ns');
     $nodes = $xpath->query('//d:multistatus/d:response/d:propstat/d:prop/owncloud:id');
     $this->assertEquals(1, $nodes->length, $responseDoc->saveXML());
     $this->assertNotEmpty($nodes->item(0)->nodeValue, $responseDoc->saveXML());
 }
Example #11
0
 function loadSX()
 {
     $xml = simplexml_load_file($this->_xml);
     $newDoc = new DOMDocument();
     $products = $newDoc->createElement("Allitems");
     foreach ($xml as $product) {
         $domDoc = new DOMDocument();
         $domDoc->loadXML($product->asXML());
         $x = $domDoc->documentElement;
         if (!$domDoc->schemaValidate($this->_xsd)) {
             $errors = libxml_get_errors();
             foreach ($errors as $error) {
                 //print libxml_display_error($error);
             }
             libxml_clear_errors();
         } else {
             print "validation successful\n";
             $item = $newDoc->createElement("Item");
             $i = 1;
             foreach ($x->childNodes as $ele) {
                 if (!$ele instanceof DOMElement) {
                     continue;
                 }
                 $nodeData = $newDoc->createElement(trim($ele->nodeName), $ele->nodeValue);
                 $item->appendChild($nodeData);
             }
             $products->appendChild($item);
             $newDoc->appendChild($products);
             $newDoc->formatOutput = true;
             print $newDoc->saveXML();
         }
     }
     print_r($newDoc->saveXML());
 }
 /**
  * Recuperer la configuration au format XML.
  */
 public function saveXML()
 {
     $existing = array();
     $attributes = $this->domdocument->getElementsByTagName('attribute');
     foreach ($attributes as $attribute) {
         $existing[$attribute->getAttribute('name')] = $attribute;
     }
     if ($this->domdocument->getElementsByTagName('config')->item(0) == null) {
         $root = $this->domdocument->createElement('config');
         $this->domdocument->appendChild($root);
     } else {
         $root = $this->domdocument->getElementsByTagName('config')->item(0);
     }
     foreach ($this->config as $attribute => $value) {
         if (array_key_exists($attribute, $existing)) {
             $node = $existing[$attribute];
         } else {
             $node = $this->domdocument->createElement('attribute');
             $root->appendChild($node);
             $node->setAttribute('name', $attribute);
         }
         $node->setAttribute('value', $value);
     }
     $configNodes = $root->getElementsByTagName('attribute');
     foreach ($configNodes as $node) {
         if (!array_key_exists($node->getAttribute('name'), $this->config)) {
             $root->removeChild($node);
         }
     }
     $out = $this->domdocument->saveXML();
     return $out;
 }
Example #13
0
 /**
  * @param DOMNode $node
  */
 public function export(DOMNode $node = null)
 {
     if ($node === null) {
         return $this->_document->saveXML();
     } else {
         return $this->_document->saveXML($node);
     }
 }
Example #14
0
 /**
  * Dumps a single Schema model into an XML formatted version.
  *
  * @param  Schema  $schema                The schema object
  * @param  boolean $doFinalInitialization Whether or not to validate the schema
  * @return string
  */
 public function dumpSchema(Schema $schema, $doFinalInitialization = true)
 {
     $rootNode = $this->document->createElement('app-data');
     $this->document->appendChild($rootNode);
     foreach ($schema->getDatabases($doFinalInitialization) as $database) {
         $this->appendDatabaseNode($database, $rootNode);
     }
     return trim($this->document->saveXML());
 }
Example #15
0
 protected function finaliseStoreData()
 {
     // Write DOM to file
     $filename = $this->info("clean_store_name") . '-products.xml';
     $io = new Varien_Io_File();
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $this->getPath()));
     $io->write($filename, $this->_dom->saveXML());
     $io->close();
 }
function prettyPrint($result, $file)
{
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($result);
    $dom->formatOutput = true;
    //call function to write request/response in file
    outputWriter($file, $dom->saveXML());
    return $dom->saveXML();
}
 /**
  * Load XML file
  *
  * @param string $filepath
  * @return void
  */
 protected function loadFile($filepath)
 {
     // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
     $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
     $this->xmlDoc = new \DOMDocument('1.0', 'utf-8');
     $this->xmlDoc->loadXML(file_get_contents($filepath));
     libxml_disable_entity_loader($previousValueOfEntityLoader);
     // @TODO: oliver@typo3.org: I guess this is not required here
     $this->xmlDoc->saveXML();
 }
Example #18
0
 /**
  * Generate nice and sweet XML
  *
  * @see SimpleXMLElement::asXML()
  */
 public function asXML($filename = null)
 {
     $dom = new DOMDocument('1.0');
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     $dom->loadXML(parent::asXML());
     if ($filename) {
         return (bool) file_put_contents($filename, $dom->saveXML());
     }
     return $dom->saveXML();
 }
 /**
  * Generates an XML string from a Root config object, including all settings (global, shop, payment, protect)
  *
  * @api
  *
  * @param Payone_Settings_Data_ConfigFile_Root $config
  * @return mixed @see SimpleXMLElement::asXml()
  */
 public function generate(Payone_Settings_Data_ConfigFile_Root $config)
 {
     // @todo wandelt anhand Shop "gruppiert" um und fügt mehrere Shops umwandlungen zusammen in ein config-root
     $this->dom = new DOMDocument('1.0', 'UTF-8');
     $root = $this->appendElement($this->dom, $config->getKey());
     foreach ($config->getShop() as $key => $value) {
         $shop = $this->mapShop($value, $root);
     }
     $this->dom->formatOutput = true;
     $xmlString = $this->dom->saveXML();
     return $xmlString;
 }
Example #20
0
 /**
  * Returns the xml structure the writer
  * will use
  *
  * @return string
  */
 public function getXml()
 {
     $suites = $this->interpreter->flattenCases();
     $root = $this->getSuiteRoot($suites);
     foreach ($suites as $suite) {
         $snode = $this->appendSuite($root, $suite);
         foreach ($suite->cases as $case) {
             $cnode = $this->appendCase($snode, $case);
         }
     }
     return $this->document->saveXML();
 }
 /**
  * Get any value
  * @uses \DOMDocument::loadXML()
  * @uses \DOMDocument::hasChildNodes()
  * @uses \DOMDocument::saveXML()
  * @uses \DOMNode::item()
  * @uses \Ews\StructType\EwsConfigurationRequestDetailsType::setAny()
  * @param bool $asString true: returns XML string, false: returns \DOMDocument
  * @return \DOMDocument|null
  */
 public function getAny($asString = true)
 {
     if (!empty($this->any) && !$this->any instanceof \DOMDocument) {
         $dom = new \DOMDocument('1.0', 'UTF-8');
         $dom->formatOutput = true;
         if ($dom->loadXML($this->any)) {
             $this->setAny($dom);
         }
         unset($dom);
     }
     return $asString && $this->any instanceof \DOMDocument && $this->any->hasChildNodes() ? $this->any->saveXML($this->any->childNodes->item(0)) : $this->any;
 }
 public function actionRenderSitemap()
 {
     header('Content-type: text/xml');
     if (craft()->cache->get('sitemap')) {
         return print craft()->cache->get('sitemap');
     }
     $this->createUrlSet();
     $this->addSections();
     $data = $this->dom->saveXML();
     print $data;
     craft()->cache->add('sitemap', $data, 60 * 60 * 24);
 }
 /**
  * Save FB2 file
  * @param string $path
  */
 public function save($path = '')
 {
     if ($this->fictionBook instanceof FictionBook) {
         self::$FB2DOM = new \DOMDocument("1.0", "UTF-8");
         self::$FB2DOM->preserveWhiteSpace = FALSE;
         self::$FB2DOM->formatOutput = TRUE;
         $this->fictionBook->buildXML();
         self::$FB2DOM->schemaValidate("./XSD/FB2.2/FictionBook.xsd");
         //$domDoc->schemaValidate("./XSD/FB2.0/FictionBook2.xsd");
         self::$FB2DOM->save($path);
         echo self::$FB2DOM->saveXML();
     }
 }
 /**
  * Wrap a CAS 2.0 XML response and output it as a string.
  *
  * @return string CAS 2.0+ server response as an XML string.
  */
 public function prepare()
 {
     $root = $this->createElement('serviceResponse');
     if (!empty($this->response)) {
         $root->appendChild($this->response);
     }
     // Removing all child nodes from response document:
     while ($this->document->firstChild) {
         $this->document->removeChild($this->document->firstChild);
     }
     $this->document->appendChild($root);
     return $this->document->saveXML();
 }
Example #25
0
 /**
  * Dumps the service container as an XML string.
  *
  * @param array $options An array of options
  *
  * @return string An xml string representing of the service container
  *
  * @api
  */
 public function dump(array $options = array())
 {
     $this->document = new \DOMDocument('1.0', 'utf-8');
     $this->document->formatOutput = true;
     $container = $this->document->createElementNS('http://symfony.com/schema/dic/services', 'container');
     $container->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
     $container->setAttribute('xsi:schemaLocation', 'http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd');
     $this->addParameters($container);
     $this->addServices($container);
     $this->document->appendChild($container);
     $xml = $this->document->saveXML();
     $this->document = null;
     return $xml;
 }
 /**
  * test testGetProperties method
  */
 public function testGetProperties()
 {
     $body = '<?xml version="1.0" encoding="utf-8"?>
              <propfind xmlns="DAV:">
                 <prop>
                     <default-alarm-vevent-date xmlns="urn:ietf:params:xml:ns:caldav"/>
                     <default-alarm-vevent-datetime xmlns="urn:ietf:params:xml:ns:caldav"/>
                     <default-alarm-vtodo-date xmlns="urn:ietf:params:xml:ns:caldav"/>
                     <default-alarm-vtodo-datetime xmlns="urn:ietf:params:xml:ns:caldav"/>
                 </prop>
              </propfind>';
     $request = new Sabre\HTTP\Request(array('REQUEST_METHOD' => 'PROPFIND', 'REQUEST_URI' => '/calendars/' . Tinebase_Core::getUser()->contact_id, 'HTTP_DEPTH' => '0'));
     $request->setBody($body);
     $this->server->httpRequest = $request;
     $this->server->exec();
     //var_dump($this->response->body);
     $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status);
     $responseDoc = new DOMDocument();
     $responseDoc->loadXML($this->response->body);
     //$responseDoc->formatOutput = true; echo $responseDoc->saveXML();
     $xpath = new DomXPath($responseDoc);
     $xpath->registerNamespace('cal', 'urn:ietf:params:xml:ns:caldav');
     $nodes = $xpath->query('//d:multistatus/d:response/d:propstat/d:prop/cal:default-alarm-vevent-datetime');
     $this->assertEquals(1, $nodes->length, $responseDoc->saveXML());
     $this->assertNotEmpty($nodes->item(0)->nodeValue, $responseDoc->saveXML());
     $nodes = $xpath->query('//d:multistatus/d:response/d:propstat/d:prop/cal:default-alarm-vevent-date');
     $this->assertEquals(1, $nodes->length, $responseDoc->saveXML());
     $this->assertNotEmpty($nodes->item(0)->nodeValue, $responseDoc->saveXML());
     $nodes = $xpath->query('//d:multistatus/d:response/d:propstat/d:prop/cal:default-alarm-vtodo-datetime');
     $this->assertEquals(1, $nodes->length, $responseDoc->saveXML());
     $this->assertNotEmpty($nodes->item(0)->nodeValue, $responseDoc->saveXML());
     $nodes = $xpath->query('//d:multistatus/d:response/d:propstat/d:prop/cal:default-alarm-vtodo-date');
     $this->assertEquals(1, $nodes->length, $responseDoc->saveXML());
     $this->assertNotEmpty($nodes->item(0)->nodeValue, $responseDoc->saveXML());
 }
 /**
  * Respond to Ecopayz confirming or rejecting the payment.
  *
  * One of the following status codes:
  * - InvalidRequest
  * - OK
  * - Confirmed
  * - Cancelled
  *
  * @param  string $status           The ecopayz status code
  * @param  int    $errorCode        The merchant error code
  * @param  string $errorDescription The merchant error description
  * @return string response
  */
 public function createResponse($status, $errorCode, $errorDescription)
 {
     $document = new \DOMDocument('1.0', 'utf-8');
     $document->formatOutput = false;
     $response = $document->appendChild($document->createElement('SVSPurchaseStatusNotificationResponse'));
     $result = $response->appendChild($document->createElement('TransactionResult'));
     $result->appendChild($document->createElement('Description', $errorDescription));
     $result->appendChild($document->createElement('Code', $errorCode));
     $response->appendChild($document->createElement('Status', $status));
     $authentication = $response->appendChild($document->createElement('Authentication'));
     $checksum = $authentication->appendChild($document->createElement('Checksum', $this->getMerchantPassword()));
     $checksum->nodeValue = $this->calculateXmlChecksum($document->saveXML());
     return $document->saveXML();
 }
Example #28
0
 public function run()
 {
     $log = new Stream('php://stdout');
     /** @var Config $config */
     $config = Di::getDefault()->getShared('config');
     $expireDate = new DateTime('now', new DateTimeZone('UTC'));
     $expireDate->modify('+1 day');
     $sitemap = new DOMDocument("1.0", "UTF-8");
     $sitemap->formatOutput = true;
     $urlset = $sitemap->createElement('urlset');
     $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
     $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
     $baseUrl = $config->get('site')->url;
     $url = $sitemap->createElement('url');
     $url->appendChild($sitemap->createElement('loc', $baseUrl));
     $url->appendChild($sitemap->createElement('changefreq', 'daily'));
     $url->appendChild($sitemap->createElement('priority', '1.0'));
     $urlset->appendChild($url);
     $karmaSql = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies';
     $parametersPosts = ['conditions' => 'deleted != 1', 'columns' => "id, slug, modified_at, {$karmaSql} AS karma", 'order' => 'karma DESC'];
     $posts = Posts::find($parametersPosts);
     $parametersKarma = ['column' => $karmaSql, 'conditions' => 'deleted != 1'];
     $karma = Posts::maximum($parametersKarma);
     $modifiedAt = new DateTime('now', new DateTimeZone('UTC'));
     foreach ($posts as $post) {
         $modifiedAt->setTimestamp($post->modified_at);
         $postKarma = $post->karma / ($karma + 100);
         $url = $sitemap->createElement('url');
         $href = trim($baseUrl, '/') . '/discussion/' . $post->id . '/' . $post->slug;
         $url->appendChild($sitemap->createElement('loc', $href));
         $valuePriority = $postKarma > 0.7 ? sprintf("%0.1f", $postKarma) : sprintf("%0.1f", $postKarma + 0.25);
         $url->appendChild($sitemap->createElement('priority', $valuePriority));
         $url->appendChild($sitemap->createElement('lastmod', $modifiedAt->format('Y-m-d\\TH:i:s\\Z')));
         $urlset->appendChild($url);
     }
     $sitemap->appendChild($urlset);
     $adapter = new Local(dirname(dirname(__FILE__)) . '/public');
     $filesystem = new Filesystem($adapter);
     if ($filesystem->has('sitemap.xml')) {
         $result = $filesystem->update('sitemap.xml', $sitemap->saveXML() . PHP_EOL);
     } else {
         $result = $filesystem->write('sitemap.xml', $sitemap->saveXML() . PHP_EOL);
     }
     if ($result) {
         $log->info('The sitemap.xml was successfully updated');
     } else {
         $log->error('Failed to update the sitemap.xml file');
     }
 }
Example #29
0
/**
 * Implements hook_feeds_xpathparser_filter_domnode().
 *
 * Allows arbitrary manipulation of the feed item being processed while it is
 * still a DOMNode.
 *
 * This hook can also be used to skip parsing of a specific feed item by
 * returning TRUE.
 *
 * @param DOMNode $node
 *   The feed item being parsed, as a dom node.
 * @param DOMDocument $document
 *   The entire XML/HTML document being parsed.
 * @param FeedsSource $source
 *   The feed source being imported.
 *
 * @return bool
 *   Returns TRUE if the dom node should be skipped.
 */
function hook_feeds_xpathparser_filter_domnode(DOMNode $node, DOMDocument $document, FeedsSource $source)
{
    if (my_module_node_is_bad($node)) {
        return TRUE;
    }
    // To print out the raw XML.
    $debug = $document->saveXML($node);
    // For HTML.
    if (version_compare(phpversion(), '5.3.6', '>=')) {
        $debug = $document->saveHTML($node);
    } else {
        $debug = $document->saveXML($node, LIBXML_NOEMPTYTAG);
    }
    drupal_set_message($debug);
}
 /**
  * Transform the input XML based on C14n XML Exclusive Canonicalization rules
  *
  * @throws Exception
  * @param string $strXMLData The input XML
  * @return string The output XML
  */
 public function transform($strXMLData)
 {
     $dom = new DOMDocument();
     $dom->loadXML($strXMLData);
     if ($strXMLData == NULL) {
         SimpleSAML\Logger::debug("NOXML: " . $dom->saveXML());
     } else {
         SimpleSAML\Logger::debug("XMLcan: " . $dom->saveXML());
     }
     if (method_exists($dom, 'C14N')) {
         return $dom->C14N(true, false);
     }
     SimpleSAML\Logger::debug("This transform requires the C14N() method to exist in the DOM extension");
     throw new Exception('This transform requires the C14N() method to exist in the DOM extension');
 }