示例#1
2
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     // force id = 1
     $metadata = $manager->getClassMetaData(get_class(new SecurityType()));
     $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
     $file = $this->container->getParameter('sulu_security.security_types.fixture');
     $doc = new \DOMDocument();
     $doc->load($file);
     $xpath = new \DOMXpath($doc);
     $elements = $xpath->query('/security-types/security-type');
     if (!is_null($elements)) {
         /** @var $element \DOMNode */
         foreach ($elements as $element) {
             $securityType = new SecurityType();
             $children = $element->childNodes;
             /** @var $child \DOMNode */
             foreach ($children as $child) {
                 if (isset($child->nodeName)) {
                     if ($child->nodeName == 'id') {
                         $securityType->setId($child->nodeValue);
                     }
                     if ($child->nodeName == 'name') {
                         $securityType->setName($child->nodeValue);
                     }
                 }
             }
             $manager->persist($securityType);
         }
     }
     $manager->flush();
 }
示例#2
1
 /**
  * {@inheritdoc}
  */
 public function apply(base $databox, Application $app)
 {
     $structure = $databox->get_structure();
     $DOM = new DOMDocument();
     $DOM->loadXML($structure);
     $xpath = new DOMXpath($DOM);
     foreach ($xpath->query('/record/subdefs/subdefgroup[@name="video"]/subdef[@name="preview"]/acodec') as $node) {
         $node->nodeValue = 'libvo_aacenc';
     }
     foreach ($xpath->query('/record/subdefs/subdefgroup[@name="video"]/subdef[@name="preview"]/vcodec') as $node) {
         $node->nodeValue = 'libx264';
     }
     $databox->saveStructure($DOM);
     $subdefgroups = $databox->get_subdef_structure();
     foreach ($subdefgroups as $groupname => $subdefs) {
         foreach ($subdefs as $name => $subdef) {
             $this->addScreenDeviceOption($subdefgroups, $subdef, $groupname);
             if (in_array($name, ['preview', 'thumbnail'])) {
                 if ($name == 'thumbnail' || $subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) {
                     $this->addMobileSubdefImage($subdefgroups, $subdef, $groupname);
                 } else {
                     $this->addMobileSubdefVideo($subdefgroups, $subdef, $groupname);
                 }
             }
             if ($subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) {
                 continue;
             }
             $this->addHtml5Video($subdefgroups, $subdef, $groupname);
         }
     }
     return true;
 }
 function get_play_store()
 {
     $remote = array();
     $store_page = new DOMDocument();
     $internalErrors = libxml_use_internal_errors(true);
     $store_page->loadHTMLFile("https://play.google.com/store/search?q=awareframework%20plugin");
     $xpath = new DOMXpath($store_page);
     $packages_titles = $xpath->query('//a[@class="title"]/@href');
     foreach ($packages_titles as $pkgs) {
         $package_name = substr($pkgs->textContent, strrpos($pkgs->textContent, "=") + 1, strlen($pkgs->textContent));
         preg_match("/^com\\.aware\\.plugin\\..*/", $package_name, $matches, PREG_OFFSET_CAPTURE);
         if (count($matches) == 0) {
             continue;
         }
         $package_page = new DOMDocument();
         $package_page->loadHTMLFile("https://play.google.com/store/apps/details?id={$package_name}");
         $xpath = new DOMXpath($package_page);
         $icon = $xpath->query('//img[@class="cover-image"]/@src');
         $version = $xpath->query('//div[@itemprop="softwareVersion"]');
         $description = $xpath->query('//div[@itemprop="description"]');
         $pkg = array('title' => trim($pkgs->parentNode->textContent), 'package' => $package_name, 'version' => trim($version->item(0)->textContent), 'desc' => $description->item(0)->childNodes->item(1)->nodeValue, 'iconpath' => 'https:' . $icon->item(0)->value, 'first_name' => 'AWARE', 'last_name' => 'Framework', 'email' => '*****@*****.**');
         $remote[] = $pkg;
     }
     return $remote;
 }
示例#4
0
 /**
  * @param string $html HTML document
  * @return boolean|array
  */
 public function HTMLtoLunchArray($html)
 {
     $doc = new DOMDocument();
     @$doc->loadHTML($html);
     $xpath = new DOMXpath($doc);
     $elements = $xpath->query('//html/body/div/div/div/article/section/div/p');
     $arr = array();
     $i = 1;
     if (!is_null($elements)) {
         foreach ($elements as $element) {
             $nodes = $element->childNodes;
             foreach ($nodes as $node) {
                 $dish = parent::fixSpaces(trim(utf8_decode($node->nodeValue)));
                 if (!empty($dish)) {
                     $arr[$i][] = parent::fixSpaces(trim($node->nodeValue));
                 }
             }
             $i++;
         }
     }
     foreach ($arr as $dayNo => $dayDishArr) {
         $weekDay = parent::weekNumToText($dayNo + 1);
         $dishes[$weekDay] = implode(' / ', $dayDishArr);
     }
     if (!empty($dishes)) {
         return $dishes;
     }
     return false;
 }
示例#5
0
 /**
  * main function extracts url data and returns json array
  * @return json array
  */
 public function getData()
 {
     $results = array();
     $total = 0;
     $htmlMain = $this->getHtml($this->url);
     $doc = new DOMDocument();
     @$doc->loadHTML($htmlMain['result']);
     $xpath = new DOMXpath($doc);
     $products = $xpath->query('//div[@class="productInfo"]');
     foreach ($products as $entry) {
         $htmlLinks = $entry->getElementsByTagName("a");
         foreach ($htmlLinks as $item) {
             $href = $item->getAttribute("href");
             $link = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
             $html = $this->getHtml($href);
             $doc = new DOMDocument();
             @$doc->loadHTML($html['result']);
             $xpath = new DOMXpath($doc);
             $productUnitPrice = $xpath->query('//p[@class="pricePerUnit"]');
             foreach ($productUnitPrice as $itemPrice) {
                 $unitPrice = preg_replace('/[^0-9.]*/', '', $itemPrice->nodeValue);
                 break;
             }
             $productText = $xpath->query('//div[@class="productText"]');
             foreach ($productText as $itemText) {
                 $description = trim($itemText->nodeValue);
                 break;
             }
             $results['result'][] = array('title' => $link, 'size' => $html['size'], 'unit_price' => $unitPrice, 'description' => $description);
             $total += $unitPrice;
         }
     }
     $results['total'] = $total;
     return json_encode($results);
 }
 public function getJobs()
 {
     $jobs = [];
     $tz = new \DateTimeZone('Europe/London');
     foreach ($this->getRss()->channel->item as $job) {
         $jobClass = new JobModel();
         $explodedTitle = explode(':', (string) $job->title);
         $jobClass->applyurl = (string) $job->guid;
         $jobClass->position = (string) (count($explodedTitle) > 1) ? trim($explodedTitle[1]) : trim($job->title);
         $jobClass->dateadded = (string) (new \DateTime($job->pubDate))->setTimezone($tz)->format('Y-m-d H:i:s');
         $jobClass->description = (string) $job->description;
         $jobClass->sourceid = self::SOURCE_ID;
         $jobClass->company->name = trim($explodedTitle[0]);
         $doc = new \DOMDocument();
         libxml_use_internal_errors(true);
         $doc->loadHTML(file_get_contents($jobClass->applyurl));
         libxml_clear_errors();
         $xpath = new \DOMXpath($doc);
         $elements = $xpath->query("//li[@class='twitter']");
         $jobClass->company->twitter = $elements->length > 0 ? str_replace('@', '', trim($elements->item(0)->textContent)) : '';
         $jobClass->company->logo = '';
         $jobs[] = $jobClass;
     }
     return $jobs;
 }
function hal_parse($url)
{
    $url = trim(html_entity_decode($url), "\"' ");
    $infos = parse_url($url);
    $ip = gethostbyname($infos['host']);
    if ($ip != '193.48.96.10') {
        spip_log("Url invalid", _LOG_ERREUR);
        return;
    }
    spip_log(sprintf("[hal_parse] init_http(%s)", $url), _LOG_DEBUG);
    $content = recuperer_page($url);
    spip_log(sprintf("[hal_parse] init_http(%s): Done", $url), _LOG_DEBUG);
    $dom = new DomDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $str = mb_convert_encoding($content, "HTML-ENTITIES");
    @$dom->loadHTML($str);
    $xpath = new DOMXpath($dom);
    $entries = $xpath->query('//div[@id="res_script"]');
    if ($entries->length == 0) {
        spip_log("No tag found ...", _LOG_ERREUR);
        return;
    }
    $res_script = $dom->saveXML($entries->item(0));
    return $res_script;
}
示例#8
0
 public function getForm($formId, $params, $headers)
 {
     /** @var DOMElement $form */
     $dom = new DomDocument();
     libxml_use_internal_errors(true);
     $dom->loadHTML($this->response());
     $xpath = new DOMXpath($dom);
     $form = $xpath->query("//form[@id='{$formId}']")->item(0);
     $elements = $xpath->query('//input');
     $form_params = [];
     $allowedTypes = ["hidden", "text", "password"];
     foreach ($elements as $element) {
         /** @var DOMElement $element */
         $type = $element->getAttribute("type");
         if (in_array($type, $allowedTypes)) {
             $name = $element->getAttribute("name");
             $value = $element->getAttribute("value");
             $form_params[$name] = $value;
         }
     }
     $headers = array_merge(["Referer" => $this->baseUri], $headers);
     $url = Uri::resolve(new Uri($this->baseUri), $form->getAttribute("action"))->__toString();
     $method = strtoupper($form->getAttribute("method"));
     return ["method" => $method, "url" => $url, "headers" => $headers, "params" => array_merge($form_params, $params)];
 }
function get_image($game, $name, $width, $height)
{
    $url = 'http://steamcommunity.com/market/listings/' . $game . '/' . rawurlencode($name) . '/render?start=0&count=1&currency=1&format=json';
    $response = get_page_html($url);
    $jobject = json_decode($response);
    if (!isset($jobject)) {
        return null;
    }
    // Get the HTML render
    $render_html = $jobject->results_html;
    // Parse the html
    $dom = new DOMDocument();
    $dom->loadHTML($render_html);
    $xpath = new DOMXpath($dom);
    // Get the image
    $img = $xpath->query('//img[@class="market_listing_item_img"]')->item(0);
    if (!isset($img)) {
        return null;
    }
    // Get image src
    $imgurl = $img->getAttribute('src');
    // Remove the pre-set size
    $imgurl = substr($imgurl, 0, strrpos($imgurl, '/'));
    // Replace with our size
    $imgurl .= '/' . $width . 'fx' . $height . 'f';
    return $imgurl;
}
    /**
     * Provide DOMNodeLists of CategoryLink/Name nodes and a collection of categories.
     *
     * @return array[]
     */
    public function provideCategoryNameNodes()
    {
        $doc = Mage::helper('eb2ccore')->getNewDomDocument();
        $doc->loadXML('
			<CategoryLinks>
				<CategoryLink import_mode="Update">
					<Name>Luma Root</Name>
				</CategoryLink>
				<CategoryLink import_mode="Update">
					<Name>Luma Root-Shoes</Name>
				</CategoryLink>
				<CategoryLink import_mode="Update">
					<Name>Luma Root-Shoes-Boots</Name>
				</CategoryLink>
				<!-- The item should end up in Luma Root/Outerwear/Jackets, but not Luma Root/Outerwear -->
				<CategoryLink import_mode="Update">
					<Name>Luma Root-Outerwear-Jackets</Name>
				</CategoryLink>
			</CategoryLinks>
		');
        $xp = new DOMXpath($doc);
        $nodes = $xp->query('/CategoryLinks/CategoryLink[@import_mode!="Delete"]/Name');
        $catCol = $this->getResourceModelMockBuilder('catalog/category_collection')->setMethods(array('addAttributeToSelect', 'getColumnValues', 'getAllIds'))->getMock();
        $catCol->expects($this->any())->method('addAttributeToSelect')->with($this->identicalTo(array('name', 'path', 'id')))->will($this->returnSelf());
        $ids = array(0, 1, 2, 3, 30, 31);
        $names = array('Root Catalog', 'Luma Root', 'Shoes', 'Boots', 'Outerwear', 'Jackets');
        $paths = array('0', '0/1', '0/1/2', '0/1/2/3', '0/1/30', '0/1/30/31');
        $catCol->expects($this->any())->method('getColumnValues')->will($this->returnValueMap(array(array('name', $names), array('path', $paths))));
        $catCol->expects($this->any())->method('getAllIds')->will($this->returnValue($ids));
        return array(array($nodes, $catCol));
    }
示例#11
0
function count_quotations($html)
{
    /* Count the number of quotations using the 'cite' tag
     * (Used to determine if URL should be submitted to Neotext)
     *
     * Credit: http://htmlparsing.com/php.html
     */
    $quotations_count = 0;
    # Parse the HTML
    # The @ before the method call suppresses any warnings that
    # loadHTML might throw because of invalid HTML in the page.
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXpath($dom);
    # Iterate over all the <blockquote> and <q> tags
    $quotations = $xpath->query('//blockquote | //q');
    //foreach($dom->getElementsByTagName('blockquote') as $quote) {
    foreach ($quotations as $quote) {
        $cite_url = $quote->getAttribute('cite');
        // If URL in valid form:
        if (!filter_var($cite_url, FILTER_VALIDATE_URL) === false) {
            $quotations_count = $quotations_count + 1;
        }
    }
    return $quotations_count;
}
示例#12
0
 function testOff()
 {
     $doc = $this->process_post("[bibshow file=custom://data show_links=0][bibcite key=test]", ShowLinks::$data);
     $xpath = new DOMXpath($doc);
     $href = $xpath->evaluate("//a[@class = 'papercite_bibcite']/@href");
     $this->assertEquals(0, $href->length, "There were {$href->length} links detected - expected none");
 }
示例#13
0
 public static function LINKS($url)
 {
     $content = file_get_contents($url);
     $doc = new \DOMDocument();
     $doc->loadHTML($content);
     // \bloc\application::instance()->log($doc);
     $xpath = new \DOMXpath($doc);
     $handle = curl_init("https://validator.nu/?level=error&doc={$url}&out=json");
     curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT']]);
     $report = json_decode(curl_exec($handle));
     $number_of_errors = count($report->messages);
     $files = [['name' => 'index.html', 'content' => $content, 'type' => 'lang-html', 'url' => $url, 'report' => ['count' => count($report->messages), 'errors' => (new \bloc\types\Dictionary($report->messages))->map(function ($item) {
         return ['line' => $item->lastLine ?? 1, 'message' => $item->message];
     })]], ['name' => 'README', 'content' => null, 'type' => 'plain-text', 'url' => base64_encode($url . '/readme.txt')]];
     foreach ($xpath->query("//script[@src and not(contains(@src, 'http'))]") as $file) {
         $src = $file->getAttribute('src');
         $files[] = ['url' => base64_encode($url . '/' . $src), 'name' => substr($src, strrpos($src, '/') + 1), 'content' => null, 'type' => 'lang-js'];
     }
     foreach ($xpath->query("//link[not(contains(@href, 'http')) and contains(@href, '.css')]") as $file) {
         $src = $file->getAttribute('href');
         $uri = $url . '/' . $src;
         $code = substr(get_headers($uri)[0], 9, 3);
         if ($code < 400) {
             $report = json_decode(file_get_contents("https://jigsaw.w3.org/css-validator/validator?output=json&warning=0&profile=css3&uri=" . $uri));
             $count = $report->cssvalidation->result->errorcount;
         } else {
             $report = 'not-found';
             $count = "fix";
         }
         $files[] = ['url' => base64_encode($uri), 'name' => substr($src, strrpos($src, '/') + 1), 'content' => null, 'type' => 'lang-css', 'report' => ['count' => $count, 'errors' => (new \bloc\types\Dictionary($report->cssvalidation->errors ?? []))->map(function ($item) {
             return ['line' => $item->line, 'message' => $item->message];
         })]];
     }
     return $files;
 }
示例#14
0
 /**
  * Returns if significant whitespaces occur in the paragraph.
  *
  * This method checks if the paragraph $element contains significant
  * whitespaces in form of <text:s/> or <text:tab/> elements.
  * 
  * @param DOMElement $element 
  * @return bool
  */
 protected function hasSignificantWhitespace(DOMElement $element)
 {
     $xpath = new DOMXpath($element->ownerDocument);
     $xpath->registerNamespace('text', ezcDocumentOdt::NS_ODT_TEXT);
     $whitespaces = $xpath->evaluate('.//text:s|.//text:tab|.//text:line-break', $element);
     return $whitespaces instanceof DOMNodeList && $whitespaces->length > 0;
 }
示例#15
0
 function process(&$article)
 {
     $owner_uid = $article["owner_uid"];
     if (strpos($article["link"], "threewordphrase.com") !== FALSE) {
         if (strpos($article["plugin_data"], "af_comics,{$owner_uid}:") === FALSE) {
             $doc = new DOMDocument();
             @$doc->loadHTML(fetch_file_contents($article["link"]));
             $basenode = false;
             if ($doc) {
                 $xpath = new DOMXpath($doc);
                 $basenode = $xpath->query("//td/center/img")->item(0);
                 if ($basenode) {
                     $article["content"] = $doc->saveXML($basenode);
                     $article["plugin_data"] = "af_comics,{$owner_uid}:" . $article["plugin_data"];
                 }
             }
         } else {
             if (isset($article["stored"]["content"])) {
                 $article["content"] = $article["stored"]["content"];
             }
         }
         return true;
     }
     return false;
 }
示例#16
0
 public function indexAction()
 {
     SxCms_Acl::requireAcl('ad', 'ad.edit');
     $filename = APPLICATION_PATH . '/var/ads.xml';
     $dom = new DOMDocument();
     $dom->preserveWhiteSpace = false;
     $dom->loadXml(file_get_contents($filename));
     $dom->formatOutput = true;
     $xpath = new DOMXpath($dom);
     $xml = simplexml_import_dom($dom);
     if ($this->getRequest()->isPost()) {
         $ads = $this->_getParam('ad');
         foreach ($ads as $key => $value) {
             $nodeList = $xpath->query("//zone[id='{$key}']/content");
             if ($nodeList->length) {
                 $cdata = $dom->createCDATASection(stripslashes($value));
                 $content = $dom->createElement('content');
                 $content->appendChild($cdata);
                 $nodeList->item(0)->parentNode->replaceChild($content, $nodeList->item(0));
             }
         }
         $dom->save($filename);
         $flashMessenger = $this->_helper->getHelper('FlashMessenger');
         $flashMessenger->addMessage('Advertentie werd succesvol aangepast');
     }
     $this->view->ads = $xml;
 }
示例#17
0
 /**
  * @param string $html HTML document
  * @return boolean|array
  */
 public function HTMLtoLunchArray($html)
 {
     $doc = new DOMDocument();
     @$doc->loadHTML($html);
     $xpath = new DOMXpath($doc);
     $dElements = array(0 => array(2, 3, 4), 1 => array(8, 9, 10), 2 => array(14, 15, 16), 3 => array(20, 21, 22), 4 => array(26, 27, 28));
     $arr = array();
     $i = 0;
     foreach ($dElements as $dId => $dArr) {
         $dayMenu = array();
         foreach ($dArr as $dRow) {
             $element = $xpath->query('//*[@id="lounaslistaTable"]/tr[' . $dRow . ']/td[1]');
             foreach ($element as $e) {
                 $dayMenu[] = trim($e->nodeValue);
             }
         }
         $weekDay = parent::weekNumToText($i);
         $arr[$weekDay] = parent::fixSpaces(trim(implode(' / ', $dayMenu)));
         $i++;
     }
     if (!empty($arr)) {
         return $arr;
     }
     return false;
 }
示例#18
0
 /**
  * Retreives a list of tags for a given resource that are marked
  * "Sujet principal". 
  * 
  * With the "non_principal_fallback" option set to TRUE, in the
  * event that there are no "sujet principal" tags, all the tags will
  * be used instead.
  *
  * (There should probably be a parameter for the string "Sujet
  * principal".)
  *
  * @param $url Optional. Defaults to current page.
  * @param $non_principal_fallback boolean Get all tags if there are NO "sujet principal".
  * @returns folksoPageDataMeta object
  */
 public function buildMeta($url = NULL, $max_tags = 0, $non_principal_fallback = NULL)
 {
     $mt = new folksoPageDataMeta();
     $this->getData($url);
     /** could set a maximum here, but instead we can
                                   set that at display time, since we might be 
                                   reusing data. 
     
                                   NB: if $url is NULL, getData() will use
                                   $this->url anyway.
                               **/
     if ($this->is_valid()) {
         $xpath = new DOMXpath($this->xml_DOM());
         // reusing existing DOM, maybe
         //$tag_princ is a DOMNodelist object
         $tag_princ = $xpath->query('//taglist/tag[metatag="Sujet principal"]');
         // 'Sujet principal' only
         if ($tag_princ->length > 0) {
             foreach ($tag_princ as $element) {
                 $tagname = $element->getElementsByTagName('display');
                 $mt->add_principal_keyword($tagname->item(0)->textContent);
             }
         }
         // All tags, when no 'sujet principal' is found.
         $all_tags = $xpath->query('//taglist/tag');
         if ($all_tags->length > 0) {
             foreach ($all_tags as $element) {
                 $tagname = $element->getElementsByTagName('display');
                 $mt->add_all_tags($tagname->item(0)->textContent);
             }
         }
         $this->mt = $mt;
         return $mt;
     }
 }
示例#19
0
 /**
  * @param string $html HTML document
  * @return boolean|array
  */
 public function HTMLtoLunchArray($html)
 {
     $doc = new DOMDocument();
     @$doc->loadHTML($html);
     $xpath = new DOMXpath($doc);
     $elements = $xpath->query('//*[@id="o-learys-forum-helsinki"]');
     $i = 0;
     $arr = array();
     foreach ($elements as $element) {
         $nodes = $element->childNodes;
         foreach ($nodes as $node) {
             $htmlString = $doc->saveHTML($node);
             if (preg_match('/<strong>O\'Learys Forum Helsinki<\\/strong>/', $htmlString)) {
                 preg_match_all("/<strong>([a-zA-Z]+) [0-9\\. ]+<\\/strong> <p>([a-zA-Z0-9\\’\\'\\,\\.\\-\\_\\)\\(äöÄÖ ]+)10€/", $htmlString, $res);
                 if (isset($res[2])) {
                     foreach ($res[2] as $result) {
                         $weekDay = parent::weekNumToText($i);
                         $arr[$weekDay] = $result;
                         $i++;
                     }
                 }
             }
         }
     }
     if (empty($arr)) {
         return false;
     }
     return $arr;
 }
示例#20
0
 /**
  * @param string $html HTML document
  * @return boolean|array
  */
 public function HTMLtoLunchArray($html)
 {
     $doc = new DOMDocument();
     @$doc->loadHTML($html);
     $xpath = new DOMXpath($doc);
     $dElements = array(0 => array(2, 3, 4));
     $arr = array();
     foreach ($dElements as $dId => $dArr) {
         $dayMenu = array();
         foreach ($dArr as $dRow) {
             $element = $xpath->query('/html/body/div[2]/div/div/div/div/div[' . $dRow . ']/div[1]');
             foreach ($element as $e) {
                 $dish = ucfirst(strtolower(parent::cleanStr(utf8_decode(parent::fixSpaces(trim($e->nodeValue))))));
                 $dish = preg_replace('/\\([a-z, ]+\\)/e', 'strtoupper("$0")', $dish);
                 $dayMenu[] = $dish;
             }
         }
         $weekDay = parent::today();
         $arr[$weekDay] = implode(' / ', $dayMenu);
     }
     if (!empty($arr)) {
         return $arr;
     }
     return false;
 }
示例#21
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     // get already stored countries
     $qb = $manager->createQueryBuilder();
     $qb->from(Country::class, 'c', 'c.code');
     $qb->select('c');
     $existingCountries = $qb->getQuery()->getResult();
     // load xml
     $file = dirname(__FILE__) . '/../countries.xml';
     $doc = new \DOMDocument();
     $doc->load($file);
     $xpath = new \DOMXpath($doc);
     $elements = $xpath->query('/Countries/Country');
     if (!is_null($elements)) {
         /** @var $element DOMNode */
         foreach ($elements as $element) {
             /** @var $child DOMNode */
             foreach ($element->childNodes as $child) {
                 if (isset($child->nodeName)) {
                     if ($child->nodeName == 'Name') {
                         $countryName = $child->nodeValue;
                     }
                     if ($child->nodeName == 'Code') {
                         $countryCode = $child->nodeValue;
                     }
                 }
             }
             $country = array_key_exists($countryCode, $existingCountries) ? $existingCountries[$countryCode] : new Country();
             $country->setName($countryName);
             $country->setCode($countryCode);
             $manager->persist($country);
         }
     }
     $manager->flush();
 }
示例#22
0
 function populate_resource($id, $overrideExportable = false)
 {
     //local SOLR index for fast searching
     $ci =& get_instance();
     $ci->load->library('solr');
     $ci->solr->clearOpt('fq');
     $ci->solr->setOpt('fq', '+id:' . $id);
     $this->overrideExportable = $overrideExportable;
     $result = $ci->solr->executeSearch(true);
     if (sizeof($result['response']['docs']) == 1) {
         $this->index = $result['response']['docs'][0];
     }
     //local XML resource
     $xml = $this->ro->getSimpleXML();
     $xml = addXMLDeclarationUTF8($xml->registryObject ? $xml->registryObject->asXML() : $xml->asXML());
     $xml = simplexml_load_string($xml);
     $xml = simplexml_load_string(addXMLDeclarationUTF8($xml->asXML()));
     if ($xml) {
         $this->xml = $xml;
         $rifDom = new DOMDocument();
         $rifDom->loadXML($this->ro->getRif());
         $gXPath = new DOMXpath($rifDom);
         $gXPath->registerNamespace('ro', 'http://ands.org.au/standards/rif-cs/registryObjects');
         $this->gXPath = $gXPath;
     }
 }
 public function fetchExcuse($event, $queue)
 {
     $url = 'http://devanswers.ru';
     $request = new Request(['url' => $url, 'resolveCallback' => function ($data, $headers, $code) use($event, $queue) {
         $dom = new \DOMDocument();
         $dom->loadHTML($data);
         $xpath = new \DOMXpath($dom);
         // XPath to the excuse text
         $result = $xpath->query('/html/head/script[6]');
         if ($result->length > 0) {
             //                        $queue->ircPrivmsg($event->getSource(), $result->item(0)->nodeValue);
             $queue->ircPrivmsg($event->getSource(), print_r($result));
         }
         if ($data->getStatusCode() !== 200) {
             $this->getLogger()->notice('[DEVANS] Site responded with error', ['code' => $data->getStatusCode(), 'message' => $data->getReasonPhrase()]);
             $queue->ircPrivmsg($event->getSource(), 'Sorry, no excuse was found');
             return;
         }
         $this->getLogger()->info('[DEVANS] Site successful return');
     }, 'rejectCallback' => function ($data, $headers, $code) use($event, $queue) {
         $this->getLogger()->notice('[DEVANS] Site failed to respond');
         $queue->ircPrivmsg($event->getSource(), 'Sorry, there was a problem communicating with the site');
     }]);
     $this->getEventEmitter()->emit('http.request', [$request]);
 }
示例#24
0
 protected function HTMLtoLunchArray($html)
 {
     $doc = new DOMDocument();
     @$doc->loadHTML($html);
     $xpath = new DOMXpath($doc);
     $dElements = array(0 => array(1), 1 => array(2), 2 => array(3), 3 => array(4), 4 => array(5));
     $arr = array();
     foreach ($dElements as $dId => $dArr) {
         $dayMenu = '';
         foreach ($dArr as $dRow) {
             $element = $xpath->query('/html/body/div[2]/div[2]/article/div/div/p[' . $dRow . ']');
             foreach ($element as $e) {
                 $dayMenuExploded = explode(PHP_EOL, $e->nodeValue);
                 $foodArray = array();
                 foreach ($dayMenuExploded as $foods) {
                     $foods = parent::cleanStr($foods);
                     if (!empty($foods)) {
                         $foodArray[] = preg_replace('/([\\t0-9, ]+$)/', '', $foods);
                     }
                 }
                 $dayMenu = implode(' / ', $foodArray);
             }
         }
         $weekDay = parent::weekNumToText($dId);
         $arr[$weekDay] = parent::fixSpaces(preg_replace('/[0-9, ]+$/', '', $dayMenu));
     }
     if (!empty($arr)) {
         return $arr;
     }
     return false;
 }
示例#25
0
 private function CreateDomNodeListFromScrapedDataWithXpathQuery()
 {
     $domDocument = new \model\DOMDOMDocument($this->GetScrapedData());
     $xpath = new DOMXpath($domDocument);
     $domNodeList = $xpath->GetDomAfterFiltration($this->m_xpathQuery);
     return $domNodeList;
 }
 public function metascore($type = "game", $name, $platform = NULL)
 {
     if (!$name) {
         throw new Exception("No parameters.");
     }
     $name = self::stripUrl($name);
     if ($platform) {
         $platform = self::stripUrl($platform);
     }
     $dom = new DomDocument();
     if ($type != ("movie" || "tv")) {
         $dom->loadHtmlFile("http://www.metacritic.com/{$type}/{$platform}/{$name}/");
         //replace this with Metacritics JSON search
     } else {
         $dom->loadHtmlFile("http://www.metacritic.com/{$type}/{$name}/");
         //replace this with Metacritics JSON search
     }
     $xpath = new DOMXpath($dom);
     $nodes = $xpath->evaluate("//span[@property='v:average']");
     if ($nodes) {
         return $nodes->item(0)->nodeValue;
     } else {
         throw new Exception("Could not find Metascore.");
     }
 }
 /**
  * Insert content template
  *
  * @param ilPageObject $a_pg_obj page object
  * @param string $a_hier_id Hierarchical ID
  * @param string $a_pc_id pc id
  * @param int $a_page_templ template page id
  */
 function create($a_pg_obj, $a_hier_id, $a_pc_id, $a_page_templ)
 {
     $source_id = explode(":", $a_page_templ);
     $source_page = ilPageObjectFactory::getInstance($source_id[1], $source_id[0]);
     $source_page->buildDom();
     $source_page->addHierIds();
     $hier_ids = $source_page->getHierIds();
     $copy_ids = array();
     foreach ($hier_ids as $hier_id) {
         // move top level nodes only
         if (!is_int(strpos($hier_id, "_"))) {
             if ($hier_id != "pg" && $hier_id >= $a_hid) {
                 $copy_ids[] = $hier_id;
             }
         }
     }
     asort($copy_ids);
     // get the target parent node
     $pos = explode("_", $a_pos);
     array_pop($pos);
     $parent_pos = implode($pos, "_");
     if ($parent_pos != "") {
         $target_parent = $a_pg_obj->getContentNode($parent_pos);
     } else {
         $target_parent = $a_pg_obj->getNode();
     }
     //$source_parent = $source_page->getContentNode("pg");
     $curr_node = $a_pg_obj->getContentNode($a_hier_id, $a_pcid);
     foreach ($copy_ids as $copy_id) {
         $source_node = $source_page->getContentNode($copy_id);
         $new_node = $source_node->clone_node(true);
         $new_node->unlink_node($new_node);
         if ($succ_node = $curr_node->next_sibling()) {
             $succ_node->insert_before($new_node, $succ_node);
         } else {
             //echo "movin doin append_child";
             $target_parent->append_child($new_node);
         }
         //$xpc = xpath_new_context($a_pg_obj->getDomDoc());
         $xpath = new DOMXpath($a_pg_obj->getDomDoc());
         //var_dump($new_node->myDOMNode);
         //echo "-".$new_node->get_attribute("PCID")."-"; exit;
         if ($new_node->get_attribute("PCID") != "") {
             $new_node->set_attribute("PCID", "");
         }
         $els = $xpath->query(".//*[@PCID]", $new_node->myDOMNode);
         foreach ($els as $el) {
             $el->setAttribute("PCID", "");
         }
         $curr_node = $new_node;
     }
     $a_pg_obj->update();
     //$this->node = $this->createPageContentNode();
     /*$a_pg_obj->insertContent($this, $a_hier_id, IL_INSERT_AFTER, $a_pc_id);
     		$this->map_node =& $this->dom->create_element("Map");
     		$this->map_node =& $this->node->append_child($this->map_node);
     		$this->map_node->set_attribute("Latitude", "0");
     		$this->map_node->set_attribute("Longitude", "0");
     		$this->map_node->set_attribute("Zoom", "3");*/
 }
示例#28
0
 function _list()
 {
     error_reporting(E_ALL);
     list($code, $body) = $this->_request('status');
     $d = new DOMDocument();
     $d->loadXML($body);
     $xp = new DOMXpath($d);
     foreach ($xp->query('//language') as $c) {
         $name = $code = '';
         foreach ($c->childNodes as $n) {
             switch (strtolower($n->nodeName)) {
                 case 'name':
                     $name = $n->textContent;
                     break;
                 case 'code':
                     $code = $n->textContent;
                     break;
             }
         }
         if (!$code) {
             continue;
         }
         $this->stdout->write(sprintf("%s (%s)\n", $code, $name));
     }
 }
示例#29
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $metadata = $manager->getClassMetaData(get_class(new Operator()));
     $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
     $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
     $i = 1;
     $file = dirname(__FILE__) . '/../../operators.xml';
     $doc = new \DOMDocument();
     $doc->load($file);
     $xpath = new \DOMXpath($doc);
     $elements = $xpath->query('/operators/operator');
     if (!is_null($elements)) {
         /** @var $element DOMNode */
         foreach ($elements as $element) {
             $operator = new Operator();
             $operator->setId($i);
             $operator->setType($this->getTypeForString($element->getAttribute('type')));
             $operator->setOperator($element->getAttribute('operator'));
             $operator->setInputType($element->getAttribute('inputType'));
             // translations
             $translations = $xpath->query('translations/translation', $element);
             $this->processTranslations($manager, $operator, $translations);
             // values
             $values = $xpath->query('values/value', $element);
             $this->processValues($manager, $xpath, $operator, $values);
             $manager->persist($operator);
             ++$i;
         }
     }
     $manager->flush();
 }
示例#30
-1
 /**
  * 
  */
 public function rerender()
 {
     $cssFileContent = '';
     $components = $this->uiComposer->getUiComponents();
     //Get all CSS file content
     foreach ($components as $component) {
         //TODO: check renderresult instead of component type
         if ($component instanceof HtmlWidget) {
             $cssFileContent .= $component->getRenderResult()->cssFileContent;
         }
     }
     if (trim($cssFileContent)) {
         // build file
         $cssFileContent = $this->minify($cssFileContent);
         $httpFileNamePath = '/generated/' . md5($cssFileContent) . '.css';
         $fileNamePath = 'public' . $httpFileNamePath;
         if (!file_exists($fileNamePath)) {
             file_put_contents($fileNamePath, $cssFileContent);
         }
         // get $doc and add the href
         $doc = $this->uiComposer->getDoc();
         //TODO: use composer xpath?
         $xPath = new \DOMXpath($this->uiComposer->getDoc());
         $linkElement = $xPath->query('//link[@id="css-file"]');
         //TODO url function missing
         $linkElement->item(0)->setAttribute('href', FC::assetLink($httpFileNamePath));
     }
     $this->needsRerender = false;
 }