Example #1
1
 /**
  * @test
  */
 public function trimFromHTMLString()
 {
     $helper = new DOMHelper();
     $directory = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'htmlData' . DIRECTORY_SEPARATOR;
     $dom = new DOMDocument();
     $input = file_get_contents($directory . 'trimAfterString_input_1.html');
     // Si le marqueur n'existe pas, le texte est renvoyé intact
     $expected = str_replace("\n", "", $input);
     $actual = str_replace("\n", "", $helper->trimFromHTMLString($input, "{{XXXXXX}}"));
     $this->assertEquals(preg_replace('/\\s+/', '', $expected), preg_replace('/\\s+/', '', $actual));
     // Suppression simple
     $htmlHead = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><title>***</title></head><body>';
     $htmlFoot = '</body></html>';
     $actual = str_replace("\n", "", $helper->trimFromHTMLString($input, "{{LIRE_LA_SUITE}}"));
     $dom->loadHTML($htmlHead . file_get_contents($directory . 'trimAfterString_output_1.html') . $htmlFoot);
     $expected = $this->cleanTmpHTML(str_replace("\n", "", $dom->saveHTML()), $htmlHead, $htmlFoot);
     $this->assertEquals(preg_replace('/\\s+/', '', $expected), preg_replace('/\\s+/', '', $actual));
     // Suppression avec insertion d'un bouton "Lire la suite"
     $actual = str_replace("\n", "", $helper->trimFromHTMLString($input, "{{LIRE_LA_SUITE}}", "<button>Lire la suite</button>"));
     $dom->loadHTML($htmlHead . file_get_contents($directory . 'trimAfterString_output_2.html') . $htmlFoot);
     $expected = $this->cleanTmpHTML(str_replace("\n", "", $dom->saveHTML()), $htmlHead, $htmlFoot);
     $this->assertEquals(preg_replace('/\\s+/', '', $expected), preg_replace('/\\s+/', '', $actual));
     // Suppression avec insertion d'un texte et d'un bouton "Lire la suite"
     $actual = str_replace("\n", "", $helper->trimFromHTMLString($input, "{{LIRE_LA_SUITE}}", "Pour en savoir plus : <button>Lire la suite</button>"));
     $dom->loadHTML($htmlHead . file_get_contents($directory . 'trimAfterString_output_3.html') . $htmlFoot);
     $expected = $this->cleanTmpHTML(str_replace("\n", "", $dom->saveHTML()), $htmlHead, $htmlFoot);
     $this->assertEquals(preg_replace('/\\s+/', '', $expected), preg_replace('/\\s+/', '', $actual));
 }
Example #2
1
 /**
  *
  * @return string
  */
 public function getMessage()
 {
     if (empty($this->_jobTraining)) {
         return '';
     }
     $this->_dom = new DOMDocument();
     $classMessage = 'alert ';
     $divFluid = $this->_dom->createElement('div');
     $divMessage = $this->_dom->createElement('div');
     $divFluid->setAttribute('class', 'row-fluid');
     if ($this->_jobTraining->status != 1) {
         $classMessage .= 'alert-error';
         $iconClass = 'icon-remove-sign';
         $alertText = ' Atensaun ';
         $message = ' Job Training ' . ($this->_jobTraining->status == 2 ? 'Kansela' : 'Taka') . ' tiha ona, La bele halo Atualizasaun.';
     } else {
         $iconClass = 'icon-ok-sign';
         $classMessage .= 'alert-success';
         $alertText = '';
         $message = ' Job Training Loke, então bele halo Atualizasaun.';
     }
     $divMessage->setAttribute('class', $classMessage);
     $strong = $this->_dom->createElement('strong');
     $i = $this->_dom->createElement('i');
     $i->setAttribute('class', $iconClass);
     $strong->appendChild($i);
     $strong->appendChild($this->_dom->createTextNode($alertText));
     $divMessage->appendChild($strong);
     $divMessage->appendChild($this->_dom->createTextNode($message));
     $divFluid->appendChild($divMessage);
     $this->_dom->appendChild($divFluid);
     return $this->_dom->saveHTML();
 }
Example #3
0
 /**
  * @param \DOMDocument $dom
  * @param \DOMNode $node
  * @return string
  */
 protected static function saveHTMLExact(\DOMDocument $dom, \DOMNode $node)
 {
     if ($dom !== null && defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 50306) {
         return $dom->saveHTML($node);
     }
     return preg_replace(array("/^<!DOCTYPE.*?<body>/si", "#</body>.*</html>\$#si"), '', $dom->saveHTML());
 }
Example #4
0
 /**
  * @param $elements
  * @param $length
  *
  * @return array
  */
 protected function trimMarkup($elements, $length)
 {
     $markup = '';
     $textLength = 0;
     foreach ($elements as $element) {
         if ($element instanceof DOMText) {
             $textLength += strlen($element->nodeValue);
             $element->nodeValue = substr($element->nodeValue, 0, $length - $textLength);
             if ($textLength >= $length - 30) {
                 $element->nodeValue .= '...';
             }
             $markup .= $this->DOMDocument->saveHTML($element);
         } elseif ($element->firstChild instanceof DOMText) {
             $textLength += strlen($element->firstChild->nodeValue);
             $element->firstChild->nodeValue = substr($element->firstChild->nodeValue, 0, $length - $textLength);
             if ($textLength >= $length - 30) {
                 $element->firstChild->nodeValue .= '...';
             }
             $markup .= $this->DOMDocument->saveHTML($element);
         } else {
             $trimmed = $this->trimMarkup($element, $length - $textLength);
             if ($trimmed['finished']) {
                 return array('finished' => true, 'markup' => $markup . $trimmed['markup']);
             }
             $markup .= $trimmed['markup'];
             $textLength += $trimmed['length'];
         }
         if ($textLength >= $length - 30) {
             return array('finished' => true, 'markup' => $markup, 'length' => $length);
         }
     }
     return array('finished' => false, 'markup' => $markup, 'length' => $length);
 }
Example #5
0
 /**
  * Render the DOM document
  *
  * @access public
  * @return string
  */
 public function Render() : string
 {
     /* ------------------------------------------------------------------------------------------------------
           RETURN
        ------------------------------------------------------------------------------------------------------ */
     return $this->DOMDocument->saveHTML();
 }
Example #6
0
 protected function parseHTML($body)
 {
     if (strpos($body, '<div class="description">未找到相關資料</div>')) {
         return array();
     }
     $doc = new DOMDocument();
     $full_body = '<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></html><body>' . $body . '</body></html>';
     @$doc->loadHTML($full_body);
     $result_dom = $doc->getElementById('hiddenresult');
     if (is_null($result_dom)) {
         var_dump($body);
         throw new Exception('找不到 div#hiddenresult');
     }
     $count = 0;
     $results = array();
     foreach ($result_dom->childNodes as $div_result_dom) {
         if ('#text' == $div_result_dom->nodeName) {
             continue;
         }
         if ('div' != $div_result_dom->nodeName) {
             throw new Exception("div#hiddenresult 下面只會是 div.result");
         }
         foreach ($div_result_dom->childNodes as $tr_dom) {
             if ('tr' == $tr_dom->nodeName) {
                 $count++;
                 $results[$count] = new StdClass();
                 $results[$count]->content = $doc->saveHTML($tr_dom);
             } elseif ('script' == $tr_dom->nodeName) {
                 $results[$count]->script = $doc->saveHTML($tr_dom);
             }
         }
     }
     return array_values($results);
 }
 public function buildMenu($contents)
 {
     $this->dom = new \DOMDocument();
     $menu = $this->createMenu($contents);
     $this->dom->appendChild($menu);
     $result = $this->dom->saveHTML();
     return $result;
 }
 public function transform()
 {
     E()->getResponse()->setHeader('Content-Type', 'text/javascript; charset=utf-8');
     $component = $this->document->getElementById('result');
     if (!$component) {
         throw new SystemException('ERR_BAD_OPERATION_RESULT', SystemException::ERR_CRITICAL, $this->document->saveHTML());
     }
     return $component->nodeValue;
 }
Example #9
0
function modChrome_material_card($module, &$params, &$attribs)
{
    if (!empty($module->content)) {
        $extractImage = ArrayHelper::getValue($attribs, 'extractimage', true);
        $titleImage = '';
        if ($extractImage) {
            $doc = new DOMDocument();
            $doc->loadHTML($module->content);
            $images = $doc->getElementsByTagName('img');
            $i = 0;
            foreach ($images as $image) {
                if ($i > 0) {
                    continue;
                }
                $titleImage = $doc->saveHTML($image);
                $image->parentNode->removeChild($image);
                $i++;
            }
            $module->content = $doc->saveHTML();
        }
        ?>
		<div class="col-grow-vertical <?php 
        echo htmlspecialchars($params->get('moduleclass_sfx')) . ' ' . ArrayHelper::getValue($attribs, 'col');
        ?>
">
			<div class="card">
				<?php 
        if ($titleImage !== '') {
            ?>
					<div class="card-image">
						<?php 
            echo $titleImage;
            ?>
					</div>
				<?php 
        }
        ?>
				<div class="card-content">
					<?php 
        if ($module->showtitle != 0) {
            ?>
						<span class="card-title"><?php 
            echo $module->title;
            ?>
</span>
					<?php 
        }
        ?>
					<?php 
        echo $module->content;
        ?>
				</div>
			</div>
		</div>
		<?php 
    }
}
Example #10
0
 /**
  * Convert document to HTML.
  *
  * @return string
  */
 public function toHtml()
 {
     $html = null;
     $nodes_list = $this->document->getElementsByTagName('body')->item(0)->childNodes;
     foreach ($nodes_list as $item) {
         $html .= $this->document->saveHTML($item);
     }
     return $html;
 }
 public static function getNewBoard($bid)
 {
     $url = "https://forum.blockland.us/index.php?board={$bid}.0";
     // we only need to check one page
     // I doubt there'll be that many updates in a minute
     $html = file_get_contents($url);
     $dom = new DOMDocument();
     $dom->loadHTML($html);
     $tables = $dom->getElementsByTagName("table");
     $header = $tables->item(0);
     $welcome = $header->getElementsByTagName("td")->item(1);
     date_default_timezone_set('US/Eastern');
     $text = $dom->saveHTML($welcome);
     $lines = explode("<br>", $text);
     $words = explode(" ", $lines[2]);
     $date = str_replace($words[2] . " ", "", $lines[2]);
     $forumTime = strtotime(strip_tags($date));
     $table = null;
     foreach ($tables as $tab) {
         if ($tab->getAttribute("class") == "bordercolor") {
             $table = $tab;
         }
     }
     $nlist = $table->getElementsByTagName("tr");
     foreach ($nlist as $index => $tr) {
         if ($index == 0) {
             continue;
         }
         $tds = $tr->getElementsByTagName("td");
         $name = "";
         $topic = "";
         foreach ($tds as $idx => $td) {
             if ($idx == 1) {
                 $u = $td->getElementsByTagName("a")->item(0);
                 $name = $u->textContent;
                 $topic = str_replace("https://forum.blockland.us/index.php?topic=", "", $u->getAttribute("href"));
             } else {
                 if ($idx == 5) {
                     $text = $dom->saveHTML($td);
                     $lines = explode("<br>", $text);
                     $date = strip_tags($lines[0]);
                     $date = str_replace("Today at", date("F j,", $forumTime), $date);
                     $time = strtotime($date);
                     $author = trim(strip_tags(substr($lines[1], 3, strlen($lines[1]))));
                     if ($time > $forumTime - 60) {
                         echo $topic . "\n";
                         //NotificationManager::sendPushNotification("9789", "Forum Post", $text = "<color:3333ff><font:verdana bold:13>$author<font:verdana:13><color:000000> posted a reply in <font:verdana bold:13>$name", "newspaper", "", 0);
                     }
                 }
             }
         }
     }
 }
Example #12
0
function stripStyles($partBodyData)
{
    $data = strtr($partBodyData, array('-' => '+', '_' => '/'));
    $data = base64_decode($data);
    $doc = new DOMDocument();
    @$doc->loadHTML($data);
    foreach ($doc->getElementsByTagName("style") as $style) {
        $style->parentNode->removeChild($style);
        $doc->saveHTML();
    }
    $encodedDom = base64_encode($doc->saveHTML());
    $encodedDom = strtr($encodedDom, array('+' => '+', '/' => '_'));
    return $encodedDom;
}
Example #13
0
 public function getItemData($itemId)
 {
     $xml = $this->getItem($itemId);
     $doc = new DOMDocument();
     $desdoc = new DOMDocument();
     $doc->loadXML($xml);
     $desdoc->loadHTML($doc->getElementsByTagName("Description")->item(0)->nodeValue);
     // GET DESCRIPTION DIV
     $divs = $desdoc->getElementsByTagName("div");
     foreach ($divs as $div) {
         if ($div->attributes->getNamedItem("class")->nodeValue != "des") {
             continue;
         }
         $des = $div;
         break;
     }
     $descr_str = $desdoc->saveHTML($des);
     ////////////////////////
     // GET STYLES
     $style_str = "";
     $styles = $desdoc->getElementsByTagName("style");
     foreach ($styles as $style) {
         $style_str .= $desdoc->saveHTML($style);
     }
     ////////////////////////
     // GET Scripts
     $script_str = "";
     $scripts = $desdoc->getElementsByTagName("script");
     foreach ($scripts as $script) {
         $script_str .= $desdoc->saveHTML($script);
     }
     ////////////////////////
     $item = new Item();
     $item->description = $script_str . " " . $style_str . " " . $descr_str;
     $item->setSku($doc->getElementsByTagName("SKU")->item(0)->nodeValue);
     $item->price = $doc->getElementsByTagName("CurrentPrice")->item(0)->nodeValue;
     $item->currency = $doc->getElementsByTagName("CurrentPrice")->item(0)->attributes->getNamedItem("currencyID")->nodeValue;
     $item->quantity = $doc->getElementsByTagName("Quantity")->item(0)->nodeValue;
     $item->categoryId = $doc->getElementsByTagName("CategoryID")->item(0)->nodeValue;
     $item->categoryName = $doc->getElementsByTagName("CategoryName")->item(0)->nodeValue;
     $pictures = $doc->getElementsByTagName("PictureURL");
     $item->pictures = array();
     foreach ($pictures as $pic) {
         array_push($item->pictures, $pic->nodeValue);
     }
     $item->name = $doc->getElementsByTagName("Title")->item(0)->nodeValue;
     return $item;
 }
Example #14
0
 /**
  * Returns the full HTML text in the original charset.
  *
  * @param array $opts  Additional options: (since 2.1.0)
  *   - charset: (string) Return using this charset. If set but empty, will
  *              return as currently stored in the DOM object.
  *   - metacharset: (boolean) If true, will add a META tag containing the
  *                  charset information.
  *
  * @return string  HTML text.
  */
 public function returnHtml(array $opts = array())
 {
     $curr_charset = $this->getCharset();
     if (strcasecmp($curr_charset, 'US-ASCII') === 0) {
         $curr_charset = 'UTF-8';
     }
     $charset = array_key_exists('charset', $opts) ? empty($opts['charset']) ? $curr_charset : $opts['charset'] : $this->_origCharset;
     if (empty($opts['metacharset'])) {
         $text = $this->dom->saveHTML();
     } else {
         /* Add placeholder for META tag. Can't add charset yet because DOM
          * extension will alter output if it exists. */
         $meta = $this->dom->createElement('meta');
         $meta->setAttribute('http-equiv', 'content-type');
         $meta->setAttribute('horde_dom_html_charset', '');
         $head = $this->getHead();
         $head->insertBefore($meta, $head->firstChild);
         $text = str_replace('horde_dom_html_charset=""', 'content="text/html; charset=' . $charset . '"', $this->dom->saveHTML());
         $head->removeChild($meta);
     }
     if (strcasecmp($curr_charset, $charset) !== 0) {
         $text = Horde_String::convertCharset($text, $curr_charset, $charset);
     }
     if (!$this->_xmlencoding || ($pos = strpos($text, $this->_xmlencoding)) === false) {
         return $text;
     }
     return substr_replace($text, '', $pos, strlen($this->_xmlencoding));
 }
Example #15
0
 function parseHtml()
 {
     //$this->_html = str_replace("<!DOCTYPE html>", "", $this->_html);
     /*
     $p = xml_parser_create();
     xml_parse_into_struct($p, $this->_html, $vals, $index);
     xml_parser_free($p);
     echo "Index array\n";
     pr($index);
     echo "\nVals array\n";
     pr($vals);
     die;
     */
     /*
     $this->_html = str_replace("<!DOCTYPE html>", "", $this->_html);
     $__data = new SimpleXMLElement($this->_html);
     pr($__data); die;
     */
     $dom = new DOMDocument();
     //echo htmlentities($this->_html); die;
     libxml_use_internal_errors(true);
     //$this->_html = str_replace("<!DOCTYPE html>", "", $this->_html);
     //$this->_html = str_replace("</h1>", "", $this->_html);
     //echo htmlentities($this->_html); die;
     //echo htmlentities($this->_html); die;
     $dom->loadHTML($this->_html);
     foreach ($dom->getElementsByTagName('img') as $node) {
         $array[] = $dom->saveHTML($node);
     }
     //pr($array);
     //die;
 }
 /**
  * Performs final transformations and returns resulting HTML.  Note that if you want to call this
  * both without an element and with an element you should call it without an element first.  If you
  * specify the $element in the method it'll change the underlying dom and you won't be able to get
  * it back.
  *
  * @param DOMElement|string|null $element ID of element to get HTML from or
  *   false to get it from the whole tree
  * @return string Processed HTML
  */
 public function getText($element = null)
 {
     if ($this->doc) {
         if ($element !== null && !$element instanceof \DOMElement) {
             $element = $this->doc->getElementById($element);
         }
         if ($element) {
             $body = $this->doc->getElementsByTagName('body')->item(0);
             $nodesArray = [];
             foreach ($body->childNodes as $node) {
                 $nodesArray[] = $node;
             }
             foreach ($nodesArray as $nodeArray) {
                 $body->removeChild($nodeArray);
             }
             $body->appendChild($element);
         }
         $html = $this->doc->saveHTML();
         $html = $this->fixLibXml($html);
         if (PHP_EOL === "\r\n") {
             // Cleanup for CRLF misprocessing of unknown origin on Windows.
             $html = str_replace('&#13;', '', $html);
         }
     } else {
         $html = $this->html;
     }
     // Remove stuff added by wrapHTML()
     $html = \preg_replace('/<!--.*?-->|^.*?<body>|<\\/body>.*$/s', '', $html);
     $html = $this->onHtmlReady($html);
     if ($this->elementsToFlatten) {
         $elements = \implode('|', $this->elementsToFlatten);
         $html = \preg_replace("#</?({$elements})\\b[^>]*>#is", '', $html);
     }
     return $html;
 }
 /**
  * Método que genera el formulario de pago en HTML
  *
  * @param string $button_type
  *   Dimensión del boton a mostrar
  *
  * @return string
  *   Formulario renderizado
  */
 public function renderForm($button_type = '100x50')
 {
     $values = $this->getFormLabels();
     $html = new DOMDocument();
     $html->formatOutput = true;
     $form = $html->createElement('form');
     $form->setAttribute('action', $this->getApiUrl());
     $form->setAttribute('method', 'POST');
     foreach ($values as $name => $value) {
         $input_hidden = $html->createElement('input');
         $input_hidden->setAttribute('type', 'hidden');
         $input_hidden->setAttribute('name', $name);
         $input_hidden->setAttribute('value', $value);
         $form->appendChild($input_hidden);
     }
     $input_hidden = $html->createElement('input');
     $input_hidden->setAttribute('type', 'hidden');
     $input_hidden->setAttribute('name', 'agent');
     $input_hidden->setAttribute('value', $this->agent);
     $form->appendChild($input_hidden);
     $buttons = Khipu::getButtonsKhipu();
     if (isset($buttons[$button_type])) {
         $button = $buttons[$button_type];
     } else {
         $button = $buttons['100x50'];
     }
     $submit = $html->createElement('input');
     $submit->setAttribute('type', 'image');
     $submit->setAttribute('src', $button);
     $form->appendChild($submit);
     $html->appendChild($form);
     return $html->saveHTML();
 }
 public function display($supress_output = false)
 {
     if (!array_key_exists('HTTP_HOST', $_SERVER)) {
         exit("No command line usage for this page");
     }
     if (!$this->get_exists('delay_index')) {
         I2CE::raiseError("Invalid tree data request:  'request' is missing");
         return false;
     }
     $delay_index = $this->get('delay_index');
     if (!array_key_exists('tree_data', $_SESSION) || !is_array($_SESSION['tree_data']) || !array_key_exists($delay_index, $_SESSION['tree_data'])) {
         return false;
     }
     $data = $_SESSION['tree_data'][$delay_index];
     unset($_SESSION['tree_data'][$delay_index]);
     if (!is_array($data)) {
         return false;
     }
     $template = new I2CE_Template();
     $template->loadRootText("<span id='root'>");
     $root = $template->getElementById('root');
     $doc = $template->getDoc();
     I2CE_Module_TreeSelect::createTreeData($template, $root, $data);
     $tdoc = new DOMDocument();
     $tdoc->appendChild($tdoc->importNode($root, true));
     echo $tdoc->saveHTML();
     die;
 }
 public function onRenderProductListBefore(FilterResponseEvent $event)
 {
     $app = $this->app;
     $request = $event->getRequest();
     $response = $event->getResponse();
     $id = $request->query->get('category_id');
     // category_idがない場合、レンダリングを変更しない
     if (is_null($id)) {
         return;
     }
     $CategoryContent = $app['category_content.repository.category_content']->find($id);
     // 登録がない、もしくは空で登録されている場合、レンダリングを変更しない
     if (is_null($CategoryContent) || $CategoryContent->getContent() == '') {
         return;
     }
     // 書き換えhtmlの初期化
     $html = $response->getContent();
     libxml_use_internal_errors(true);
     $dom = new \DOMDocument();
     $dom->loadHTML('<?xml encoding="UTF-8">' . $html);
     $dom->encoding = "UTF-8";
     $dom->formatOutput = true;
     // 挿入対象を取得
     $navElement = $dom->getElementById('page_navi_top');
     if (!$navElement instanceof \DOMElement) {
         return;
     }
     $template = $dom->createDocumentFragment();
     $template->appendXML(htmlspecialchars($CategoryContent->getContent()));
     $node = $dom->importNode($template, true);
     $navElement->insertBefore($node);
     $newHtml = html_entity_decode($dom->saveHTML(), ENT_NOQUOTES, 'UTF-8');
     $response->setContent($newHtml);
     $event->setResponse($response);
 }
Example #20
0
 public static function uploadTextarea($texto, $tipo_midia)
 {
     $nomeTipo = TipoMidia::findOrFail($tipo_midia)->descricao;
     // gravando imagem do corpo da noticia
     $dom = new \DOMDocument();
     $dom->loadHtml($texto, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
     $images = $dom->getElementsByTagName('img');
     // foreach <img> in the submited message
     foreach ($images as $img) {
         $src = $img->getAttribute('src');
         // if the img source is 'data-url'
         if (preg_match('/data:image/', $src)) {
             // get the mimetype
             preg_match('/data:image\\/(?<mime>.*?)\\;/', $src, $groups);
             $mimetype = $groups['mime'];
             // Generating a random filename
             $filename = md5(uniqid());
             $filepath = "uploads/" . $nomeTipo . "/" . $filename . '.' . $mimetype;
             // @see http://image.intervention.io/api/
             $image = Image::make($src)->encode($mimetype, 100)->save(public_path($filepath));
             $new_src = asset($filepath);
             $img->removeAttribute('src');
             $img->setAttribute('src', $new_src);
         }
     }
     return $dom->saveHTML();
 }
Example #21
0
 /**
  * Add ids to headings tags based on their content
  *
  * @static
  * @param string $html html string
  * @param string $headingSelector CSS selector
  * @return mixed modified
  */
 public static function addHeadingsId($html, $headingSelector = 'h1, h2, h3, h4, h5, h6', $addLink = false)
 {
     if (!$html) {
         return '';
     }
     $document = new \DOMDocument();
     $document->loadHTML('<?xml encoding="UTF-8">' . $html);
     $xpath = new \DOMXPath($document);
     // Search heading tags
     $ids = array();
     foreach ($xpath->query(CssSelector::toXPath($headingSelector)) as $node) {
         // If they don't have an id, find an unique one
         if (!$node->hasAttribute('id')) {
             $id = Inflector::urlize($node->textContent);
             if (array_key_exists($id, $ids)) {
                 $ids[$id] += 1;
                 $id .= '-' . $ids[$id];
             } else {
                 $ids[$id] = 1;
             }
             $node->setAttribute('id', $id);
         }
         if ($addLink) {
             $link = $document->createElement('a', '#');
             $link->setAttribute('href', '#' . $node->getAttribute('id'));
             $link->setAttribute('class', 'anchor');
             $node->appendChild($link);
         }
     }
     // Remove \DomDocument's extra tags (doctype, html, body). Yeah, that's (a bit) ugly.
     return preg_replace('#.*<html><body>(.*)</body></html>.*#is', '\\1', $document->saveHTML());
 }
Example #22
0
 public function render($caption_set, $file = false)
 {
     $dom = new \DOMDocument("1.0");
     $dom->formatOutput = true;
     $root = $dom->createElement('tt');
     $dom->appendChild($root);
     $body = $dom->createElement('body');
     $root->appendChild($body);
     $xmlns = $dom->createAttribute('xmlns');
     $xmlns->appendChild($dom->createTextNode('http://www.w3.org/ns/ttml'));
     $root->appendChild($xmlns);
     $div = $dom->createElement('div');
     $body->appendChild($div);
     foreach ($caption_set->captions() as $index => $caption) {
         $entry = $dom->createElement('p');
         $from = $dom->createAttribute('begin');
         $from->appendChild($dom->createTextNode(DfxpHelper::time_to_string($caption->start())));
         $entry->appendChild($from);
         $to = $dom->createAttribute('end');
         $to->appendChild($dom->createTextNode(DfxpHelper::time_to_string($caption->end())));
         $entry->appendChild($to);
         $entry->appendChild($dom->createCDATASection($caption->text()));
         $div->appendChild($entry);
     }
     if ($file) {
         return file_put_contents($file, $dom->saveXML());
     } else {
         return $dom->saveHTML();
     }
 }
Example #23
0
 public function run()
 {
     header('Content-Type: text/html; charset=UTF-8');
     $url = $this->getUrl();
     $kategoria = $this->getKategoria();
     $dir = opendir('uploads/');
     $doc = new \DOMDocument();
     @$doc->loadHTMLFile($url);
     $xpath = new \DOMXPath($doc);
     $titles = $xpath->query('//div[@class="rendslide-box"]//div[@class="product-box"]//td[@class="label"]//p[@class="font-fitter"]');
     $links = $xpath->query('//div[@class="rendslide-box"]//div[@class="slide page"]/@onclick');
     for ($i = 0; $i < $links->length; $i++) {
         $title = iconv('UTF8', 'LATIN1', $titles->item($i)->nodeValue);
         $link = str_replace("'", "", str_replace('window.location.href=', '', $links->item($i)->value));
         $subDoc = new \DOMDocument();
         @$subDoc->loadHTMLFile($link);
         $subXpath = new \DOMXPath($subDoc);
         $src = $subXpath->query('//div[@id="product"]//div[@class="left"]//a[@class="box"]/@href')->item(0)->value;
         $ext = pathinfo($src, PATHINFO_EXTENSION);
         $description = $subDoc->saveHTML($subXpath->query('//div[@id="product"]//div[@class="right"]//div[@class="left-margin"]')->item(0));
         $permalink = $this->createPermalink($title);
         $description = iconv('UTF8', 'LATIN1', $description);
         $description = preg_replace('/<p>.<\\/p>/', '', $description);
         \DB\base\Manager::connection()->exec("\n                INSERT INTO element \n                    (label, permalink, opis, extension, kategoria_id)\n                    VALUES\n                    ('" . $title . "','" . $permalink . "','" . $description . "', '" . $ext . "'," . $kategoria . ")\n            ");
         $lastId = \DB\base\Manager::connection()->query("\n                SELECT id FROM element ORDER BY id DESC LIMIT 1\n            ")->fetchColumn();
         $imgCt = file_get_contents($src);
         $folder = 'uploads/' . $lastId;
         mkdir($folder);
         $fp = fopen($folder . "/image." . $ext, "w");
         fwrite($fp, $imgCt);
         fclose($fp);
     }
 }
 /**
  * Our function called via Twig; it can do anything you want
  *
  * @return string
  */
 public function lettering($text = null, $class = 'chars')
 {
     if (!$text || strlen($text) === 0 || !method_exists(craft()->lettering, $class)) {
         return $text;
     }
     $dom = new LetteringDom();
     $dom->loadHTML(mb_convert_encoding('<div id="workingNode">' . $text . '</div>', 'HTML-ENTITIES', $this->encoding));
     $workingNode = $dom->getElementById('workingNode');
     $fragment = $dom->createDocumentFragment();
     foreach ($workingNode->childNodes as $node) {
         if ($node->nodeType !== 1) {
             continue;
         }
         $value = $node->nodeValue;
         $result = craft()->lettering->{$class}($value, $class);
         $node->nodeValue = '';
         $tempFragment = new LetteringDom();
         $tempFragment->loadHTML(mb_convert_encoding($result[$class], 'HTML-ENTITIES', $this->encoding));
         foreach ($tempFragment->getElementsByTagName('body')->item(0)->childNodes as $tempNode) {
             $tempNode = $node->ownerDocument->importNode($tempNode, true);
             $node->appendChild($tempNode);
         }
         $node->setAttribute('aria-label', trim(strip_tags($value)));
         $fragment->appendChild($node->cloneNode(true));
     }
     $workingNode->parentNode->replaceChild($fragment, $workingNode);
     $result = TemplateHelper::getRaw(preg_replace('~<(?:!DOCTYPE|/?(?:html|head|body))[^>]*>\\s*~i', '', $dom->saveHTML()));
     if (strlen(trim($result)) === 0) {
         $result = craft()->lettering->{$class}($text);
         return $result ? $result[$class] : $text;
     }
     return $result;
 }
Example #25
0
 /**
  * The <div id="connexion">
  * @return DOMNode
  */
 public function getWidget()
 {
     $doc = new \DOMDocument();
     $doc->preserveWhiteSpace = true;
     $this->isConnected() ? $doc->loadHTMLFile('page/edit/connexion.html') : $doc->loadHTMLFile('page/show/connexion.html', LIBXML_HTML_NOIMPLIED);
     return $doc->saveHTML();
 }
Example #26
0
 public static function static__escaped_fragment_($_escaped_fragment_)
 {
     \libxml_use_internal_errors(true);
     $html = new \DOMDocument();
     $html->loadHTML(static::default_page($_escaped_fragment_ ? $_escaped_fragment_ : true));
     if ($error = \libxml_get_last_error()) {
         //new \SYSTEM\LOG\ERROR('Parse Error: '.$error->message.' line:'.$error->line.' html: '.$html->saveHTML());
         \libxml_clear_errors();
     }
     $state = \SYSTEM\PAGE\State::get(static::get_apigroup(), $_escaped_fragment_ ? $_escaped_fragment_ : static::get_default_state(), false);
     foreach ($state as $row) {
         $frag = new \DOMDocument();
         parse_str(\parse_url($row['url'], PHP_URL_QUERY), $params);
         $class = static::get_class($params);
         if ($class) {
             $frag->loadHTML(\SYSTEM\API\api::run('\\SYSTEM\\API\\verify', $class, static::get_params($params), static::get_apigroup(), true, false));
             if ($error = \libxml_get_last_error()) {
                 //new \SYSTEM\LOG\ERROR('Parse Error: '.$error->message.' line:'.$error->line.' html: '.$frag->saveHTML());
                 \libxml_clear_errors();
             }
             $html->getElementById(substr($row['div'], 1))->appendChild($html->importNode($frag->documentElement, true));
             //Load subpage css
             foreach ($row['css'] as $css) {
                 $css_frag = new \DOMDocument();
                 $css_frag->loadHTML('<link href="' . $css . '" rel="stylesheet" type="text/css">');
                 $html->getElementsByTagName('head')[0]->appendChild($html->importNode($css_frag->documentElement, true));
             }
         }
     }
     echo $html->saveHTML();
     new \SYSTEM\LOG\COUNTER("API was called sucessfully.");
     die;
 }
Example #27
0
 /**
  * Transform asset paths based on the report
  *
  * @param $content
  * @return string
  * @throws ExtensionNotLoadedException
  */
 public function transformAssetPaths($content)
 {
     if (null === $content) {
         throw new ContentNotFoundException('No content was found to be rendered');
     }
     libxml_use_internal_errors(true);
     $doc = new \DOMDocument();
     $doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES'));
     $reportRouting = $this->extensionManager->findExtension('report_routing');
     if (null === $reportRouting) {
         throw new ExtensionNotLoadedException('report_routing');
     }
     /* Transform images */
     $images = $doc->getElementsByTagName('img');
     foreach ($images as $image) {
         $this->prepareAsset($image, 'src', $reportRouting);
     }
     /* Transform styles */
     $styles = $doc->getElementsByTagName('link');
     foreach ($styles as $style) {
         $this->prepareAsset($style, 'href', $reportRouting);
     }
     /* Transform scripts */
     $scripts = $doc->getElementsByTagName('script');
     foreach ($scripts as $script) {
         $this->prepareAsset($script, 'src', $reportRouting);
     }
     return $doc->saveHTML();
 }
Example #28
0
 public function run()
 {
     header('Content-Type: text/html; charset=utf-8');
     $url = $this->getUrl();
     $kategoria = $this->getKategoria();
     $dir = opendir('uploads/');
     $doc = new \DOMDocument();
     @$doc->loadHTMLFile($url);
     $xpath = new \DOMXPath($doc);
     $links = $xpath->query('//td[@class="main_table"]//td[@class="right"]//table[@class="tekst"]//td[@class="product_list_foto"]//a/@href');
     $titles = $xpath->query('//td[@class="main_table"]//td[@class="right"]//table[@class="tekst"]//td[@class="product_list_data"]//span[@class="product_list_name"]');
     $desc = $xpath->query('//td[@class="main_table"]//td[@class="right"]//table[@class="tekst"]//td[@class="product_list_data"]//td[@class="product_list_desc"]');
     for ($i = 0, $j = 0; $i < $links->length; $i++, $j = $j + 2) {
         $description = $doc->saveHTML($desc->item($j));
         $description = strip_tags($description, '<p><div><br>');
         $title = $titles->item($i)->nodeValue;
         $src = self::PREFIX_TO_IMAGES . $links->item($i)->value;
         $ext = pathinfo($src, PATHINFO_EXTENSION);
         $permalink = $this->createPermalink($title);
         \DB\base\Manager::connection()->exec("\n                INSERT INTO element \n                    (label, permalink, opis, extension, kategoria_id)\n                    VALUES\n                    ('" . $title . "','" . $permalink . "','" . $description . "', '" . $ext . "'," . $kategoria . ")\n            ");
         $lastId = \DB\base\Manager::connection()->query("\n                SELECT id FROM element ORDER BY id DESC LIMIT 1\n            ")->fetchColumn();
         $imgCt = file_get_contents($src);
         $folder = 'uploads/' . $lastId;
         mkdir($folder);
         $fp = fopen($folder . "/image." . $ext, "w");
         fwrite($fp, $imgCt);
         fclose($fp);
     }
 }
 public static function getDom($stream)
 {
     rewind($stream);
     $doc = new DOMDocument();
     $doc->loadHTML(stream_get_contents($stream));
     return new SimpleXMLElement($doc->saveHTML());
 }
Example #30
0
function parseLinks($xml)
{
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($xml, 'HTML-ENTITIES', "UTF-8"));
    $nodes = $dom->getElementsByTagName("ai_link");
    while ($nodes->length > 0) {
        $node = $nodes->item(0);
        $newNode = $dom->createElement("a");
        foreach ($node->attributes as $attribute) {
            $newNode->setAttribute($attribute->name, $attribute->value);
        }
        if ($newNode->hasAttribute("frag")) {
            $newNode->setAttribute("onclick", "loadFragment('" . $newNode->getAttribute("frag") . "');return false;");
            $newNode->setAttribute("href", "/?p=" . $newNode->getAttribute("frag"));
            $newNode->removeAttribute("frag");
        } else {
            if ($newNode->hasAttribute("ext")) {
                $newNode->setAttribute("href", $newNode->getAttribute("ext"));
                $newNode->setAttribute("target", "_blank");
                $newNode->removeAttribute("ext");
            }
        }
        foreach ($node->childNodes as $child) {
            $newNode->appendChild($node->removeChild($child));
        }
        $node->parentNode->replaceChild($newNode, $node);
    }
    return preg_replace(array("/^\\<\\!DOCTYPE.*?<html><body>/si", "!</body></html>\$!si"), "", $dom->saveHTML($dom->documentElement));
}