/**
  * @throws     BuildException
  */
 public function main()
 {
     if (!$this->getDatabaseName()) {
         throw new BuildException("The databaseName attribute (defined in propel.project property) is required for schema reverse engineering", $this->getLocation());
     }
     //(not yet supported) $this->log("schema : " . $this->dbSchema);
     //DocumentTypeImpl docType = new DocumentTypeImpl(null, "database", null,
     //       "http://jakarta.apache.org/turbine/dtd/database.dtd");
     $this->doc = new DOMDocument('1.0', 'utf-8');
     $this->doc->formatOutput = true;
     // pretty printing
     $this->doc->appendChild($this->doc->createComment("Autogenerated by " . get_class($this) . " class."));
     try {
         $database = $this->buildModel();
         if ($this->validatorBits !== self::VALIDATORS_NONE) {
             $this->addValidators($database);
         }
         $database->appendXml($this->doc);
         $this->log("Writing XML to file: " . $this->xmlSchema->getPath());
         $out = new FileWriter($this->xmlSchema);
         $xmlstr = $this->doc->saveXML();
         $out->write($xmlstr);
         $out->close();
     } catch (Exception $e) {
         $this->log("There was an error building XML from metadata: " . $e->getMessage(), Project::MSG_ERR);
         return false;
     }
     $this->log("Schema reverse engineering finished");
 }
 /**
  * Add document comment for formatting
  *
  * @param string $element            
  * @param string $comment            
  */
 protected function appendFormatComment(string $element, string $comment)
 {
     if ($this->format_output) {
         $com = $this->docObj->createComment($comment);
         $this->{$element}->appendChild($com);
     }
 }
 public function convert($mailchimp)
 {
     $vars = array('*|MC:SUBJECT|*' => '<?php echo $this->getSubject() ?>', '*|ARCHIVE|*' => '<?php echo $this->getViewInBrowserUrl() ?>', '*|CURRENT_YEAR|*' => '<?php echo date("Y") ?>', '*|UNSUB|*' => '<?php echo $this->getUnsubscribeUrl() ?>', '*|FACEBOOK:PROFILEURL|*' => '<?php echo $this->getFacebookUrl() ?>', '*|TWITTER:PROFILEURL|*' => '<?php echo $this->getTwitterUrl() ?>', '*|LIST:COMPANY|*' => '<?php echo $this->getStoreName() ?>', '*|LIST:DESCRIPTION|*' => '', '*|HTML:LIST_ADDRESS_HTML|*' => '*****@*****.**', '*|IF:REWARDS|* *|HTML:REWARDS|*' => '', '*|FORWARD|*' => '', '/*@editable*/' => '', '*|UPDATE_PROFILE|*' => '', 'mc:repeatable' => '', 'mc:allowtext' => '', 'mc:hideable' => '', 'mc:allowdesigner' => '', '*|IFNOT:ARCHIVE_PAGE|*' => '', '*|END:IF|*' => '', 'mc:edit' => 'mcedit');
     foreach ($vars as $old => $new) {
         $mailchimp = str_replace($old, $new, $mailchimp);
     }
     $dom = new DOMDocument();
     $dom->recover = true;
     $dom->strictErrorChecking = false;
     @$dom->loadHTML($mailchimp);
     $xpath = new DomXpath($dom);
     $items = $xpath->query('//*[@mcedit]');
     foreach ($items as $mcedit) {
         $area = 'area.' . $mcedit->getAttribute('mcedit');
         if ($area == 'area.monkeyrewards') {
             $mcedit->parentNode->removeChild($mcedit);
             continue;
         }
         $mcedit->removeAttribute('mcedit');
         $a = $dom->createComment('<?php echo $this->area("' . $area . '"); ?>');
         // $b = $dom->createComment('{{/ivar}}');
         $mcedit->parentNode->insertBefore($a, $mcedit);
         // $mcedit->parentNode->insertBefore($b);
     }
     $dom->formatOutput = true;
     $dom->preserveWhitespace = false;
     $html = $dom->saveHTML();
     $html = str_replace('%7B', '{', $html);
     $html = str_replace('%7D', '}', $html);
     $html = str_replace('%20', ' ', $html);
     $html = preg_replace('/mc:label="[a-zA-Z0-9_]*"/', '', $html);
     $html = preg_replace('/mc:variant="[^"]*"/', '', $html);
     $html = str_replace('%24', '$', $html);
     return $html;
 }
 /**
  * @see Renderable::render()
  */
 public function render(\DOMDocument $domDocument)
 {
     $domElement = $domDocument->createElement("script");
     if ($this->text) {
         $scriptComment = $domDocument->createComment($this->text);
         $domElement->appendChild($scriptComment);
     }
     return $domElement;
 }
Example #5
0
 /**
  * Append header comments to the DOM document
  */
 protected function do_header_comments()
 {
     /* Array of translated comment lines */
     $lines = array(__('This is a code snippets export file generated by the Code Snippets WordPress plugin.', 'code-snippets'), 'https://wordpress.org/plugins/code-snippets', __('To import these snippets a WordPress site follow these steps:', 'code-snippets'), __('1. Log in to that site as an administrator.', 'code-snippets'), __('2. Install the Code Snippets plugin using the directions provided at the above link.', 'code-snippets'), __("3. Go to 'Tools: Import' in the WordPress admin panel.", 'code-snippets'), __('4. Click on the "Code Snippets" importer in the list', 'code-snippets'), __('5. Upload this file using the form provided on that page.', 'code-snippets'), __('6. Code Snippets will then import all of the snippets and associated information contained in this file into your site.', 'code-snippets'), __("7. You will then have to visit the 'Snippets: Manage' admin menu and activate desired snippets.", 'code-snippets'));
     /* Add each line as a comment element */
     foreach ($lines as $line) {
         $comment = $this->dom->createComment(" {$line} ");
         $this->dom->appendChild($comment);
     }
     /* Build a generator line, like the WordPress export files */
     $gen = sprintf('generator="Code Snippets/%s" created="%s"', CODE_SNIPPETS_VERSION, date('Y-m-d H:i'));
     /* Run the generator line through the standard WordPress filter */
     $type = 'code_snippets_export';
     $gen = apply_filters("get_the_generator_{$type}", $gen, $type);
     /* Add it to the file as a comment */
     $gen = $this->dom->createComment(" {$gen} ");
     $this->dom->appendChild($gen);
 }
Example #6
0
 /**
  * Add comment
  *
  * @param string $data
  */
 public function add_comment($data)
 {
     $n = $this->node ? new self($this->owner) : $this;
     $e = $this->doc->createComment($data);
     if (!$this->node) {
         $n->node = $this->node = $this->doc->appendChild($e);
     } else {
         $n->node = $this->node->appendChild($e);
     }
     unset($e);
     return $n;
 }
Example #7
0
 /**
  * Append assets
  *
  * @param array $assets            
  * @return void
  */
 public function appendAssets(array $assets)
 {
     if (!empty($assets)) {
         if ($this->format_output) {
             $com = $this->docObj->createComment('');
             $this->scene->appendChild($com);
         }
         foreach ($assets as $asset) {
             $this->appendAsset($asset);
         }
         $this->scene->appendChild($this->assets);
     }
 }
 protected function on_create(DOMDocument &$doc, $rootmanifestnode = null, $nmanifestID = null)
 {
     $doc->formatOutput = true;
     $doc->preserveWhiteSpace = true;
     $this->manifestID = is_null($nmanifestID) ? cc_helpers::uuidgen('M_') : $nmanifestID;
     $mUUID = $doc->createAttribute('identifier');
     $mUUID->nodeValue = $this->manifestID;
     if (is_null($rootmanifestnode)) {
         if (!empty($this->_generator)) {
             $comment = $doc->createComment($this->_generator);
             $doc->appendChild($comment);
         }
         $rootel = $doc->createElementNS($this->ccnamespaces['imscc'], 'manifest');
         $rootel->appendChild($mUUID);
         $doc->appendChild($rootel);
         //add all namespaces
         foreach ($this->ccnamespaces as $key => $value) {
             if ($key != 'lom') {
                 $dummy_attr = $key . ":dummy";
                 $doc->createAttributeNS($value, $dummy_attr);
             }
         }
         // add location of schemas
         $schemaLocation = '';
         foreach ($this->ccnsnames as $key => $value) {
             $vt = empty($schemaLocation) ? '' : ' ';
             $schemaLocation .= $vt . $this->ccnamespaces[$key] . ' ' . $value;
         }
         $aSchemaLoc = $doc->createAttributeNS($this->ccnamespaces['xsi'], 'xsi:schemaLocation');
         $aSchemaLoc->nodeValue = $schemaLocation;
         $rootel->appendChild($aSchemaLoc);
     } else {
         $rootel = $doc->createElementNS($this->ccnamespaces['imscc'], 'imscc:manifest');
         $rootel->appendChild($mUUID);
     }
     $metadata = $doc->createElementNS($this->ccnamespaces['imscc'], 'metadata');
     $schema = $doc->createElementNS($this->ccnamespaces['imscc'], 'schema', 'IMS Common Cartridge');
     $schemaversion = $doc->createElementNS($this->ccnamespaces['imscc'], 'schemaversion', $this->ccversion);
     $metadata->appendChild($schema);
     $metadata->appendChild($schemaversion);
     $rootel->appendChild($metadata);
     if (!is_null($rootmanifestnode)) {
         $rootmanifestnode->appendChild($rootel);
     }
     $organizations = $doc->createElementNS($this->ccnamespaces['imscc'], 'organizations');
     $rootel->appendChild($organizations);
     $resources = $doc->createElementNS($this->ccnamespaces['imscc'], 'resources');
     $rootel->appendChild($resources);
     return true;
 }
Example #9
0
 public function reverse()
 {
     if (!$this->getDatabaseName()) {
         throw new BuildException('The databaseName attribute is required for schema reverse engineering');
     }
     $this->xml = new \DOMDocument('1.0', 'utf-8');
     $this->xml->formatOutput = true;
     // pretty printing
     $this->xml->appendChild($this->xml->createComment("Autogenerated by " . get_class($this) . " class."));
     try {
         $database = $this->buildModel();
         $database->appendXml($this->xml);
         $file = $this->getWorkingDirectory() . DIRECTORY_SEPARATOR . $this->getSchemaName() . '.xml';
         $this->log("Writing XML file to " . $file);
         file_put_contents($file, $this->xml->saveXML());
     } catch (\Exception $e) {
         $this->log(sprintf('<error>There was an error building XML from metadata: %s</error>', $e->getMessage()));
         return false;
     }
     return true;
 }
Example #10
0
}
/**
 * exportHelper object to help us in the exporting process...
*/
$exportHelper = new exportHelper($exportCourse);
/**
 * comment to be inserted as first line of XML document
*/
$commentStr = "Exported From " . PORTAL_NAME . " v" . ADA_VERSION;
// create a dom document with encoding utf8
$domtree = new DOMDocument('1.0', ADA_CHARSET);
$domtree->preserveWhiteSpace = false;
$domtree->formatOutput = true;
// generate and add comment, if any
if (isset($commentStr)) {
    $domtree->appendChild($domtree->createComment($commentStr));
    unset($commentStr);
}
// create the root element of the xml tree
$xmlRoot = $domtree->createElement("ada_export");
$xmlRoot->setAttribute("exportDate", date('r'));
// append it to the document created
$xmlRoot = $domtree->appendChild($xmlRoot);
foreach ($nodesToExport as $course_id => $nodeList) {
    // need an Import/Export DataHandler
    $dh = AMAImpExportDataHandler::instance(MultiPort::getDSN($_SESSION['sess_selected_tester']));
    $course_data = $dh->get_course($course_id);
    if (!empty($course_data) && !AMA_DB::isError($course_data)) {
        // create node for current course
        $XMLcourse = $domtree->createElement('modello_corso');
        $XMLcourse->setAttribute('exportedId', $course_id);
Example #11
0
 private function exportData($aaExportPageGroups)
 {
     $oDoc = new DOMDocument("1.0", "UTF-8");
     //put information as comment
     $sComment = "";
     $sComment .= $this->t_("xmlcomment_info") . "\n";
     $sComment .= ANWIKI_WEBSITE . "\n\n";
     $sComment .= $this->t_("xmlcomment_time", array("time" => Anwi18n::dateTime(time()))) . "\n";
     $sComment .= $this->t_("xmlcomment_version", array("version" => ANWIKI_VERSION_NAME)) . "\n";
     $sComment .= $this->t_("xmlcomment_user", array("user" => AnwCurrentSession::getUser()->getLogin())) . "\n";
     $sComment .= $this->t_("xmlcomment_from", array("url" => self::globalCfgUrlRoot())) . "\n\n";
     $sComment .= $this->t_("xmlcomment_contents") . "\n";
     //list exported contents as comment
     foreach ($aaExportPageGroups as $amPageGroup) {
         foreach ($amPageGroup['PAGES'] as $oPage) {
             $sPageTime = Anwi18n::dateTime($oPage->getTime());
             $sComment .= ' * ' . $oPage->getName() . " (" . $oPage->getLang() . ") (" . $sPageTime . ")\n";
         }
     }
     $sCommentSeparator = "\n**************************************************\n";
     $sComment = " " . $sCommentSeparator . $sComment . $sCommentSeparator . " ";
     $oCommentNode = $oDoc->createComment($sComment);
     $oDoc->appendChild($oCommentNode);
     //end comment
     //<anwexport time="" origin="">
     $oRootNode = $oDoc->createElement(self::XMLTAG_ROOT);
     $oRootNode->setAttribute("time", time());
     $oRootNode->setAttribute("from", AnwXml::xmlFileAttributeEncode(self::globalCfgUrlRoot()));
     $oRootNode->setAttribute("version_id", ANWIKI_VERSION_ID);
     $oRootNode->setAttribute("version_name", AnwXml::xmlFileAttributeEncode(ANWIKI_VERSION_NAME));
     $oDoc->appendChild($oRootNode);
     foreach ($aaExportPageGroups as $amPageGroup) {
         $oPageGroup = $amPageGroup['GROUP'];
         $sContentClassName = $oPageGroup->getContentClass()->getName();
         //<anwpagegroup>
         $oPageGroupNode = $oDoc->createElement(self::XMLTAG_PAGEGROUP);
         $oPageGroupNode->setAttribute("contentclass", AnwXml::xmlFileAttributeEncode($sContentClassName));
         foreach ($amPageGroup['PAGES'] as $oPage) {
             //add comment
             $sPageTime = Anwi18n::dateTime($oPage->getTime());
             $sComment = $oPage->getName() . " (" . $oPage->getLang() . ") (" . $sPageTime . ") (" . $oPageGroup->getContentClass()->getLabel() . "/" . $sContentClassName . ")";
             //$sComment = " \n*\n* ".$sComment."\n*\n ";
             $sCommentSeparator = "\n**************************************************\n";
             $sComment = " \n\n" . $sCommentSeparator . $sComment . $sCommentSeparator . " ";
             $oCommentNode = $oDoc->createComment($sComment);
             $oPageGroupNode->appendChild($oCommentNode);
             //end comment
             //using a CDATA node to preserve source breaklines :-)
             //$sPageContent = $oPage->getContent()->toXml();
             //$oPageContentNode = $oDoc->createCDATASection($sPageContent);
             $oContentNodeDoc = $oPage->getContent()->toXml()->documentElement;
             //here we got a <doc> node
             $oPageContentNodeDoc = $oDoc->importNode($oContentNodeDoc, true);
             //<anwpage name="" lang="" time="">
             $oPageNode = $oDoc->createElement(self::XMLTAG_PAGE);
             $oPageNode->setAttribute("name", AnwXml::xmlFileAttributeEncode($oPage->getName()));
             $oPageNode->setAttribute("lang", AnwXml::xmlFileAttributeEncode($oPage->getLang()));
             $oPageNode->setAttribute("time", $oPage->getTime());
             //we need to do this to squeeze the unwanted <doc> node in
             //WARNING - special loop ! childs are getting modified...
             while ($oChildNode = $oPageContentNodeDoc->childNodes->item(0)) {
                 $oPageNode->appendChild($oChildNode);
             }
             $oPageGroupNode->appendChild($oPageNode);
         }
         $oRootNode->appendChild($oPageGroupNode);
     }
     $sReturn = AnwUtils::xmlDumpNode($oRootNode);
     // even if final XML structure may be broken due to undeclared namespaces used in content,
     // we let raw content as it is for better compatibility in later versions.
     // $sReturn = AnwXml::prepareXmlValueToXml($sReturn);
     return $sReturn;
 }
             )
         );
     } else {
         $indexes[$indexName]['columns'][$indexColumn] = array(
             'key' => $indexColumn,
             'length' => $indexColumnLength,
             'collation' => $indexColumnCollation,
             'null' => $indexColumnNull
         );
     }
 }
 if (!empty($indexes)) {
     $xpdo->log(xPDO::LOG_LEVEL_INFO, "Generating XML for index elements: " . print_r($indexes, true));
     $fragment = $schema->createDocumentFragment();
     $fragment->appendChild($schema->createTextNode("\n        "));
     $fragment->appendChild($schema->createComment("Element indexes automatically generated by script: {$scriptTitle}"));
     $fragment->appendChild($schema->createTextNode("\n"));
     foreach ($indexes as $indexName => $index) {
         $indexElement = $schema->createElement('index');
         $indexElement->appendChild($schema->createTextNode("\n        "));
         foreach ($index['attributes'] as $attrKey => $attrVal) {
             $indexElement->setAttribute($attrKey, $attrVal);
         }
         foreach ($index['columns'] as $columnKey => $column) {
             $columnElement = $schema->createElement('column');
             foreach ($column as $colAttrKey => $colAttrVal) {
                 $columnElement->setAttribute($colAttrKey, $colAttrVal);
             }
             $indexElement->appendChild($schema->createTextNode("    "));
             $indexElement->appendChild($columnElement);
             $indexElement->appendChild($schema->createTextNode("\n        "));
Example #13
0
 public function testRecursiveSerialize()
 {
     $ns1 = 'tests://test/';
     $ns2 = 'tests://test_more/';
     $xmlDoc = new DOMDocument('1.0', 'UTF-8');
     $root = $xmlDoc->createElementNS($ns1, 'root');
     $sub1 = $xmlDoc->createElementNS($ns1, 'sub1');
     $sub1_1 = $xmlDoc->createElementNS($ns1, 'sub1_1');
     $cdata1_1 = $xmlDoc->createCDATASection('test text');
     $sub2 = $xmlDoc->createElementNS($ns2, 'sub2');
     $sub2_1 = $xmlDoc->createElementNS($ns1, 'sub2_1');
     $comment2_1 = $xmlDoc->createComment('test comment');
     $xmlDoc->appendChild($root);
     $root->appendChild($sub1);
     $sub1->appendChild($sub1_1);
     $sub1_1->appendChild($cdata1_1);
     $root->appendChild($sub2);
     $sub2->appendChild($sub2_1);
     $sub2_1->appendChild($comment2_1);
     // Because recursiveSerialize is not forced to use ns1 and ns2 as namespace prefixes, this test is a bit awkward. But it works for now, so let's just ignore it :)
     $this->assertSame('<ns1:root xmlns:ns1="tests://test/" xmlns:ns2="tests://test_more/"><ns1:sub1><ns1:sub1_1>test text</ns1:sub1_1></ns1:sub1><ns2:sub2><ns1:sub2_1><!--test comment--></ns1:sub2_1></ns2:sub2></ns1:root>', DAV::recursiveSerialize($root), 'DAV::recursiveSerialize() should return correct XML');
 }
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         $doc = new DOMDocument();
         $doc->version = '1.0';
         $doc->encoding = 'ISO-8859-1';
         $comment_elt = $doc->createComment('Generated by FormatiX.Eu ');
         $doc->appendChild($comment_elt);
         $note_elt = $doc->createElement('trendy');
         $doc->appendChild($note_elt);
         $skuids = $this->getRequest()->getParam('sku');
         $model = Mage::getModel('catalog/product');
         //getting product model
         $skuidarr = explode(",", $skuids);
         foreach ($skuidarr as $sku) {
             $item_elt = $doc->createElement('item');
             $doc->appendChild($item_elt);
             $productid = $model->getIdBySku($sku);
             $product = Mage::getModel('catalog/product')->load($productid);
             $product->getData();
             $pid = $product->getId();
             $productname = $product->getShortDescription();
             $price = $product->getPrice();
             //$producturl =$product->getProductUrl();
             $producturl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . $product->url_path;
             $imageurl = $product->getImageUrl();
             $sprice = $product->getSpecialPrice();
             //$description=$product->getShortDescription();
             $productname = str_replace("&", "&amp;", $productname);
             // Create to/from/heading/body elements
             $id_elt = $doc->createElement('id', $pid);
             $name_elt = $doc->createElement('name', $productname);
             $price_elt = $doc->createElement('price', $price);
             $url_elt = $doc->createElement('producturl', $producturl);
             $imageurl_elt = $doc->createElement('image', $imageurl);
             $sprice_elt = $doc->createElement('specialprice', $sprice);
             $descri_elt = $doc->createElement('description', $productname);
             // Specify that thos newly created elements are 'unique and trendy' children
             $note_elt->appendChild($item_elt);
             $item_elt->appendChild($id_elt);
             $item_elt->appendChild($name_elt);
             $item_elt->appendChild($price_elt);
             $item_elt->appendChild($url_elt);
             $item_elt->appendChild($imageurl_elt);
             $item_elt->appendChild($sprice_elt);
             $item_elt->appendChild($descri_elt);
         }
         // Beautify
         $doc->formatOutput = true;
         // Display the XML content we just created
         $doc->saveXML();
         // Save this to topseller.xml
         $doc->save('trendy.xml');
         if (isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
             try {
                 /* Starting upload */
                 $uploader = new Varien_File_Uploader('filename');
                 // Any extention would work
                 $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                 $uploader->setAllowRenameFiles(false);
                 // Set the file upload mode
                 // false -> get the file directly in the specified folder
                 // true -> get the file in the product like folders
                 //	(file.jpg will go in something like /media/f/i/file.jpg)
                 $uploader->setFilesDispersion(false);
                 // We set media as the upload dir
                 $path = Mage::getBaseDir('media') . DS;
                 $uploader->save($path, $_FILES['filename']['name']);
             } catch (Exception $e) {
             }
             //this way the name is saved in DB
             $data['filename'] = $_FILES['filename']['name'];
         }
         $model = Mage::getModel('trendy/trendy');
         $model->setData($data)->setId($this->getRequest()->getParam('id'));
         try {
             if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
                 $model->setCreatedTime(now())->setUpdateTime(now());
             } else {
                 $model->setUpdateTime(now());
             }
             $model->save();
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('trendy')->__('Item was successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('trendy')->__('Unable to find item to save'));
     $this->_redirect('*/*/');
 }
Example #15
0
 static function comment($comment)
 {
     end(self::$parentNodes)->appendChild(self::$domDocument->createComment($comment));
 }
Example #16
0
 private function parse($content)
 {
     $extension = $this->getExtension();
     $path = $this->getPath();
     $parseVariable = $this->isParseVariable();
     $options = $this->getOptions();
     /*
      * Everything inside a <% IGNORE %>...<% IGNOER_END %> block
      * will be ignored from being parsed
      */
     $ignoreBlock = array();
     $content = preg_replace_callback('@(<% *IGNORE *%>(.*?)<% *IGNORE_END *%>)@s', function ($matches) use(&$ignoreBlock) {
         $ignoreBlock[] = $matches[2];
         return '<!--SimPHPfyIgnoreBlock#' . count($ignoreBlock) . '#SimPHPfyIgnoreBlock-->';
     }, $content);
     /* 
      * Code block is in the form <% code %>, code can be any valid
      * PHP statements.
      * A special form of code block is <%= ${variable_name} %> 
      * which is equivalent to echo a variable
      * 
      * Every code snippet is stored inside the $codeBlock Array to
      * prevent variable parsing from corrupting the whole document
      */
     $codeBlock = array();
     $content = preg_replace_callback('@(<%= *(.*?[^\\\\]) *%>)@s', function ($matches) use(&$codeBlock) {
         $codeSnippet = $matches[2];
         if (preg_match('@^\\${([a-zA-Z_\\x7f-\\xff][\\[\\]\'"a-zA-Z0-9_\\x7f-\\xff*]*(\\[[\'"][a-zA-Z0-9_\\x7f-\\xff*]*[\'"]\\])*)}$@', $codeSnippet)) {
             $codeSnippet = "<?php if (isset({$codeSnippet})) { echo {$codeSnippet}; } ?>";
         } elseif (preg_match('@^\\$([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff*]*(\\[[\'"][a-zA-Z0-9_\\x7f-\\xff*]*[\'"]\\])*)$@', $codeSnippet)) {
             $codeSnippet = "<?php if (isset({$codeSnippet})) { echo {$codeSnippet}; } ?>";
         }
         $codeBlock[] = $codeSnippet;
         return '<!--SimPHPfyCodeBlock#' . count($codeBlock) . '#SimPHPfyCodeBlock-->';
     }, $content);
     $content = preg_replace_callback('@(<% *(.*?[^\\\\]) *%>)@s', function ($matches) use(&$codeBlock, $path) {
         $codeSnippet = $matches[2];
         if ($codeSnippet == 'IGNORE_MINIFY' || $codeSnippet == 'IGNORE_MINIFY_END') {
             return $matches[0];
         } elseif (preg_match('@^render.*$@', $codeSnippet)) {
             /*
              * Layout rendering
              */
             $codeSnippet = '<' . $codeSnippet . ' />';
             $dom = new DOMDocument();
             @$dom->loadXML($codeSnippet);
             /*
              * extract the attributes of render tag
              */
             $render = $dom->getElementsByTagName('render')->item(0);
             // <% render file='header.html' directory='' static='' dynamic='' %>
             $file = $directory = $dynamic = $format = $parsedDirectory = '';
             if (($file = $render->getAttribute('file')) == '') {
                 throw new InvalidTemplateException(array($path, 'Missing `file` for layout rendering'));
             }
             $directory = ASSERT;
             $parsedDirectory = TEMP_VIEW . 'Assert' . DS;
             if ($dirAttr = $render->getAttribute('directory') != '') {
                 $directory .= $dirAttr . DS;
                 $parsedDirectory = TEMP_VIEW . $dirAttr . DS;
             }
             /*
              * If `controller` attribute is spceified, the layout is 
              * inside the View/:Controller
              */
             if (($controllerAttr = $render->getAttribute('controller')) != '') {
                 $directory = VIEW . $controllerAttr . DS;
                 $parsedDirectory = TEMP_VIEW . $controllerAttr . DS;
             }
             if (($staticAttr = $render->getAttribute('static')) != '') {
                 $dynamic = !$staticAttr;
             }
             /*
              * `dynamic` attribute always overwrite `static` attribute, 
              * thought it is not recommended to set both attributes
              */
             if (($dynamicAttr = $render->getAttribute('dynamic')) != '') {
                 $dynamic = $dynamicAttr;
             }
             /*
              * The behaviour of render. When a render code is parsed, 
              * should it return a URL to the rendered file or directly 
              * render that file, possiblities: 'url' | 'direct'
              * default: 'direct'
              */
             if (($behaviourAttr = $render->getAttribute('behaviour')) == '') {
                 $behaviour = 'direct';
             } else {
                 $behaviour = $behaviourAttr;
             }
             $format = $render->getAttribute('format');
             $optionArray = 'array(';
             $i = 0;
             if ($format != '') {
                 $optionArray .= "'format' => {$format}";
                 $i++;
             }
             if ($parsedDirectory != '') {
                 $optionArray .= ($i++ == 0 ? '' : ', ') . "'parsedDirectory' => '{$parsedDirectory}'";
             }
             if ($dynamic !== '') {
                 $optionArray .= ($i++ == 0 ? '' : ', ') . '\'dynamic\' => ' . ($dynamic ? 'TRUE' : 'FALSE');
             } else {
                 $dynamic = TRUE;
             }
             $optionArray .= ')';
             $extension = substr(strrchr($file, "."), 1);
             if ($behaviour == 'direct' || $dynamic) {
                 if ($extension == 'html') {
                     $codeSnippet = "<?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?>";
                 } elseif ($extension == 'js') {
                     $codeSnippet = "<script><?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?></script>";
                 } elseif ($extension == 'css') {
                     $codeSnippet = "<style><?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?></style>";
                 }
             } else {
                 if ($extension == 'html') {
                     $codeSnippet = "<?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?>";
                 } else {
                     $optionArray = substr($optionArray, 0, -1) . ($i++ == 0 ? '' : ', ') . '\'relative\' => TRUE)';
                     if ($extension == 'js') {
                         $codeSnippet = "<script src=\"<?php echo Template::render('{$file}', '{$directory}', {$optionArray}); ?>\"></script>";
                     } elseif ($extension == 'css') {
                         $codeSnippet = "<link rel=\"stylesheet\" href=\"<?php include Template::render('{$file}', '{$directory}', {$optionArray}); ?>\" />";
                     }
                 }
             }
         } else {
             $codeSnippet = '<?php ' . str_replace('\\%>', '%>', $codeSnippet) . ' ?>';
         }
         $codeBlock[] = $codeSnippet;
         return '<!--SimPHPfyCodeBlock#' . count($codeBlock) . '#SimPHPfyCodeBlock-->';
     }, $content);
     /* 
      * Perform HTML specificied parsing
      */
     if ($extension == 'html') {
         $htmlBlock = array();
         /* 
          * gurantee the form tag is not inside a comment by examining the 
          * DOM Tree instead of pure regular expression
          */
         $dom = new DOMDocument();
         @$dom->loadHTML($content);
         $forms = $dom->getElementsByTagName('form');
         for ($i = 0; $i < $forms->length; $i++) {
             /*
              * Re-create the DOM because the previous iteration have
              * changed the content of $content
              */
             $dom = new DOMDocument();
             @$dom->loadHTML($content);
             $form = $dom->getElementsByTagName('form')->item($i);
             if ($form->textContent == '') {
                 /*
                  * Create dummy block to make the form tag recognizable
                  */
                 $dummyString = '<!--SimPHPfyDummyBlock#' . $i . '#SimPHPfyDummyBlock-->';
                 $textNode = $dom->createTextNode($dummyString);
                 $form->appendChild($textNode);
                 $content = $dom->saveHTML();
                 $pattern = '@(< *form.*?>)(' . $dummyString . ')@';
             } else {
                 /*
                  * Save the form HTML content into the $htmlBlock
                  */
                 $htmlContent = '';
                 while ($form->hasChildNodes()) {
                     /*
                      * Loop through the child to skip the parent form tag
                      * from including into the stored $htmlBlock
                      */
                     $node = $form->childNodes->item(0);
                     $htmlContent .= $dom->saveXML($node);
                     $form->removeChild($node);
                 }
                 $htmlBlock[] = $htmlContent;
                 $commentNode = $dom->createComment('SimPHPfyHTMLBlock#' . count($htmlBlock) . '#SimPHPfyHTMLBlock');
                 $htmlBlockString = '<!--SimPHPfyHTMLBlock#' . count($htmlBlock) . '#SimPHPfyHTMLBlock-->';
                 $form->appendChild($commentNode);
                 $content = $dom->saveHTML();
                 $pattern = '@(< *form.*?>)(' . $htmlBlockString . ')@';
             }
             $content = preg_replace_callback($pattern, function ($matches) use($options, $path) {
                 $formDom = new DOMDocument();
                 @$formDom->loadHTML($matches[1]);
                 $formTags = @$formDom->getElementsByTagName('form');
                 $formTag = $formTags->item(0);
                 $controller = $action = '';
                 /*
                  * data-controller and data-action attributes determine which 
                  * controller and action the form should send to
                  * 
                  * A table of the possible values of data-* are as followed:
                  * data-controller  data-action     result
                  * String           String          $contoller/$action
                  * Omitted          String          :Controller/$action
                  * String           Omitted         Disallowed
                  * Omitted          Omitted         :Controller/:Action
                  */
                 if ($formTag->getAttribute('data-helper') == 'simphpfy') {
                     if ($formTag->getAttribute('data-controller') == '') {
                         if ($formTag->getAttribute('data-action') == '') {
                             if (isset($options['controller'])) {
                                 $controller = $options['controller']->getController();
                                 $action = $options['controller']->getAction();
                             } else {
                                 throw new InvalidTemplateException(array($path, 'missing controller and/or action for form helper'));
                             }
                         } else {
                             if (isset($options['controller'])) {
                                 $controller = $options['controller']->getController();
                                 $action = $formTag->getAttribute('data-action');
                             } else {
                                 throw new InvalidTemplateException(array($path, 'missing controller for form helper'));
                             }
                         }
                     } else {
                         if ($formTag->getAttribute('data-action') == '') {
                             throw new InvalidTemplateException(array($path, 'malformed form helper'));
                         } else {
                             $controller = $formTag->getAttribute('data-controller');
                             $action = $formTag->getAttribute('data-action');
                         }
                     }
                     if ($controller && $action) {
                         $actionAttr = DIRECTORY_PREFIX . $controller . DS . $action;
                         if (($id = $formTag->getAttribute('data-id')) != '') {
                             $actionAttr .= DS . $id;
                         }
                         $formTag->setAttribute('action', $actionAttr);
                     } else {
                         throw new InvalidTemplateException(array($path, 'malformed form helper'));
                     }
                     // check if method is PUT or DELETE
                     if ($formTag->getAttribute('data-method') != '') {
                         $method = strtoupper($formTag->getAttribute('data-method'));
                         if ($method == "PUT" || $method == "DELETE") {
                             $formTag->setAttribute('method', 'POST');
                         } elseif ($method == 'GET' || $method == 'POST') {
                             $formTag->setAttribute('method', $method);
                         }
                         $inputMethod = $formDom->createElement('input');
                         $inputMethod->setAttribute('type', 'hidden');
                         $inputMethod->setAttribute('name', '_method');
                         $inputMethod->setAttribute('value', $method);
                         $formTag->appendChild($inputMethod);
                     }
                     // remove <!DOCTYPE
                     $formDom->removeChild($formDom->doctype);
                     // remove <html><body></body></html>
                     $formDom->replaceChild($formDom->firstChild->firstChild->firstChild, $formDom->firstChild);
                     return str_replace('</form>', '', $formDom->saveHTML()) . $matches[2];
                 } else {
                     return $matches[0];
                 }
             }, $content);
         }
         $content = preg_replace_callback('@<!--SimPHPfyHTMLBlock#([0-9]+)#SimPHPfyHTMLBlock-->@', function ($matches) use($htmlBlock) {
             return $htmlBlock[(int) $matches[1] - 1];
         }, $content);
         $dom = new DOMDocument();
         @$dom->loadHTML($content);
         $this->parseInput($dom->getElementsByTagName('input'), $codeBlock);
         $this->parseInput($dom->getElementsByTagName('select'), $codeBlock);
         $this->parseInput($dom->getElementsByTagName('textarea'), $codeBlock);
         $content = $dom->saveHTML();
     }
     if ($parseVariable) {
         $content = preg_replace('@([^\\\\]|]^)\\${([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)}\\$@', '<?php echo $\\2; ?>', $content);
         $content = preg_replace('@([^\\\\]|^)\\$([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)\\$@', '<?php echo $\\2; ?>', $content);
     }
     $content = preg_replace_callback('@<!--SimPHPfyIgnoreBlock#([0-9]+)#SimPHPfyIgnoreBlock-->@', function ($matches) use($ignoreBlock) {
         return $ignoreBlock[(int) $matches[1] - 1];
     }, $content);
     $content = preg_replace_callback('@<!--SimPHPfyCodeBlock#([0-9]+)#SimPHPfyCodeBlock-->@', function ($matches) use($codeBlock) {
         return $codeBlock[(int) $matches[1] - 1];
     }, $content);
     $content = preg_replace('@<!--SimPHPfyDummyBlock#([0-9]+)#SimPHPfyDummyBlock-->@', '', $content);
     return $content;
 }
Example #17
0
/**
 * Find a tag by ID and append/replace content
 *
 * source: http://stackoverflow.com/a/17661043/1829145
 * Thanks to Rodolfo Buaiz (brasofilo)
 *
 * @param string $oDoc source html (passed by reference!)
 * @param string $s html code to insert
 * @param string $sId id of the tag to find
 * @param string $sHtml
 * @param boolean $bAppend append new code?
 * @param boolean $bInsert replace existing contents by the new source code?
 * @param boolean $bAddToOuter
 * @return boolean
 */
function brasofilo_suSetHtmlElementById(&$oDoc, &$s, $sId, $sHtml, $bAppend = false, $bInsert = false, $bAddToOuter = false)
{
    if (brasofilo_suIsValidString($s) && brasofilo_suIsValidString($sId)) {
        $bCreate = true;
        if (is_object($oDoc)) {
            if (!$oDoc instanceof DOMDocument) {
                return false;
            }
            $bCreate = false;
        }
        if ($bCreate) {
            $oDoc = new DOMDocument();
        }
        libxml_use_internal_errors(true);
        $oDoc->loadHTML($s);
        libxml_use_internal_errors(false);
        $oNode = $oDoc->getElementById($sId);
        if (is_object($oNode)) {
            $bReplaceOuter = !$bAppend && !$bInsert;
            $sId = uniqid('NVCMS_SHEBI-');
            $aId = array("<!-- {$sId} -->", "<!--{$sId}-->");
            if ($bReplaceOuter) {
                if (brasofilo_suIsValidString($sHtml)) {
                    $oNode->parentNode->replaceChild($oDoc->createComment($sId), $oNode);
                    $s = $oDoc->saveHtml();
                    $s = str_replace($aId, $sHtml, $oDoc->saveHtml());
                } else {
                    $oNode->parentNode->removeChild($oNode);
                    $s = $oDoc->saveHtml();
                }
                return true;
            }
            $bReplaceInner = $bAppend && $bInsert;
            $sThis = null;
            if (!$bReplaceInner) {
                $sThis = $oDoc->saveHTML($oNode);
                $sThis = ($bInsert ? $sHtml : '') . ($bAddToOuter ? $sThis : substr($sThis, strpos($sThis, '>') + 1, -(strlen($oNode->nodeName) + 3))) . ($bAppend ? $sHtml : '');
            }
            if (!$bReplaceInner && $bAddToOuter) {
                $oNode->parentNode->replaceChild($oDoc->createComment($sId), $oNode);
                $sId =& $aId;
            } else {
                $oNode->nodeValue = $sId;
            }
            $s = str_replace($sId, $bReplaceInner ? $sHtml : $sThis, $oDoc->saveHtml());
            return true;
        }
    }
    return false;
}
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         $doc = new DOMDocument();
         $doc->version = '1.0';
         $doc->encoding = 'ISO-8859-1';
         $comment_elt = $doc->createComment('Generated by FormatiX.Eu ');
         $doc->appendChild($comment_elt);
         $note_elt = $doc->createElement('mania');
         $doc->appendChild($note_elt);
         $skuids = $this->getRequest()->getParam('sku');
         $model = Mage::getModel('catalog/product');
         //getting product model
         $skuidarr = explode(",", $skuids);
         foreach ($skuidarr as $sku) {
             $item_elt = $doc->createElement('item');
             $doc->appendChild($item_elt);
             $productid = $model->getIdBySku($sku);
             $product = Mage::getModel('catalog/product')->load($productid);
             $product->getData();
             $pid = $product->getId();
             $productname = $product->getShortDescription();
             $price = $product->getPrice();
             //$producturl =$product->getProductUrl();
             $producturl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB) . $product->url_path;
             $imageurl = $product->getImageUrl();
             $sprice = $product->getSpecialPrice();
             //$description=$product->getShortDescription();
             $productname = str_replace("&", "&amp;", $productname);
             // Create to/from/heading/body elements
             $id_elt = $doc->createElement('id', $pid);
             $name_elt = $doc->createElement('name', $productname);
             $price_elt = $doc->createElement('price', $price);
             $url_elt = $doc->createElement('producturl', $producturl);
             $imageurl_elt = $doc->createElement('image', $imageurl);
             $sprice_elt = $doc->createElement('specialprice', $sprice);
             $descri_elt = $doc->createElement('description', $productname);
             // Specify that thos newly created elements are 'mania' children
             $note_elt->appendChild($item_elt);
             $item_elt->appendChild($id_elt);
             $item_elt->appendChild($name_elt);
             $item_elt->appendChild($price_elt);
             $item_elt->appendChild($url_elt);
             $item_elt->appendChild($imageurl_elt);
             $item_elt->appendChild($sprice_elt);
             $item_elt->appendChild($descri_elt);
         }
         // Beautify
         $doc->formatOutput = true;
         // Display the XML content we just created
         $doc->saveXML();
         // Save this to topseller.xml
         $doc->save('mania.xml');
         if (isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
             try {
                 /* Starting upload */
                 $uploader = new Varien_File_Uploader('filename');
                 // Any extention would work
                 $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                 $uploader->setAllowRenameFiles(false);
                 // Set the file upload mode
                 // false -> get the file directly in the specified folder
                 // true -> get the file in the product like folders
                 //	(file.jpg will go in something like /media/f/i/file.jpg)
                 $uploader->setFilesDispersion(false);
                 // We set media as the upload dir
                 $path = Mage::getBaseDir('media') . DS;
                 $uploader->save($path, $_FILES['filename']['name']);
             } catch (Exception $e) {
             }
             //this way the name is saved in DB
             $data['filename'] = $_FILES['filename']['name'];
         }
         $model = Mage::getModel('mania/mania');
         $model->setData($data)->setId($this->getRequest()->getParam('id'));
         // code for creating feed for clearance sale starts here
         $base = Mage::getBaseDir('base');
         $file = $base . '/clearance_sale_feed.xml';
         if (file_exists($file)) {
             unlink($file);
         }
         //$products->getSelect()->limit(5);
         $doc1 = new DOMDocument();
         $doc1->formatOutput = true;
         $doc1->preserveWhiteSpace = true;
         $productsX = $doc1->createElement("products");
         $doc1->appendChild($productsX);
         $skuids = $this->getRequest()->getParam('sku');
         //echo 	$skuids; exit;
         //$model = Mage::getModel('catalog/product') ;//getting product model
         $skuidarr = explode(",", $skuids);
         $products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('sku', array('in' => $skuidarr))->addAttributeToFilter('status', 1)->addAttributeToFilter('visibility', 4)->load();
         //echo count($products); exit;
         foreach ($products as $_product) {
             //echo $_product->getEntityId(); exit;
             $data = Mage::getModel('catalog/product')->load($_product->getEntityId());
             $category_ids = $_product->getCategoryIds();
             $firstCategoryId = $category_ids[1];
             $secondCategoryId = $category_ids[2];
             $thirdCategoryId = $category_ids[3];
             $category1 = Mage::getModel('catalog/category')->load($firstCategoryId);
             $category2 = Mage::getModel('catalog/category')->load($secondCategoryId);
             $category3 = Mage::getModel('catalog/category')->load($thirdCategoryId);
             $product = $doc1->createElement("product");
             $name = $doc1->createElement("Product_Name");
             $name->appendChild($doc1->createTextNode(trim($_product->getName())));
             $product->appendChild($name);
             //description
             $description = $doc1->createElement("Description");
             $description->appendChild($doc1->createTextNode(trim($_product->getDescription())));
             $product->appendChild($description);
             //Actual price
             $price = $doc1->createElement("Actual_Price");
             $price->appendChild($doc1->createTextNode(trim($_product->getPrice())));
             $product->appendChild($price);
             //Discount Price
             $specialprice = $doc1->createElement("Discount_Price");
             $specialprice->appendChild($doc1->createTextNode(trim($_product->getSpecialPrice())));
             $product->appendChild($specialprice);
             //product URL
             $prodURL = $doc1->createElement("URL");
             $prodURL->appendChild($doc1->createTextNode(trim($_product->getProductUrl())));
             $product->appendChild($prodURL);
             //image URL
             $prodImage = $doc1->createElement("Prod_Image");
             $prodImage->appendChild($doc1->createTextNode(trim($data->getImageUrl())));
             $product->appendChild($prodImage);
             //category name
             $catname = $doc1->createElement("Category_Name");
             $catname->appendChild($doc1->createTextNode(trim($category1->getName())));
             $product->appendChild($catname);
             //sub-category name
             $subcatname = $doc1->createElement("SubCategory_Name");
             $subcatname->appendChild($doc1->createTextNode(trim($category2->getName())));
             $product->appendChild($subcatname);
             //subsub-category name
             $subsubcatname = $doc1->createElement("SubSubCategory_Name");
             $subsubcatname->appendChild($doc1->createTextNode(trim($category3->getName())));
             $product->appendChild($subsubcatname);
             //brand
             $brand = $doc1->createElement("Brand");
             $brand->appendChild($doc1->createTextNode(trim($data->getAttributeText('brand'))));
             $product->appendChild($brand);
             //shipping price
             $shipprice = $doc1->createElement("Shipping_Price");
             $shipprice->appendChild($doc1->createTextNode("0"));
             $product->appendChild($shipprice);
             //shipping time
             $shiptime = $doc1->createElement("Shipping_Time");
             $shiptime->appendChild($doc1->createTextNode("3-4"));
             $product->appendChild($shiptime);
             //EMI
             $EMI = $doc1->createElement("EMI");
             $EMI->appendChild($doc1->createTextNode("No"));
             $product->appendChild($EMI);
             //COD
             $COD = $doc1->createElement("COD");
             $COD->appendChild($doc1->createTextNode("Yes"));
             $product->appendChild($COD);
             //STOCK
             $stock = $doc1->createElement("Stock");
             $stock->appendChild($doc1->createTextNode(trim(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getIsInStock())));
             $product->appendChild($stock);
             $productsX->appendChild($product);
         }
         file_put_contents($file, $doc1->saveXML());
         //clearance sale feed ends here
         try {
             if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
                 $model->setCreatedTime(now())->setUpdateTime(now());
             } else {
                 $model->setUpdateTime(now());
             }
             $model->save();
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('mania')->__('Item was successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('mania')->__('Unable to find item to save'));
     $this->_redirect('*/*/');
 }
Example #19
0
 /**
  * transform tasks 'workflow 01' to 'RecordMover'
  * will group tasks(01) with same period to a single task(02)
  *
  * @param base        $appbox
  * @param Application $app
  *
  * @return boolean
  */
 public function apply(base $appbox, Application $app)
 {
     $ttasks = [];
     $conn = $appbox->get_connection();
     $sql = 'SELECT task_id, active, name, class, settings
             FROM task2
             WHERE class=\'task_period_workflow01\'';
     if (($stmt = $conn->prepare($sql)) !== FALSE) {
         $stmt->execute();
         $ttasks = $stmt->fetchAll();
     }
     $stmt->closeCursor();
     $tdom = [];
     // key = period
     $taskstodel = [];
     foreach ($ttasks as $task) {
         $active = true;
         $warning = [];
         /*
          * migrating task 'workflow01'
          */
         $x = $task['settings'];
         if (false !== ($sx = simplexml_load_string($x))) {
             $period = (int) $sx->period;
             if (!array_key_exists('_' . $period, $tdom)) {
                 $dom = new DOMDocument('1.0', 'UTF-8');
                 $dom->formatOutput = true;
                 $dom->preserveWhiteSpace = false;
                 $ts = $dom->appendChild($dom->createElement('tasksettings'));
                 $ts->appendChild($dom->createElement('period'))->appendChild($dom->createTextNode(60 * $period));
                 $ts->appendChild($dom->createElement('logsql'))->appendChild($dom->createTextNode('1'));
                 $tasks = $ts->appendChild($dom->createElement('tasks'));
                 $tdom['_' . $period] = ['dom' => $dom, 'tasks' => $tasks];
             } else {
                 $dom =& $tdom['_' . $period]['dom'];
                 $tasks =& $tdom['_' . $period]['tasks'];
             }
             /*
              * migrating task 'workflow01'
              */
             if ($task['class'] === 'task_period_workflow01') {
                 $t = $tasks->appendChild($dom->createElement('task'));
                 $t->setAttribute('active', '0');
                 $t->setAttribute('name', 'imported from \'' . $task['name'] . '\'');
                 $t->setAttribute('action', 'update');
                 if ($sx->sbas_id) {
                     $sbas_id = trim($sx->sbas_id);
                     if ($sbas_id != '' && is_numeric($sbas_id)) {
                         $t->setAttribute('sbas_id', $sx->sbas_id);
                     } else {
                         $warning[] = sprintf("Bad sbas_id '%s'", $sbas_id);
                         $active = false;
                     }
                 } else {
                     $warning[] = sprintf("missing sbas_id");
                     $active = false;
                 }
                 // 'from' section
                 $from = $t->appendChild($dom->createElement('from'));
                 if ($sx->coll0) {
                     if (($coll0 = trim($sx->coll0)) != '') {
                         if (is_numeric($coll0)) {
                             $n = $from->appendChild($dom->createElement('coll'));
                             $n->setAttribute('compare', '=');
                             $n->setAttribute('id', $coll0);
                         } else {
                             $warning[] = sprintf("Bad (from) coll_id '%s'", $coll0);
                             $active = false;
                         }
                     }
                 }
                 if ($sx->status0 && trim($sx->status0) != '') {
                     $st = explode('_', trim($sx->status0));
                     if (count($st) == 2) {
                         $bit = (int) $st[0];
                         if ($bit >= 0 && $bit < 32 && ($st[1] == '0' || $st[1] == '1')) {
                             $from->appendChild($dom->createElement('status'))->setAttribute('mask', $st[1] . str_repeat('x', $bit - 1));
                         } else {
                             $warning[] = sprintf("Bad (from) status '%s'", trim($sx->status0));
                             $active = false;
                         }
                     } else {
                         $warning[] = sprintf("Bad (from) status '%s'", trim($sx->status0));
                         $active = false;
                     }
                 }
                 // 'to' section
                 $to = $t->appendChild($dom->createElement('to'));
                 if ($sx->coll1) {
                     if (($coll1 = trim($sx->coll1)) != '') {
                         if (is_numeric($coll1)) {
                             $n = $to->appendChild($dom->createElement('coll'));
                             $n->setAttribute('id', $coll1);
                         } else {
                             $warning[] = sprintf("Bad (to) coll_id '%s'", $coll1);
                             $active = false;
                         }
                     }
                 }
                 if ($sx->status1 && trim($sx->status1) != '') {
                     $st = explode('_', trim($sx->status1));
                     if (count($st) == 2) {
                         $bit = (int) $st[0];
                         if ($bit >= 0 && $bit < 32 && ($st[1] == '0' || $st[1] == '1')) {
                             $to->appendChild($dom->createElement('status'))->setAttribute('mask', $st[1] . str_repeat('x', $bit - 1));
                         } else {
                             $warning[] = sprintf("Bad (to) status '%s'", trim($sx->status1));
                             $active = false;
                         }
                     } else {
                         $warning[] = sprintf("Bad (to) status '%s'", trim($sx->status1));
                         $active = false;
                     }
                 }
                 if ($active && $task['active'] == '1') {
                     $t->setAttribute('active', '1');
                 }
                 foreach ($warning as $w) {
                     $t->appendChild($dom->createComment($w));
                 }
                 $taskstodel[] = $task['task_id'];
             }
         }
         if (count($taskstodel) > 0) {
             $conn->exec('DELETE FROM task2 WHERE task_id IN(' . implode(',', $taskstodel) . ')');
         }
     }
     /*
      * save new tasks
      */
     foreach ($tdom as $newtask) {
         $settings = $newtask['dom']->saveXML();
         $sxml = simplexml_load_string($settings);
         $period = $sxml->period ? (int) $sxml->period : 300;
         $task = new Task();
         $task->setName('Record mover')->setJobId('RecordMover')->setSettings($settings)->setPeriod($period)->setStatus(Task::STATUS_STARTED);
         $app['orm.em']->persist($task);
     }
     $app['orm.em']->flush();
     return true;
 }
Example #20
0
 private function end()
 {
     if (!$this->responseXML instanceof SimpleXMLElement) {
         throw new Exception("Response XML not provided");
     }
     if ($this->profile) {
         Zotero_DB::profileEnd($this->profileShard, false);
     }
     if ($this->responseCode) {
         switch ($this->responseCode) {
             case 201:
                 header("HTTP/1.1 201 Created");
                 break;
             default:
                 throw new Exception("Unsupported response code");
         }
     } else {
         $updated = (string) $this->responseXML->updated;
         if ($updated) {
             $updated = strtotime($updated);
             $ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
             $ifModifiedSince = strtotime($ifModifiedSince);
             if ($ifModifiedSince >= $updated) {
                 header('HTTP/1.1 304 Not Modified');
                 exit;
             }
             $lastModified = substr(date('r', $updated), 0, -5) . "GMT";
             header("Last-Modified: {$lastModified}");
         }
     }
     $xmlstr = $this->responseXML->asXML();
     $doc = new DOMDocument('1.0');
     $doc->loadXML($xmlstr);
     $doc->formatOutput = true;
     if ($this->queryParams['pprint']) {
         $ppdoc = new DOMDocument('1.0');
         // Zero-width spaces to push <feed> beyond Firefox's
         // feed auto-detection boundary
         $comment = $ppdoc->createComment("​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​");
         $ppdoc->appendChild($comment);
         $ppdoc->formatOutput = true;
         $rootElem = $doc->firstChild;
         $importedNode = $ppdoc->importNode($rootElem, true);
         $ppdoc->appendChild($importedNode);
         $doc = $ppdoc;
     }
     $xmlstr = $doc->saveXML();
     if ($this->queryParams['pprint']) {
         header("Content-Type: text/xml");
     } else {
         header("Content-Type: application/atom+xml");
     }
     echo $xmlstr;
     $this->logRequestTime();
     echo ob_get_clean();
     exit;
 }
Example #21
0
 /**
  * @param string $string or convertible to string
  *
  * @return Comment
  */
 public function createComment($string)
 {
     return parent::createComment(' ' . (string) $string . ' ');
 }
 /**
  * Creates a DOM document containing data for specified database.
  *
  * @param Database $database
  *
  * @return DOMDocument
  */
 private function createXMLDoc(Database $database)
 {
     $doc = new DOMDocument('1.0', 'utf-8');
     $doc->formatOutput = true;
     // pretty printing
     $doc->appendChild($doc->createComment("Created by PropelDataDumpTask."));
     $dsNode = $doc->createElement("dataset");
     $dsNode->setAttribute("name", "all");
     $doc->appendChild($dsNode);
     $platform = $this->getGeneratorConfig()->getConfiguredPlatform($this->conn);
     $this->log("Building DOM tree containing data from tables:");
     foreach ($database->getTables() as $tbl) {
         $this->log("\t+ " . $tbl->getName());
         $stmt = $this->getTableDataStmt($tbl->getName(), $platform);
         while ($row = $stmt->fetch()) {
             $rowNode = $doc->createElement($tbl->getPhpName());
             foreach ($tbl->getColumns() as $col) {
                 $cval = $row[$col->getName()];
                 if ($cval !== null) {
                     $rowNode->setAttribute($col->getPhpName(), iconv($this->dbEncoding, 'utf-8', $cval));
                 }
             }
             $dsNode->appendChild($rowNode);
             unset($rowNode);
         }
         unset($stmt);
     }
     return $doc;
 }
Example #23
0
function Save($n)
{
    switch ($n->getAttribute("format")) {
        case "xml":
            $xRes = new DOMDocument();
            for ($i = 0; $i < $n->childNodes->length; $i++) {
                if ($n->childNodes->item($i)->nodeName == "txs:comment" && $n->childNodes->item($i)->namespaceURI == "http://www.agencexml.com/txs") {
                    $xRes->appendChild($xRes->createComment($n->childNodes->item($i)->nodeValue));
                } else {
                    $xRes->appendChild($xRes->importNode($n->childNodes->item($i), true));
                }
            }
            $xRes->encoding = "UTF-8";
            /*
            $txsnodes = $xRes->getElementsByTagNameNS("http://www.agencexml.com/txs", "stylesheet");
            foreach($txsnodes as $txsnode) {
            	$replnode = $xRes->createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet");
            	for($j = 0; $j < $txsnode->attributes->length; $j++) {
            		$replnode->setAttributeNodeNS($txsnode->attributes->item($j));
            	}
            	for($j = 0; $j < $txsnode->childNodes->length; $j++) {
            		$replnode->appendChild($xRes->importNode($txsnode->childNodes->item($j), true));
            	}
            	$txsnode->parentNode->replaceChild($replnode, $txsnode);
            }
            */
            $txsnodes = $xRes->getElementsByTagNameNS("http://www.agencexml.com/txs", "include");
            foreach ($txsnodes as $txsnode) {
                $replnode = $xRes->createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:include");
                $nbattr = $txsnode->attributes->length;
                for ($j = 0; $j < $nbattr; $j++) {
                    $replnode->setAttributeNodeNS($xRes->importNode($txsnode->attributes->item(0)));
                }
                for ($j = 0; $j < $txsnode->childNodes->length; $j++) {
                    $replnode->appendChild($xRes->importNode($txsnode->childNodes->item($j), true));
                }
                $txsnode->parentNode->replaceChild($replnode, $txsnode);
            }
            $txsnodes = $xRes->getElementsByTagNameNS("http://www.agencexml.com/txs", "output");
            foreach ($txsnodes as $txsnode) {
                $replnode = $xRes->createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:output");
                $nbattr = $txsnode->attributes->length;
                for ($j = 0; $j < $nbattr; $j++) {
                    $replnode->setAttributeNodeNS($xRes->importNode($txsnode->attributes->item(0)));
                }
                for ($j = 0; $j < $txsnode->childNodes->length; $j++) {
                    $replnode->appendChild($xRes->importNode($txsnode->childNodes->item($j), true));
                }
                $txsnode->parentNode->replaceChild($replnode, $txsnode);
            }
            $txsnodes = $xRes->getElementsByTagNameNS("http://www.agencexml.com/txs", "comment");
            foreach ($txsnodes as $txsnode) {
                $txsnode->parentNode->replaceChild($xRes->createComment($txsnode->nodeValue), $txsnode);
            }
            //$xRes->save($n->getAttribute("filename"));
            $fp = fopen($n->getAttribute("filename"), "wb");
            fwrite($fp, "" . str_replace(" ", "&#xA0;", preg_replace("/<\\/xhtml:/sU", "</", preg_replace("/<xhtml:/sU", "<", preg_replace("/txs:stylesheet/sU", "xsl:stylesheet", $xRes->saveXML())))));
            fclose($fp);
            $empty = $n->ownerDocument->createTextNode("");
            $n->parentNode->replaceChild($empty, $n);
            break;
        case "text":
            $fp = fopen($n->getAttribute("filename"), "wb");
            fwrite($fp, $n->nodeValue);
            fclose($fp);
            $empty = $n->ownerDocument->createTextNode("");
            $n->parentNode->replaceChild($empty, $n);
            break;
            /*
            		case "email":
            			$smtpserver = $n->getAttribute("smtpserver");
            			$smtplogin = $n->getAttribute("login");
            			$smtppassword = $n->getAttribute("password");
            			for($i = 0; $i < $n->childNodes->length; $i++) {
            				$email = $n->childNodes->item($i);
            				$mail = new PHPMailer();
            				$mail->IsSMTP();
            				$mail->SMTPAuth = $smtplogin != "";
            				$mail->Host = $smtpserver;
            				$mail->Username = $smtplogin;
            				$mail->Password = $smtppassword;
            				$mail->From = $email->getAttribute("from");
            				$mail->Sender = $email->getAttribute("from");
            				$mail->FromName = $email->getAttribute("displayfrom");
            				if($email->getAttribute("mailer") != "") {
            					$mail->Version = $email->getAttribute("mailer");
            				}
            				if($email->getAttribute("readreceipt") == "true") {
            					$mail->ConfirmReadingTo = $email->getAttribute("from");
            				}
            				$mail->AddAddress($email->getAttribute("to"),$email->getAttribute("displayto"));
            				switch($email->getAttribute("priority")) {
            					case "high":
            						$mail->Priority = 1;
            						break;
            					case "low":
            						$mail->Priority = 5;
            						break;
            					default:
            						$mail->Priority = 3;
            						break;
            				}
            				$mail->Subject = $email->getAttribute("subject");
            				for($j = 0; $j < $email->childNodes->length; $j++) {
            					$emailview = $email->childNodes->item($j);
            					if($emailview->nodeName == "txs:emailview") {
            						$body = "body";
            						for($k = 0; $k < $emailview->childNodes->length; $k++) {
            							$emailviewchild = $emailview->childNodes->item($k);
            							switch($emailviewchild->nodeName) {
            								case "txs:emailbody":
            									switch($emailview->getAttribute("format")) {
            										case "text/html":
            											for($l = 0;$l < $emailviewchild->childNodes->length; $l++) {
            												$cur = $emailviewchild->childNodes->item($l);
            												if($cur->nodeType == XML_ELEMENT_NODE) {
            													$mail->IsHTML(true);
            													$xBody = new DOMDocument();
            													$xBody->loadXML("<dummy/>");
            													$xBody->documentElement->parentNode->replaceChild($xBody->importNode($cur, true), $xBody->documentElement);
            													$mail->Body = str_replace("<?xml version=\"1.0\"?>", "", str_replace("<default:", "<", str_replace("</default:", "</", str_replace(" xmlns:default=", " xmlns=", $xBody->saveXML()))));
            													break;
            												}
            											}
            											break;
            										case "text/plain":
            											$mail->AltBody = $emailviewchild->textContent;
            											break;
            									}
            									break;
            									case "txs:emailresource":
            										$mail->AddEmbeddedImage($emailviewchild->getAttribute("filename"),$emailviewchild->getAttribute("id"),"","base64",$emailviewchild->getAttribute("type"));
            										break;
            							}
            						}
            					}
            				}
            				$mail->Send();
            			}
            			$empty = $n->ownerDocument->createTextNode("");
            			$n->parentNode->replaceChild($empty, $n);
            			break;
            */
    }
}
Example #24
0
 /**
  * Creates a DOM document containing data for specified database.
  * @param Database $database
  * @return DOMDocument
  */
 private function createXMLDoc(Database $database)
 {
     $doc = new DOMDocument('1.0', 'utf-8');
     $doc->formatOutput = true;
     // pretty printing
     $doc->appendChild($doc->createComment("Created by data/dump/Control.tpl template."));
     $dsNode = $doc->createElement("dataset");
     $dsNode->setAttribute("name", "all");
     $doc->appendChild($dsNode);
     $this->log("Building DOM tree containing data from tables:");
     foreach ($database->getTables() as $tbl) {
         $this->log("\t+ " . $tbl->getName());
         $rs = $this->getTableDataRS($tbl->getName());
         while ($rs->next()) {
             $rowNode = $doc->createElement($tbl->getPhpName());
             foreach ($tbl->getColumns() as $col) {
                 $cval = $rs->get($col->getName());
                 if ($cval !== null) {
                     $rowNode->setAttribute($col->getPhpName(), iconv($this->dbEncoding, 'utf-8', $cval));
                 }
             }
             $dsNode->appendChild($rowNode);
             unset($rowNode);
         }
         $rs->close();
     }
     return $doc;
 }
Example #25
0
 /**
  * Create comment 
  * To prevent a parser error when the comment string contains this character 
  * sequence "--", This will insert a Soft Hyphen in between the two hyphens 
  * which will not cause the parser to error out.
  * 
  * @param string $value
  * 
  * @return object DOMComment
  */
 public function createComment($value)
 {
     // Keep a space either side of the comment.
     $value = ' ' . str_replace('--', '-' . chr(194) . chr(173) . '-', $value) . ' ';
     $comment = parent::createComment($value);
     return $comment;
 }
Example #26
0
}
function display_help()
{
    echo "\nUsage: addproblem.php [OPTION]... [FILE]\n\nWhere [FILE] is a single .tar.gz file having all the testdata in the\nright format. Note that even this is optional, if you do not specify\nan archive it is assumed that the the testdata has already been copied\nto the data/problems/\n\nOptions are (most options will be asked interactively if not specified\non commandline):\n  --id <id>         A unique problem identifier (e.g. SAMPLE)\n  --nick <nick>     A friendly name for this problem (e.g. 'A Sample Problem')\n  --contest <name>  The contest to which this problem should be added to.\n                    (Default: 'general')\n  --num-test-case n Number of test cases \n  --scores n,n,..,n A list of <num-test-cases> integers indicating the score\n                    for each testcase. Note that --scores should be used \n                    only after a --num-test-case.\n  --total-score     The total score for this problem. The points will be\n                    divided evenly between each test case. More convenient than\n                    using --scores.\n  --memory-limit m  Memory limit per execution (e.g. 64M, 1000K)\n  --cpu-limit       Time limit in seconds per exectution (e.g. 3,1.5)\n  --output-limit m  Limit the size of output produced by the user's program\n                    (e.g. 64M, 1000K)\n  --submission-limit n   Maximum number of submissions per user for this \n                         problem.\n  --checker         Location to the checker to be used for this problem.\n                    (See documentation for checker specification). The \n                    location of the checker should be given with relative to\n                    the backend directory.\n  --grading-style {ioi|opc} See documentation for details.\n  --only-update     Used to update the problem, if the problem was already\n                    added previously.\n  --use-sample      Instead of using input files in 0.in,1.in etc, use\n                    sample.0.in, sample.1.in etc. This makes it easy to keep\n                    both sample and final testdata in the same archive.\n  --force           Usually will be used with --only-update. The idea is to\n                    keep the user aware that file overwrites will happen and\n                    therefore you shouldn't make a mistake and provide the\n                    wrong problemid for instance.\n  --help            Display this help and exit.\n\n";
}
require_once "../config.inc";
require_once "lib/db.inc";
ob_implicit_flush(true);
$dom = new DOMDocument("1.0", "UTF-8");
$dom->formatOutput = TRUE;
$root = $dom->createElement("problem");
$dom->appendChild($root);
if (empty($id)) {
    $id = readline("Enter a unique problem ID: ");
}
$element = $dom->createComment("id is used for informative purposes only, " . "and does not overload the id stored in the database or as the current " . "filename.");
$root->appendChild($element);
$element = $dom->createElement("id", $id);
$root->appendChild($element);
if (!empty($archive)) {
    uncompress_archive($archive, $id);
}
if (!is_file(get_file_name("data/problems/{$id}/index.html"))) {
    echo "data/problems/{$id}/index.html does not exist. Aborting right now.\n";
    exit(1);
}
if (empty($nick)) {
    $nick = readline("Enter a nickname for the problem: ");
}
$element = $dom->createComment("nickname is also stored for informative purposes only.");
$root->appendChild($element);
Example #27
0
 public function createComment($comment)
 {
     return $this->_xml->createComment($comment);
 }
Example #28
0
 public function exportTopics(Application $app, Request $request)
 {
     $lng = $app['locale'];
     $obr = explode(';', $request->get('obr'));
     $t_lng = [];
     if ($request->get('ofm') == 'tofiles') {
         $t_lng = array_map(function ($code) {
             $lng_code = explode('_', $code);
             return $lng_code[0];
         }, array_keys($app['locales.available']));
     } else {
         $t_lng[] = $request->get('piv');
     }
     switch ($request->get('obrf')) {
         case 'from_itf_closable':
             $default_display = 'closed';
             $opened_display = 'opened';
             break;
         case 'from_itf_static':
             $default_display = 'closed';
             $opened_display = 'static';
             break;
         case 'all_opened_closable':
             $default_display = 'opened';
             $opened_display = '';
             break;
         case 'all_opened_static':
             $default_display = 'static';
             $opened_display = '';
             break;
         case 'all_closed':
             $default_display = 'closed';
             $opened_display = '';
             break;
     }
     $now = date('YmdHis');
     $lngs = [];
     try {
         $databox = $app['phraseanet.appbox']->get_databox((int) $request->get("bid"));
         if ($request->get("typ") == "TH") {
             $domth = $databox->get_dom_thesaurus();
         } else {
             $domth = $databox->get_dom_cterms();
         }
         if ($domth) {
             $xpathth = new \DOMXPath($domth);
             if ($request->get("id") == "T") {
                 $q = "/thesaurus";
             } elseif ($request->get("id") == "C") {
                 $q = "/cterms";
             } else {
                 $q = "//te[@id='" . $request->get("id") . "']";
             }
             if ($request->get('ofm') == 'toscreen') {
                 printf("<pre style='font-size: 12px;'>\n");
             }
             foreach ($t_lng as $lng) {
                 $dom = new \DOMDocument("1.0", "UTF-8");
                 $dom->standalone = true;
                 $dom->preserveWhiteSpace = false;
                 $dom->formatOutput = true;
                 $root = $dom->appendChild($dom->createElementNS('www.phraseanet.com', 'phraseanet:topics'));
                 $root->appendChild($dom->createComment($app->trans('thesaurus:: fichier genere le %date%', ['%date%' => $now])));
                 $root->appendChild($dom->createElement('display'))->appendChild($dom->createElement('defaultview'))->appendChild($dom->createTextNode($default_display));
                 $this->export0Topics($app, $xpathth->query($q)->item(0), $dom, $root, $lng, $request->get("srt"), $request->get("sth"), $request->get("sand"), $opened_display, $obr);
                 if ($request->get("ofm") == 'toscreen') {
                     $lngs[$lng] = str_replace(['&', '<', '>'], ['&amp;', '&lt;', '&gt;'], $dom->saveXML());
                 } elseif ($request->get("ofm") == 'tofiles') {
                     $fname = 'topics_' . $lng . '.xml';
                     @rename($app['root.path'] . '/config/topics/' . $fname, $app['root.path'] . '/config/topics/topics_' . $lng . '_BKP_' . $now . '.xml');
                     if ($dom->save($app['root.path'] . '/config/topics/' . $fname)) {
                         $lngs[$lng] = \p4string::MakeString($app->trans('thesaurus:: fichier genere : %filename%', ['%filename%' => $fname]));
                     } else {
                         $lngs[$lng] = \p4string::MakeString($app->trans('thesaurus:: erreur lors de l\'enregsitrement du fichier'));
                     }
                 }
             }
         }
     } catch (\Exception $e) {
     }
     return $app['twig']->render('thesaurus/export-topics.html.twig', ['lngs' => $lngs, 'ofm' => $request->get('ofm')]);
 }
Example #29
0
 /**
  * Visit single element in regular expression
  *
  * The return type of this method varies deping on the concrete visitor 
  * implementation
  * 
  * @param slRegularExpressionEmpty $element 
  * @return mixed
  */
 protected function visitEmpty(slRegularExpressionEmpty $element)
 {
     return $this->document->createComment('Empty regular expression');
 }
Example #30
0
 public function config_to_XML()
 {
     $array_classes = $this->GetListClasses();
     // Création fichier XML avec les données
     // Instance de la class DomDocument
     $doc = new DOMDocument();
     // Definition de la version et de l'encodage
     $doc->version = '1.0';
     $doc->encoding = 'UTF-8';
     $doc->formatOutput = true;
     // Ajout d'un commentaire a la racine
     $comment_elt = $doc->createComment(utf8_encode('Données de la Freebox Révolution - Boitier Server'));
     $doc->appendChild($comment_elt);
     $racine = $doc->createElement('freeboxOS');
     // Ajout la balise 'update' a la racine
     $version_elt = $doc->createElement('update', date("Y-m-d H:i"));
     $racine->appendChild($version_elt);
     foreach ($array_classes as $class_name) {
         $Classe_Elt = $doc->createElement($class_name);
         $class_methods = get_class_methods($class_name);
         $class = new $class_name($this);
         foreach ($class_methods as $method_name) {
             if (substr($method_name, 0, 3) === "Get") {
                 $r = new ReflectionMethod($class_name, $method_name);
                 $params = $r->getNumberOfParameters();
                 if ($params == 0) {
                     $datas = call_user_func(array($class, $method_name));
                     $Method_Elt = $doc->createElement($method_name);
                     DomArrayToXml($datas["result"], $doc, $Method_Elt);
                     $Classe_Elt->appendChild($Method_Elt);
                 }
             }
             $racine->appendChild($Classe_Elt);
         }
     }
     $doc->appendChild($racine);
     return $doc->saveXML();
 }