Example #1
1
 public function testCorrectSetup()
 {
     $cloneable = $this->prepareValidCloneableField();
     $this->form->add($cloneable);
     $this->assertInstanceOf('\\Phalcon\\DI', $this->form->get('cloneable_field')->getDecorator()->getDI());
     $this->form->get('cloneable_field')->getDecorator()->setTemplateName('jquery');
     $domDoc = new \DOMDocument('1.0');
     $domDoc->loadHTML($this->form->get('cloneable_field')->render());
     $this->assertEquals(2, $domDoc->getElementById('cloneable_field')->getElementsByTagName('fieldset')->length);
     $this->assertEquals(4, $domDoc->getElementById('cloneable_field')->getElementsByTagName('input')->length);
     $domDoc->loadHTML($this->form->get('cloneable_field')->render(['attribute' => 'test']));
     $this->assertEquals('test', $domDoc->getElementById('cloneable_field')->attributes->getNamedItem('attribute')->value);
     $this->assertNull($this->form->get('cloneable_field')->getBaseElement('test3'));
     $this->assertInstanceOf('\\Phalcon\\Forms\\ElementInterface', $this->form->get('cloneable_field')->getBaseElement('test2'));
 }
Example #2
0
function startGame($gameID)
{
    error_reporting(0);
    $api = curl_init('http://play.textadventures.co.uk/Play.aspx?id=' . $gameID);
    curl_setopt($api, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($api, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($api, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($api, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($api);
    $dom = new DOMDocument();
    $dom->loadHTML($result);
    $viewState = $dom->getElementById('__VIEWSTATE');
    $viewStateGenerator = $dom->getElementById('__VIEWSTATEGENERATOR');
    $eventValidation = $dom->getElementById('__EVENTVALIDATION');
    $viewState = $viewState->attributes->getNamedItem('value')->nodeValue;
    $viewStateGenerator = $viewStateGenerator->attributes->getNamedItem('value')->nodeValue;
    $eventValidation = $eventValidation->attributes->getNamedItem('value')->nodeValue;
    echo '"' . $eventValidation . '"<br>';
    echo '"' . $viewState . '"<br>';
    echo '"' . $viewStateGenerator . '"<br>';
    echo '------------------<br>';
    error_reporting(-1);
    //sleep(1);
    startGame_stage2($gameID, $viewState, $viewStateGenerator, $eventValidation);
}
Example #3
0
function getDirectoryListing($result, $path, $cat)
{
    $path .= " > " . $cat;
    $cat = str_replace(" ", "_", $cat);
    $ch = curl_init();
    $buffer = fopen("buffer.html", "w");
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2");
    curl_setopt($ch, CURLOPT_URL, "http://ru.wikipedia.org/wiki/Категория:" . $cat);
    curl_setopt($ch, CURLOPT_FILE, $buffer);
    curl_exec($ch);
    curl_close($ch);
    fclose($buffer);
    // working with the pre-fetched page using DOMDocument
    // due to a bug (?) w/ fetching Cyrillic URLs via DOMDocument->loadHTMLFile
    $html = new DOMDocument();
    $html->loadHTMLFile("buffer.html");
    $subCats = $html->getElementById("mw-subcategories");
    if ($subCats) {
        foreach ($subCats->getElementsByTagName("a") as $s) {
            getDirectoryListing($result, $path, $s->textContent);
        }
        unset($subCats);
    }
    $pages = $html->getElementById("mw-pages");
    if ($pages) {
        foreach ($pages->getElementsByTagName("a") as $a) {
            fwrite($result, "{$path} > {$a->textContent}" . PHP_EOL);
        }
        unset($pages);
    }
}
 /**
  * Removes the TOC (#toc) from the body
  */
 protected function removeToc()
 {
     $element = $this->dom->getElementById('toc');
     if ($element !== null) {
         $element->parentNode->removeChild($element);
     }
 }
Example #5
0
 public function handleError(\Dwoo\Exception $e)
 {
     $html = new \DOMDocument();
     $html->loadHTMLFile('lib/resources/exception.html');
     $message = $html->getElementById('message');
     $template = $html->createDocumentFragment();
     $template->appendXML($e->getMessage());
     $message->appendChild($template);
     unset($template);
     $php_version = $html->getElementById('php-version');
     $template = $html->createDocumentFragment();
     $template->appendXML(phpversion());
     $php_version->appendChild($template);
     unset($template);
     $dwoo_version = $html->getElementById('dwoo-version');
     $template = $html->createDocumentFragment();
     $template->appendXML(Core::VERSION);
     $dwoo_version->appendChild($template);
     unset($template);
     $exectime = $html->getElementById('exectime');
     $template = $html->createDocumentFragment();
     $template->appendXML(round(microtime(true) - $_SERVER['REQUEST_TIME'], 3));
     $exectime->appendChild($template);
     unset($template);
     echo $html->saveHTML();
 }
 /**
  * @param string $uri
  * @return string
  * @throws \Exception
  */
 protected function getCurrentSslVoting($uri, $ip = NULL)
 {
     $pathSegments = parse_url($uri);
     if ($ip === NULL) {
         if (!array_key_exists('host', $pathSegments)) {
             throw new \Exception('The Uri' . $uri . ' can´ be parsed cleanly');
         }
         $ip = gethostbyname($pathSegments['host']);
     }
     $buffer = file_get_contents('https://www.ssllabs.com/ssltest/analyze.html?d=' . urlencode($pathSegments['host']) . '&s=' . $ip);
     libxml_use_internal_errors(true);
     $domDocument = new \DOMDocument();
     $domDocument->loadHTML($buffer);
     $ratingElement = $domDocument->getElementById('rating');
     if ($ratingElement === NULL) {
         $warningBox = $domDocument->getElementById('warningBox');
         if ($warningBox !== null) {
             switch (trim($warningBox->textContent)) {
                 case 'Assessment failed: No secure protocols supported':
                 case 'Assessment failed: Unable to connect to server':
                     throw new NoSslException(trim($warningBox->textContent), $this->getSession());
                     break;
                 default:
                     throw new StillRunningException(trim($warningBox->textContent), $this->getSession());
                     break;
             }
         }
         throw new \Exception('No voting available yet');
     }
     libxml_use_internal_errors(false);
     return trim($ratingElement->childNodes->item(3)->textContent);
 }
 public function parse($html)
 {
     if (empty($html)) {
         $this->title = $this->message = 'Empty exception';
         $this->sourceFile = '';
         return false;
     }
     if (!$this->domDocument) {
         $this->domDocument = new \DOMDocument();
     }
     @$this->domDocument->loadHTML($html);
     $titleItem = $this->domDocument->getElementsByTagName("title")->item(0);
     $this->title = $titleItem ? $titleItem->textContent : 'N/A';
     try {
         $sourceFileElement = $this->domDocument->getElementById("tracy-bs-error");
         if (is_object($sourceFileElement)) {
             $sourceFileLinkNode = $sourceFileElement->getElementsByTagName("a")->item(0);
             $this->sourceFile = trim($sourceFileLinkNode->textContent);
         } else {
             $this->sourceFile = 'Unknown format of exception';
         }
         $messageNode = $this->domDocument->getElementsByTagName("p")->item(0);
         if (is_object($messageNode)) {
             $messageNode->removeChild($messageNode->lastChild);
             $this->message = trim($messageNode->textContent);
         } else {
             $this->message = 'Unable to parse';
         }
     } catch (\Exception $e) {
         $this->message = 'Unable to parse';
     }
 }
Example #8
0
function get_profile_email($url)
{
    global $g_acegi_cookie;
    global $g_session_cookie;
    global $g_delay;
    sleep($g_delay);
    // Create a stream
    // get cookie values using wget commands
    $cookie = sprintf("Cookie: ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE=%s; JSESSIONID=%s\r\n", $g_acegi_cookie, $g_session_cookie);
    $opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\n" . $cookie));
    $context = stream_context_create($opts);
    @($html = file_get_contents($url, false, $context));
    $doc = new \DOMDocument();
    @$doc->loadHTML($html);
    $emailNode = $doc->getElementById("email1__ID__");
    $nameNode = $doc->getElementById("name1__ID__");
    $titleNode = $doc->getElementById("title1__ID__");
    $companyNode = $doc->getElementById("company1__ID__");
    if (!is_null($emailNode)) {
        $data = array();
        $data["email"] = $emailNode->nodeValue;
        $data["name"] = is_null($nameNode) ? "" : $nameNode->nodeValue;
        $data["title"] = is_null($titleNode) ? "" : $titleNode->nodeValue;
        $data["company"] = is_null($companyNode) ? "" : $companyNode->nodeValue;
        return $data;
    }
    return NULL;
}
Example #9
0
function t($xml)
{
    $dom = new DOMDocument();
    $dom->loadHTML($xml);
    $child = $dom->getElementById('x');
    $child = null;
    $child = $dom->getElementById('x');
}
Example #10
0
 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 #11
0
function get_song($content)
{
    //$host = 'http://zaycev.net';
    //$content = file_get_contents($url);
    $dom = new DOMDocument();
    $dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=windows-1251">' . $content);
    $link = $dom->getElementById("pages-download-button")->getAttribute('href');
    $name = $dom->getElementById("pages-download-link")->nodeValue;
    return array('name' => $name, 'link' => $link);
}
function PegaNivelRioDoceGV($url = "http://saaegoval.com.br/custom/niv_rio_vis.aspx")
{
    $html = file_get_contents($url);
    $dom = new DOMDocument('1.0');
    $dom->loadHTML($html);
    $txNivel = $dom->getElementById('txNivel');
    $txData = $dom->getElementById('txData');
    $txHora = $dom->getElementById('txHora');
    $NivelDoRioDoceGV = new StdClass();
    $NivelDoRioDoceGV->nivel = $txNivel->C14N();
    $NivelDoRioDoceGV->data = $txData->C14N();
    $NivelDoRioDoceGV->hora = $txHora->C14N();
    return $NivelDoRioDoceGV;
}
Example #13
0
 public function findUser($nick)
 {
     $options = array(CURLOPT_URL => 'http://rutracker.org/forum/profile.php?mode=viewprofile&u=' . $nick, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_USERAGENT => self::$agent, CURLOPT_COOKIEJAR => self::$cookieFile, CURLOPT_COOKIEFILE => self::$cookieFile, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10);
     $curl = curl_init();
     curl_setopt_array($curl, $options);
     $result = curl_exec($curl);
     curl_close($curl);
     $doc = new DOMDocument();
     @$doc->loadHTML($result);
     $role = $this->clean($doc->getElementById('role')->textContent);
     $totalDownloaded = $this->clean($doc->getElementById('u_down_total')->textContent);
     $totalUploaded = $this->clean($doc->getElementById('u_up_total')->textContent);
     $regDate = $this->clean($doc->getElementById('user_regdate')->textContent);
     return array('role' => $role, 'totalDownloaded' => $totalDownloaded, 'totalUploaded' => $totalUploaded, 'registerDate' => $regDate);
 }
 /**
  * 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 #15
0
function get_element_by_id($url, $id)
{
    $html = new DOMDocument();
    @$html->loadHTMLFile($url);
    $element = $html->getElementById($id);
    return $html->saveHTML($element);
}
 /**
  * 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;
 }
 /**
  *
  */
 private function removeBXcommentsSection()
 {
     $find_queries = array('//a[@name="post_content_extended"]', '//div[@class="post_links"]', '//div[@class="post_content_extended"]', '//span[@span="post_comments_count"]', '//a[@name="comments"]', '//div[@name="comments_not"]', '//span[@name="post_uri"]', '//div[@class="post_tags"]', '//span[@class="post_more"]', '//div[@class="post_links"]', '//div[@class="post_meta_data"]', '//script[@type="text/javascript"]', '//a[@name="fb_share"]', '//a[@class="twitter-share-button"]');
     if (class_exists('DOMDocument', false)) {
         $dom = new DOMDocument();
         $dom->loadHTML("<div id=\"removeBXcommentsSection\"> {$this->html} </div>");
     } else {
         return;
     }
     if (class_exists('DOMXPath', false)) {
         $xpath = new DOMXPath($dom);
     } else {
         //echo "<p><strong>DOMXPath not found</strong></p>";
         return;
     }
     $masterNode = $dom->getElementById('removeBXcommentsSection');
     foreach ($find_queries as $query) {
         $entries = $xpath->query($query);
         if ($entries) {
             foreach ($entries as $entry) {
                 //echo "Found {$entry->nodeName}: {$entry->nodeValue}, " ;
                 try {
                     $entry->parentNode->removeChild($entry);
                 } catch (Exception $e) {
                     //echo "<span style=\"color: red;\">Not found {$entry->nodeName}</span>";
                 }
             }
         }
     }
     $this->html = '';
     foreach ($masterNode->childNodes as $node) {
         $this->html .= $dom->saveXML($node);
     }
     $this->html = utf8_decode($this->html);
 }
Example #18
0
 /**
  * 生成导航条
  * $uri : 形式如 c=xxx&a=xxx
  * @return String
  */
 public function genNav($uri = "", $glude = " >> ")
 {
     $uri = empty($uri) ? $_SERVER['QUERY_STRING'] : $uri;
     $aU = explode("&", $uri);
     $aCtl = explode("=", $aU[0]);
     $aAct = explode("=", $aU[1]);
     if ($aCtl[0] != "c" || $aAct[0] != "a") {
         return "导航出错!";
     } else {
         $dom = new DOMDocument("1.0", "UTF-8");
         if ($dom->load(SYSMENU)) {
             $theAct = $dom->getElementById($aCtl[1] . "_" . $aAct[1]);
             if ($theAct->nodeName == 'op') {
                 $sCtl = $theAct->parentNode->parentNode->attributes->getNamedItem("des")->nodeValue;
                 $sAct = $theAct->getAttribute("des");
                 // 还有再下一级的操作
                 $pAct = $theAct->parentNode->attributes;
                 $sP = $pAct->getNamedItem("id")->nodeValue;
                 $aP = explode("_", $sP);
                 $ssAct = "<a href='" . url($aP[0], $aP[1]) . "'>" . $pAct->getNamedItem("des")->nodeValue . "</a>";
                 //$sCtl.$glude.$sAct
                 return $sCtl . $glude . $ssAct . $glude . "<b style='color:red'>" . $sAct . "</b>";
             } elseif ($theAct->nodeName == 'action') {
                 $sCtl = $theAct->parentNode->attributes->getNamedItem("des")->nodeValue;
                 $sAct = "<a href='" . url($aCtl[1], $aAct[1]) . "'>" . $theAct->getAttribute("des") . "</a>";
                 //dump($theCtl->getAttribute("des"));
                 return $sCtl . $glude . $sAct;
             }
         } else {
             return "导航出错!";
         }
     }
 }
Example #19
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 #20
0
 public function preFilter($sHtml, $config, $context)
 {
     if (false === strstr($sHtml, '<a ')) {
         return $sHtml;
     }
     $sId = 'bx-links-' . md5(microtime());
     $dom = new DOMDocument();
     @$dom->loadHTML('<?xml encoding="UTF-8"><div id="' . $sId . '">' . $sHtml . '</div>');
     $xpath = new DOMXpath($dom);
     $oLinks = $xpath->evaluate('//a');
     for ($i = 0; $i < $oLinks->length; $i++) {
         $oLink = $oLinks->item($i);
         $sClasses = $oLink->getAttribute('class');
         if (!$sClasses || false === strpos($sClasses, $this->class)) {
             $sClasses = ($sClasses ? $sClasses . ' ' : '') . $this->class;
         }
         $oLink->removeAttribute('class');
         $oLink->setAttribute("class", $sClasses);
     }
     if (false === ($s = $dom->saveXML($dom->getElementById($sId)))) {
         // in case of error return original string
         return $sHtml;
     }
     return mb_substr($s, 52, -6);
     // strip added tags
 }
Example #21
0
 /**
  * N.B. Not used.
  * 
  * Function to retrieve the DOM element of a page for a given element ID.
  * 
  * @param String $pageSource
  * @param type $id
  * 
  * @return DOMElement $domElement
  */
 public static function retrieveElementById($pageSource, $id)
 {
     $domDocument = new DOMDocument();
     @$domDocument->loadHTML($pageSource);
     $domElement = $domDocument->getElementById($id);
     return $domElement;
 }
Example #22
0
function search_wolframalpha($query)
{
    $url2 = 'http://www.wolframalpha.com/input/?i=' . urlencode($query);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 0);
    //curl_setopt($ch, CURLOPT_REFERER, $ref);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
    //curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url2);
    $r = curl_exec($ch);
    $doc = new DOMDocument();
    @$doc->loadHTML($r);
    $results = $doc->getElementById("results");
    $imgs = array();
    foreach ($results->getElementsByTagName("img") as $img) {
        $src = $img->getAttribute("src");
        if ($src != "/images/loadingdots.gif") {
            //echo "<img src='".$src."'><br>";
            $imgs[] = $src;
        }
    }
    return $imgs;
}
Example #23
0
function ReadXml($xml, $getElement, $attr = '', $type = 'string', $elementtype = 'tagName')
{
    /**
     函数返回字符串.
     参数说明  : (1) $xml - xml文档 ,可以是字符串(4)$type='string' ,或者xml文件路径 (4)$type='filepath'
    		    (2) $getElement - 要获取的元素名, 可以是 tagName(标签名) (5)$elementtype='tagName'  或 id(ID) (5)$elementtype='id'
    			(3) $attr 属性
    **/
    $dom = new DOMDocument();
    if ($type == 'string') {
        $dom->loadXML($xml);
    } else {
        $dom->load($xml);
    }
    $xpath = new DOMXPath($dom);
    if ($elementtype == 'tagName') {
        $nodelist = $xpath->query("//{$getElement}");
    } else {
        $nodelist = $dom->getElementById($getElement);
    }
    foreach ($nodelist as $v) {
        if ($attr == '') {
            return $v->nodeValue;
        } else {
            if ($v->getAttribute($attr)) {
                return $v->getAttribute($attr);
            }
        }
    }
}
Example #24
0
 /**
  * returns the content of this item
  *
  * @return string content
  */
 public function getContent()
 {
     if ($this->items !== false && $this->valid()) {
         try {
             // load entry page
             $client = new Zend_Http_Client($this->getLink() . '?page=all');
             $response = $client->request();
             $content = $response->getBody();
             $content = utf8_decode($content);
             // parse content
             $dom = new Zend_Dom_Query($content);
             $text = $dom->query('.article');
             $innerHTML = '';
             // convert innerHTML from DOM to string
             // taken from http://us2.php.net/domelement (patrick smith)
             $children = $text->current()->childNodes;
             foreach ($children as $child) {
                 $tmp_doc = new DOMDocument();
                 $tmp_doc->appendChild($tmp_doc->importNode($child, true));
                 if (count($tmp_doc->getElementById('comments')) > 0) {
                     continue;
                 }
                 // convert to text
                 $innerHTML .= @$tmp_doc->saveHTML();
             }
             return $innerHTML;
         } catch (Exception $e) {
             // return default content
             return current($this->items)->get_content();
         }
     }
 }
Example #25
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);
 }
Example #26
0
 /**
  * Delete
  *  - Delete the given item from a feed
  *    if no item is given, the feed is deleted
  *
  * @param string $id
  * @return bool
  */
 public function delete($id = null)
 {
     if ($this->isRemote) {
         throw new Rss_RemoteFeed();
     }
     if (is_null($id)) {
         if (zula_is_deletable($this->rssDir . $this->name)) {
             // Call hooks
             Hooks::notifyAll('rss_feed_delete', $this->rssDir, $this->name);
             return unlink($this->rssDir . $this->name);
         }
         $this->_log->message('Unable to delete RSS Feed "' . $this->name . '".', LOG::L_WARNING);
         return false;
     }
     $channels = $this->feed->getElementsByTagName('channel');
     if ($channels->length == 0) {
         throw new Rss_NoFeedInfo();
     }
     $channel = $channels->item(0);
     // Find element to delete
     $node = $this->feed->getElementById($id);
     if (is_null($node)) {
         return false;
     }
     $channel->removeChild($node);
     unset($this->items[$id]);
     Hooks::notifyAll('rss_item_delete', $this->name, $id);
     return true;
 }
 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 #28
0
function embedImageURL($url)
{
    $url .= "/details/xs";
    // PHP5 befigyel!!!
    $doc = new DOMDocument();
    $opts = array('http' => array('max_redirects' => 100));
    $resource = stream_context_get_default($opts);
    $context = stream_context_create($opts);
    libxml_set_streams_context($context);
    // Pattogna kulonben a cookie miatt, kenytelenek vagyunk curl-t hasznalni
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile");
    curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile");
    # SAME cookiefile
    if (@$doc->loadHTML(curl_exec($curl))) {
        if ($retnode = $doc->getElementById("textfield-url")) {
            echo "megy";
            return "<img src=\"{$retnode->nodeValue}\">";
        } else {
            return false;
        }
    } else {
        return false;
    }
}
Example #29
0
 function hook_article_filter($article)
 {
     $owner_uid = $article["owner_uid"];
     if (strpos($article["link"], "nationalgeographic.com") !== FALSE) {
         if (strpos($article["plugin_data"], "natgeo,{$owner_uid}:") === FALSE) {
             $doc = new DOMDocument();
             @$doc->loadHTML(fetch_file_contents($article["link"]));
             $basenode = false;
             if ($doc) {
                 $xpath = new DOMXPath($doc);
                 $basenode = $doc->getElementById("content_mainA");
                 $trash = $xpath->query("//*[@class='aside' or @id='livefyre' or @id='powered_by_livefyre' or @class='social_buttons']");
                 foreach ($trash as $t) {
                     $t->parentNode->removeChild($t);
                 }
                 if ($basenode) {
                     $article["content"] = $doc->saveXML($basenode);
                     $article["plugin_data"] = "natgeo,{$owner_uid}:" . $article["plugin_data"];
                 }
             }
         } else {
             if (isset($article["stored"]["content"])) {
                 $article["content"] = $article["stored"]["content"];
             }
         }
     }
     return $article;
 }
 public function getCurrencyPair(Currency $counterCurrency, Currency $baseCurrency)
 {
     $from = $counterCurrency->getName();
     $to = $baseCurrency->getName();
     $pair = null;
     $url = self::URL . sprintf(self::QUERY, $from, $to);
     $html = @file_get_contents($url);
     if ($html == false) {
         throw new CurrencyRateException('Rate not avaiable, resource not found');
     }
     $doc = new \DOMDocument();
     @$doc->loadHTML($html);
     $el = $doc->getElementById('currency_converter_result');
     if ($el && $el->hasChildNodes()) {
         foreach ($el->childNodes as $node) {
             if ($node->nodeName == 'span' && preg_match('/[0-9\\.]+ ' . $to . '/i', $node->textContent, $matches)) {
                 $ratio = (double) $matches[0];
                 $pair = new CurrencyPair($counterCurrency, $baseCurrency, $ratio);
             }
         }
     }
     if (!$pair) {
         throw new CurrencyRateException('Rate not avaiable, can not parse result: ' . $html);
     }
     return $pair;
 }