newDocumentXML() public static method

Chainable.
public static newDocumentXML ( unknown_type $markup = null, $charset = null ) : phpQueryObject | QueryTemplatesSource | QueryTemplatesParse | QueryTemplatesSourceQuery
$markup unknown_type
return phpQueryObject | QueryTemplatesSource | QueryTemplatesParse | QueryTemplatesSourceQuery
Ejemplo n.º 1
0
 public function testExtend()
 {
     $newMethods = array('newMethod1' => array($this, 'callback1'), 'newMethod2' => array($this, 'callback2'));
     phpQuery::extend('phpQueryObject', $newMethods);
     $doc = phpQuery::newDocumentXML("<div/>");
     $this->assertTrue($doc->newMethod1() == $doc, '$doc->newMethod1 == $doc');
     $this->assertTrue($doc->newMethod2() == "callback2", '$doc->newMethod1 == "callback2"');
 }
Ejemplo n.º 2
0
 protected function _getCurrencyArray()
 {
     $client = new Zend_Http_Client($this->url);
     $response = $client->request('GET');
     if ($response->getStatus() != 200) {
         throw new Zend_Exception('Не удалось получить страницу курсов валют');
     }
     $body = $response->getBody();
     $phpq = phpQuery::newDocumentXML($body);
     $items = $phpq->find('ValCurs Valute');
     $result = array();
     foreach ($items as $el) {
         $code = pq($el)->find('CharCode')->text();
         $result[$code] = array('name' => pq($el)->find('Name')->text(), 'value' => pq($el)->find('Value')->text(), 'nominal' => pq($el)->find('Nominal')->text());
     }
     return $result;
 }
Ejemplo n.º 3
0
 public function processFeeds($time)
 {
     if ($time >= $this->currentTime + self::PERIOD) {
         $this->currentTime = $time;
         $timers = $this->rssDb['timers'] ?: [];
         $rssStr = [];
         foreach ($this->pluginConfig['feeds'] as $feedName => $feedData) {
             $timer = array_key_exists($feedName, $timers) ? $timers[$feedName] : 0;
             if (!$feedData['enabled'] || $timer && $timer + $this->pluginConfig['refresh_timeout'] > $time) {
                 //                    \Util::debug('RSS not ready');
                 continue;
             }
             //                \Util::debug('RSS get ' . $feedData['url']);
             $response = $this->http->getResponse('GET', $feedData['url']);
             if ($response && $response->getStatusCode() === 200 && ($body = $response->getBody())) {
                 //                    \Util::debug('RSS got');
                 $format = array_key_exists('format', $feedData) ? $feedData['format'] : $this->pluginConfig['format'];
                 $items = \phpQuery::newDocumentXML($body)->find('channel item');
                 rsort($items);
                 foreach ($items as $item) {
                     \Util::debug($item);
                     $dateTime = \DateTime::createFromFormat(\DateTime::RSS, (string) pq($item)->find('pubDate')->text());
                     $matches = [];
                     \Util::debug([$dateTime->getTimestamp(), $timer]);
                     if ($dateTime->getTimestamp() > $timer && preg_match_all('/%(\\w+)%/', $format, $matches) && count($matches)) {
                         $timer = $dateTime->getTimestamp();
                         $matchesCount = count($matches[0]);
                         for ($i = 0; $i < $matchesCount; $i++) {
                             $rssStr[] = preg_replace($matches[0][$i], (string) pq($item)->find($matches[1][$i])->text(), $format);
                         }
                     }
                 }
             }
             if (count($rssStr)) {
                 foreach ($feedData['chats'] as $chatName) {
                     $this->core->send($chatName, implode(PHP_EOL, $rssStr));
                 }
                 $timers[$feedName] = $timer;
             }
         }
         $this->rssDb['timers'] = $timers;
     }
 }
Ejemplo n.º 4
0
 function parse($file)
 {
     $authors = $posts = $attachments = $post = $author_snapshots = $authors_meta = array();
     if (!class_exists('phpQueryObject')) {
         require trailingslashit(TEMPLATEPATH) . 'functions/phpQuery/phpQuery.php';
     }
     $file_content = file_get_contents($file);
     if (!$file_content) {
         return new WP_Error('xml_parse_error', __('There was an error when reading this Kipling DTD file', 'anno'));
     }
     phpQuery::newDocumentXML($file_content);
     // Made up post IDs just for sanities sake, and parent relationship
     $post_id = 1;
     $articles = pq('article');
     // Lets make sure we have article tags
     $num_articles = $articles->length();
     if (empty($num_articles)) {
         return new WP_Error('xml_parse_article_error', __('This does not appear to be a Kipling DTD file, no articles could be found', 'anno'));
     }
     // Process articles, this contains all catergory, tag, author, term etc... processing.
     foreach ($articles as $article) {
         $article = pq('article');
         $article_meta = pq('article-meta', $article);
         $article_back = pq('back', $article);
         $post['post_type'] = 'article';
         $post['post_content_filtered'] = trim(pq('> body', $article)->html());
         $post['post_title'] = trim(pq('article-title', $article_meta)->text());
         $post['postmeta'][] = array('key' => '_anno_subtitle', 'value' => trim(pq('subtitle', $article_meta)->text()));
         // Auto generated
         $post['guid'] = '';
         $abstract = pq('abstract', $article_meta);
         // We don't want the title of the abstract
         pq('title', $abstract)->remove();
         // Just the text, wpautop is run on it later (excerpt)
         $post['post_excerpt'] = trim($abstract->text());
         // Post content gets generated by Annotum theme from the XML on wp_insert_post. We can leave it empty for now.
         $post['post_content'] = '';
         $post['post_id'] = $post_id;
         // Generated from post title on insert
         $post['post_name'] = '';
         $pub_date = pq('pub-date', $article_meta);
         $pub_date = $this->parse_date($pub_date);
         $post['post_date'] = (string) $pub_date;
         $post['post_date_gmt'] = (string) $pub_date;
         $post['status'] = 'draft';
         // Reflect in post_state meta as well.
         $post['postmeta'][] = array('key' => '_post_state', 'value' => 'draft');
         // Not used in Kipling DTD, but set for data structure integrity required by the importer
         $post['post_parent'] = 0;
         $post['menu_order'] = 0;
         $post['post_password'] = '';
         $post['is_sticky'] = 0;
         $post['ping_status'] = '';
         $post['comment_status'] = '';
         // Grab the category(ies). Annotum DTD should contain only one, Kipling DTD does not contain this requirement.
         foreach (pq('subject', $article_meta) as $category) {
             $category = pq($category);
             // We really don't care about the global categories, categories aren't defined outside of an article in the XML
             $cat_name = trim($category->text());
             if (!empty($cat_name)) {
                 $post['terms'][] = array('name' => $cat_name, 'slug' => sanitize_title($cat_name), 'domain' => 'article_category');
             }
         }
         // Grab the tags.
         foreach (pq('kwd', $article_meta) as $tag) {
             $tag = pq($tag);
             // We really don't care about the global tags, tags aren't defined outside of an article in the XML
             $tag_name = trim($tag->text());
             if (!empty($tag_name)) {
                 $post['terms'][] = array('name' => $tag_name, 'slug' => sanitize_title($tag_name), 'domain' => 'article_tag');
             }
         }
         // First author is the primary author, possible @todo - look for primary-author contrib type
         $first_author_check = true;
         $default_author_id = $first_author_id = 1;
         // Grab the author(s).
         foreach (pq('contrib', $article_meta) as $contributor) {
             $contributor = pq($contributor);
             $author_arr = $this->parse_author($contributor);
             $author = $author_arr['author'];
             $author_meta = $author_arr['author_meta'];
             // Check for author_id existance, if not, assign one.
             if (empty($author['author_id'])) {
                 $author['author_id'] = $default_author_id;
             }
             // Save in authors
             $authors[$author['author_id']] = $author;
             // Save in authors_meta, consistant with author_id to match on import of user
             $authors_meta[$author['author_id']] = $author_meta;
             if ($first_author_check) {
                 $post['post_author'] = $author['author_id'];
             }
             $author_snapshots[] = $this->author_snapshot($author, $author_meta);
             if ($first_author_check) {
                 // Used in attachment assignment
                 $first_author_id = $author['author_id'];
             }
             // We'll convert this in the import process
             $post['postmeta'][] = array('key' => '_anno_author_' . $author['author_id'], 'value' => $author['author_id']);
             $first_author_check = false;
             $default_author_id++;
         }
         // Acknowledgements
         $ack = trim(pq('ack p', $article_back)->text());
         if (!empty($ack)) {
             $post['postmeta'][] = array('key' => '_anno_acknowledgements', 'value' => $ack);
         }
         // Funding
         $funding = trim(pq('funding-statement', $article_meta)->text());
         if (!empty($funding)) {
             $post['postmeta'][] = array('key' => '_anno_funding', 'value' => $funding);
         }
         // Appendices
         $appendices = pq('app', $article_back);
         $appendix_array = array();
         foreach ($appendices as $appendix) {
             $appendix = trim(pq($appendix)->html());
             if (!empty($appendix)) {
                 $appendix_array[] = $appendix;
             }
         }
         if (!empty($appendix_array)) {
             // Process to HTML on import
             $post['postmeta'][] = array('key' => '_anno_appendices', 'value' => serialize($appendix_array));
         }
         // References
         $references = pq('ref', $article_back);
         $ref_array = array();
         $single_ref = array('doi' => '', 'text' => '', 'pmid' => '', 'figures' => '', 'url' => '');
         foreach ($references as $reference) {
             $reference = pq($reference);
             // For now, just support mixed-citations as text.
             $ref_id = $reference->attr('id');
             $ref_data['text'] = trim($reference->text());
             if (empty($ref_id)) {
                 $ref_array[] = $ref_data;
             } else {
                 $ref_array[$ref_id] = $ref_data;
             }
         }
         // Attachments
         // Modification for post_id
         $attachment_id_mod = 0;
         // $pub_date is the date gathered from the post data.
         $attachment_template = array('upload_date' => (string) $pub_date, 'post_date' => (string) $pub_date, 'post_date_gmt' => (string) $pub_date, 'post_author' => $first_author_id, 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_id' => '', 'post_content' => '', 'post_content_filtered' => '', 'postmeta' => '', 'guid' => '', 'attachment_url' => '', 'status' => 'inherit', 'post_title' => '', 'ping_status' => '', 'menu_order' => '', 'post_password' => '', 'terms' => '', 'comment_status' => '', 'is_sticky' => '', 'post_excerpt' => '', 'post_name' => '');
         $inline_images = pq('> body inline-graphic', $article);
         foreach ($inline_images as $img) {
             $img = pq($img);
             $img_url = $img->attr('xlink:href');
             // Dont save chart api images (most likely formulas)
             if (!empty($img_url) && strpos($img_url, 'google.com/chart') === false) {
                 $post_meta = array();
                 $alt_text = pq('alt-text', $img)->html();
                 if (!empty($alt_text)) {
                     $post_meta[] = array('key' => '_wp_attachment_image_alt', 'value' => $alt_text);
                 }
                 $attachment_title = !empty($alt_text) ? $alt_text : end(explode('/', $img_url));
                 $attachments[] = array_merge($attachment_template, array('post_id' => $post_id . '.' . $attachment_id_mod, 'guid' => $img_url, 'attachment_url' => $img_url, 'post_parent' => $post_id, 'title' => trim($attachment_title), 'postmeta' => $post_meta, 'post_title' => $img_url));
                 $attachment_id_mod++;
             }
         }
         // Find media and save as attachment
         $media_images = pq('> body media', $article);
         foreach ($media_images as $media_image) {
             $media_image = pq($media_image);
             // Parse Media will return an array with:
             // attachment_url
             // guid
             // post_title
             // post_content
             // postmeta
             $media_array = $this->parse_media($media_image);
             if (is_array($media_array) && !empty($media_array['attachment_url'])) {
                 // Check if this is a figure image
                 $figure = $media_image->parent('fig');
                 $figure_html = trim($figure->html());
                 $caption = '';
                 if (!empty($figure_html)) {
                     $label = pq('label', $figure)->html();
                     $caption = pq('caption', $figure)->html();
                     $post_meta[] = array('key' => '_anno_attachment_image_label', 'value' => $label);
                 }
                 $attachment = array_merge($media_array, array('post_id' => $post_id . '.' . $attachment_id_mod, 'post_parent' => $post_id, 'postmeta' => array_merge($post_meta, $media_array['postmeta'])));
                 $attachments[] = array_merge($attachment_template, $attachment);
                 $attachment_id_mod++;
             }
         }
         $comments = pq('response');
         foreach ($comments as $comment) {
             $comment = pq($comment);
             $comment_content = pq('body', $comment)->html();
             $comment_date = $this->parse_date(pq('pub-date', $comment));
             $comment_author_arr = $this->parse_author(pq('contrib', $comment));
             $comment_author = $comment_author_arr['author'];
             $post['comments'][] = array('comment_id' => '', 'comment_author' => (string) $comment_author['author_display_name'], 'comment_author_email' => (string) $comment_author['author_email'], 'comment_author_IP' => '', 'comment_author_url' => (string) $comment_author['author_url'], 'comment_date' => (string) $comment_date, 'comment_date_gmt' => '', 'comment_content' => $comment_content, 'comment_approved' => 1, 'comment_type' => '', 'comment_parent' => '', 'comment_user_id' => 0, 'commentmeta' => array());
         }
         // Save our author snapshots
         $post['postmeta'][] = array('key' => '_anno_author_snapshot', 'value' => serialize($author_snapshots));
         $posts[] = $post;
         // Concat, both indexed
         $posts = array_merge($posts, $attachments);
     }
     return array('authors' => $authors, 'authors_meta' => $authors_meta, 'posts' => $posts, 'categories' => array(), 'tags' => array(), 'terms' => array(), 'base_url' => '', 'version' => 1.1);
 }
Ejemplo n.º 5
0
 /**
  * @param $document
  * @param string $type
  */
 public static function initPhpQuery($document, $type = 'html')
 {
     try {
         if ($type == 'html') {
             phpQuery::newDocumentHTML($document);
         } else {
             $document = str_replace('encoding="gbk"', 'encoding="UTF-8"', $document);
             phpQuery::newDocumentXML($document);
         }
         usleep(2000000);
     } catch (Exception $e) {
         self::outError('phpQueryException', $e->getMessage());
         exit;
     }
 }
/**
 * AJAX handler that looks up an article based on PMID and parses the data for a reference.
 * Echos a JSON encoded array
 * 
 * @return void
 */
function anno_reference_import_doi()
{
    check_ajax_referer('anno_import_doi', '_ajax_nonce-import-doi');
    if (!isset($_POST['doi'])) {
        anno_reference_error_response();
    } else {
        $doi = $_POST['doi'];
    }
    $lookup_response = array('message' => 'error', 'text' => _x('An error has occurred, please try again later', 'pmid lookup error message', 'anno'));
    // DOIs cannot contain any control characters. As defined here: http://www.doi.org/handbook_2000/appendix_1.html
    $doi = trim($doi);
    if (preg_match('/[\\x00-\\x1F\\x7F]/', $doi)) {
        anno_reference_error_response(_x('Invalid DOI', 'pmid lookup error message', 'anno'));
    }
    // Generate the URL for lookup
    $crossref_login = cfct_get_option('crossref_login');
    $crossref_pass = cfct_get_option('crossref_pass');
    // Empty login, or empty password and login is not an email.
    if (empty($crossref_login) || empty($crossref_pass) && !anno_is_valid_email($crossref_login)) {
        anno_reference_error_response(_x('Invalid CrossRef Login', 'pmid lookup error message', 'anno'));
    } else {
        if (empty($croossref_pass)) {
            $url = 'http://www.crossref.org/openurl/?pid=' . $crossref_login . '&id=doi:' . $doi . '&noredirect=true';
        } else {
            $url = 'http://www.crossref.org/openurl/?pid=' . $crossref_login . ':' . $crossref_pass . '&id=doi:' . $doi . '&noredirect=true';
        }
    }
    // Use wp.com functions if available for lookup.
    if (function_exists('vip_safe_wp_remote_get')) {
        $response = vip_safe_wp_remote_get($url);
    } else {
        $response = wp_remote_get($url);
    }
    if (is_wp_error($response) || isset($response['response']['code']) && $response['response']['code'] != 200 || !isset($response['body'])) {
        anno_reference_error_response();
    } else {
        include_once CFCT_PATH . 'functions/phpquery/phpquery.php';
        phpQuery::newDocumentXML($response['body']);
        phpQuery::getDocument();
        $html = pq('html');
        // If we find an HTML tag, echo error.
        if ($html->length > 0) {
            // We should only hit an HTML page for malformed URLs or invalid logins
            // @TODO error for invalid login.
            anno_reference_error_response(_x('Invalid DOI', 'pmid lookup error message', 'anno'));
        }
        $query_status = pq('query')->attr('status');
        // Error if unresolved
        if ($query_status == 'unresolved') {
            $lookup_response = anno_reference_error_response(pq('msg')->text());
        } else {
            if ($query_status == 'resolved') {
                $text = '';
                // There should only be a single 'first' author.
                $prime_author = pq('contributor[sequence="first"][contributor_role="author"]');
                $author_text = anno_reference_doi_process_author($prime_author);
                if (!empty($author_text)) {
                    $author_arr[] = $author_text;
                }
                $additional_authors = pq('contributor[sequence="additional"][contributor_role="author"]');
                foreach ($additional_authors as $additional_author) {
                    $additional_author = pq($additional_author);
                    $author_text = anno_reference_doi_process_author($additional_author);
                    if (!empty($author_text)) {
                        $author_arr[] = $author_text;
                    }
                }
                $text .= implode(', ', $author_arr) . '. ';
                // Title
                $title = pq('article_title')->text();
                if (!empty($title)) {
                    // Titles do not have periods
                    $text .= $title . '. ';
                }
                // Source
                $source = pq('journal_title')->text();
                if (!empty($source)) {
                    $text .= $source . '. ';
                }
                // Date, Volume, Issue, Page
                $date_meta = '';
                $date = pq('year')->text();
                $volume = pq('volume')->text();
                $issue = pq('issue')->text();
                $first_page = pq('first_page')->text();
                $last_page = pq('last_page')->text();
                if (!empty($date)) {
                    $date_meta .= $date;
                }
                if (!empty($volume) || !empty($issue) || !empty($page)) {
                    $date_meta .= ';';
                    if (!empty($volume)) {
                        $date_meta .= $volume;
                    }
                    if (!empty($issue)) {
                        $date_meta .= '(' . $issue . ')';
                    }
                    if (!empty($first_page)) {
                        $date_meta .= ':' . $first_page;
                    }
                    if (!empty($last_page)) {
                        $date_meta .= '-' . $last_page;
                    }
                }
                if (!empty($date_meta)) {
                    $text .= $date_meta . '. ';
                }
                $text .= _x('DOI:', 'Reference text for doi lookup', 'anno') . $doi . '.';
                $lookup_response = array('message' => 'success', 'text' => esc_textarea($text));
            } else {
                anno_reference_error_response();
            }
        }
    }
    echo json_encode($lookup_response);
    die;
}
Ejemplo n.º 7
0
<?php

// Copyright 2014 David Lippman for Lumen Learning
// GPL Licensed
//
// Script for doing modifications to a common cartridge file
$file = "filename.zip";
require "phpQuery-onefile.php";
$zip = new ZipArchive();
$zip->open($file);
//read in manifest file
phpQuery::newDocumentXML($zip->getFromName("imsmanifest.xml"));
//read resource list so we know what file to look in for things
$ref = pq("resource");
$reflist = array();
$reftype = array();
foreach ($ref as $r) {
    $reflist[pq($r)->attr("identifier")] = pq($r)->attr("href");
    $reftype[pq($r)->attr("identifier")] = pq($r)->attr("type");
}
$cnt = 0;
//this accesses all the learning module items
//so this script will only modify items actually listed in the modules
$base = pq("item[identifier='LearningModules'] > item");
foreach ($base as $item) {
    $moduletitle = pq($item)->children("title")->html();
    $pgs = pq($item)->children("item");
    foreach ($pgs as $pg) {
        $title = addslashes(pq($pg)->children("title")->html());
        $iref = pq($pg)->attr("identifierref");
        if ($reftype[$iref] == "webcontent") {
Ejemplo n.º 8
0
 /**
  * Fetch api endpoint response
  *
  * @param $endpoint
  * @param string $data
  * @param string $verb
  * @return mixed
  * @throws Exception
  */
 public function fetch($endpoint, $data = "", $verb = 'GET')
 {
     $queryStr = "";
     if ($data instanceof \phpQuery) {
         $data = (string) $data;
     } else {
         if (is_array($data)) {
             $queryStr = http_build_query($data);
             $data = "";
         }
     }
     $context = stream_context_create(array('http' => array('method' => $verb, 'header' => $this->getAuthHeader(), 'content' => $data)));
     $url = "{$this->apiUri}?srv={$endpoint}&{$queryStr}";
     $xml = file_get_contents($url, false, $context);
     $response = \phpQuery::newDocumentXML($xml);
     if ($response['error']->length > 0) {
         throw new Exception($response['error']->text(), $response['error']->attr('number'), (string) $response);
     }
     return $response;
 }
Ejemplo n.º 9
0
 public function consulta()
 {
     require 'assets/lib/phpQuery/phpQuery.php';
     $q = htmlspecialchars($this->input->get_post('q'));
     $filtro = $this->input->get_post('filtro');
     $start = $this->input->get_post('start') ? '&start=' . $this->input->get_post('start') : '&start=0';
     //busqueda avanzada
     $as_q = $this->input->get_post('as_q');
     $as_epq = $this->input->get_post('as_epq');
     $as_oq = $this->input->get_post('as_oq');
     $as_eq = $this->input->get_post('as_eq');
     $as_ft = $this->input->get_post('as_ft');
     $as_filetype = $this->input->get_post('as_filetype');
     $as_qdr = $this->input->get_post('as_qdr');
     $as_occt = $this->input->get_post('as_occt');
     $as_dt = $this->input->get_post('as_dt');
     $as_sitesearch = $this->input->get_post('as_sitesearch');
     //fin parametros busqueda avanzada
     /*
      *
      */
     $str_q = $q;
     $str_filtro = $filtro ? 'more:' . $filtro : '';
     $str_as_q = $as_q;
     $str_as_epq = $as_epq ? '"' . $as_epq . '"' : '';
     //al menos una palabra OR
     $aTmp_as_oq = explode(' ', $as_oq);
     $nro_palabras = count($aTmp_as_oq);
     $retorna_as_oq = '';
     $cnt = 1;
     foreach ($aTmp_as_oq as $as_oq) {
         $separador = '';
         if ($cnt < $nro_palabras) {
             $separador = ' OR ';
         }
         $retorna_as_oq .= $as_oq . $separador;
         $cnt++;
     }
     $str_as_oq = !empty($retorna_as_oq) ? $retorna_as_oq : '';
     //fin-OR
     //sin la palabra
     if (!empty($as_eq)) {
         $aTmp_as_eq = explode(' ', $as_eq);
         $nro_palabras = count($aTmp_as_eq);
         $retorna_as_eq = '';
         $cnt = 1;
         foreach ($aTmp_as_eq as $as_eq) {
             $separador = '';
             if ($cnt < $nro_palabras) {
                 $separador = ' ';
             }
             $retorna_as_eq .= '-' . $as_eq . $separador;
             $cnt++;
         }
     }
     $str_as_eq = !empty($retorna_as_eq) ? $retorna_as_eq : '';
     //fin sin la palabra
     //incluye excluye tipo archivo
     $query_ft = $as_ft == 'e' ? '-' : '';
     //(i) include & (e) exclude
     $str_as_filetype = !empty($as_filetype) ? $query_ft . 'filetype:' . $as_filetype : '';
     //archivo
     //fin incluye excluye tipo archivo
     //fecha busqueda
     $str_as_qdr = !empty($as_qdr) ? '&as_qdr=' . $as_qdr : '';
     //
     //fin fecha busqueda
     //en sitio
     $query_as_dt = '&as_dt=' . $as_dt;
     $str_as_sitesearch = !empty($as_sitesearch) ? '&as_sitesearch=' . $as_sitesearch . $query_as_dt : '';
     //fin en sitio
     //criterios
     $str_as_occt = $as_occt ? $as_occt . ':' : '';
     //fin criterios
     $query_final_buscador = ($str_as_occt ? $str_as_occt . ' ' : '') . ($str_q ? $str_q . ' ' : '') . ($str_as_q ? $str_as_q . ' ' : '') . ($str_as_epq ? $str_as_epq . ' ' : '') . ($str_as_oq ? $str_as_oq . ' ' : '') . ($str_as_eq ? $str_as_eq . ' ' : '') . ($str_as_filetype ? $str_as_filetype . ' ' : '') . ($str_as_sitesearch ? $str_as_sitesearch . ' ' : '') . ($str_filtro ? $str_filtro . ' ' : '');
     //echo '<br />http://www.google.com/cse?cx=009673987297622511854%3Adcpcxycquak&client=google-csbe&output=xml_no_dtd&cr=countryCL&num=10&q=' . $str_as_occt . $str_q . $str_filtro . $str_as_q . $str_as_epq . $str_as_oq . $str_as_eq . $str_as_filetype . $str_as_qdr . $str_as_sitesearch;
     /*
      *
      */
     $query_as_q = !empty($as_q) ? '&as_q=' . str_replace(' ', '+', $as_q) . (!empty($as_q) ? '+' : '') : '';
     $query_as_q = substr($query_as_q, -1) == '+' ? substr($query_as_q, 0, -1) : $query_as_q;
     $query_as_epq = ($as_epq ? '%22' . str_replace(' ', '+', $as_epq) . '%22' : '') . ($as_epq ? '+' : '');
     //frase exacta
     //al menos una palabra OR
     $aTmp_as_oq = explode(' ', $as_oq);
     $nro_palabras = count($aTmp_as_oq);
     $retorna_as_oq = '';
     $cnt = 1;
     foreach ($aTmp_as_oq as $as_oq) {
         $separador = '';
         if ($cnt < $nro_palabras) {
             $separador = '+OR+';
         }
         $retorna_as_oq .= $as_oq . $separador;
         $cnt++;
     }
     $plus = !empty($query_as_q) ? '+' : '';
     $query_as_oq = !empty($retorna_as_oq) ? $plus . $retorna_as_oq : '';
     //fin-OR
     //sin la palabra
     if (!empty($as_eq)) {
         $aTmp_as_eq = explode(' ', $as_eq);
         $nro_palabras = count($aTmp_as_eq);
         $retorna_as_eq = '';
         $cnt = 1;
         foreach ($aTmp_as_eq as $as_eq) {
             $separador = '';
             $pre = '';
             if ($cnt == 1) {
                 $pre = '+';
             }
             if ($cnt < $nro_palabras) {
                 $separador = '+';
             }
             $retorna_as_eq .= $pre . '%2D' . $as_eq . $separador;
             $cnt++;
         }
     }
     $query_as_eq = !empty($retorna_as_eq) ? $retorna_as_eq . '+' : '';
     //fin sin la palabra
     //incluye excluye tipo archivo
     $plus = empty($query_as_eq) ? '+' : '';
     $query_ft = $as_ft == 'e' ? '%2D' : '';
     //(i) include & (e) exclude
     $query_as_filetype = !empty($as_filetype) ? $plus . $query_ft . 'filetype%3A' . $as_filetype . '&as_ft=' . $as_ft : '';
     //archivo
     //fin incluye excluye tipo archivo
     //fecha busqueda
     $query_as_qdr = !empty($as_qdr) ? '&as_qdr=' . $as_qdr : '';
     //
     //fin fecha busqueda
     //en sitio
     $query_as_dt = '&as_dt=' . $as_dt;
     $query_as_sitesearch = !empty($as_sitesearch) ? '&as_sitesearch=' . $as_sitesearch . $query_as_dt : '';
     //fin en sitio
     //criterios
     $query_as_occt = $as_occt ? $as_occt . '%3A' : '';
     //fin criterios
     //fin busqueda avanzada
     $query = str_replace(' ', '+', $q);
     if ($filtro) {
         $filtro = '+more:' . $filtro;
     } else {
         $filtro = '';
     }
     //el debugger mula
     if (0) {
         echo 'query_as_q: ' . $query_as_q . '<br />';
         echo 'query_as_epq: ' . $query_as_epq . '<br />';
         echo 'query_as_oq: ' . $query_as_oq . '<br />';
         echo 'query_as_eq: ' . $query_as_eq . '<br />';
         echo 'query_as_filetype: ' . $query_as_filetype . '<br />';
         echo 'query_as_qdr: ' . $query_as_qdr . '<br />';
         echo 'query_as_dt: ' . $query_as_dt . '<br />';
         echo 'query_as_sitesearch: ' . $query_as_sitesearch . '<br />';
         echo 'query_as_occt: ' . $query_as_occt . '<br />';
         echo '<br />http://www.google.com/cse?cx=009673987297622511854%3Adcpcxycquak&client=google-csbe&output=xml_no_dtd&cr=countryCL&num=10&q=' . $query . $query_as_q . $query_as_epq . $query_as_oq . $query_as_eq . $query_as_filetype . $query_as_qdr . $query_as_sitesearch . $filtro . $start;
         exit;
     }
     // create a new cURL resource
     $datosxml = curl_init();
     // set URL and other appropriate options
     //curl_setopt($datosxml, CURLOPT_URL, "http://www.google.com/cse?cx=009673987297622511854%3Adcpcxycquak&client=google-csbe&output=xml_no_dtd&cr=countryCL&num=10&q=" . $query . $query_as_q . $query_as_epq . $query_as_oq . $query_as_eq . $query_as_filetype . $query_as_qdr . $query_as_sitesearch . $filtro . $start);
     curl_setopt($datosxml, CURLOPT_URL, "http://www.google.com/cse?cx=009673987297622511854%3Adcpcxycquak&client=google-csbe&output=xml_no_dtd&cr=countryCL&num=10&q=" . $query . $query_as_q . $query_as_epq . $query_as_oq . $query_as_eq . $query_as_filetype . $query_as_qdr . $query_as_sitesearch . $filtro . $start);
     //curl_setopt($datosxml, CURLOPT_HEADER, 0);
     curl_setopt($datosxml, CURLOPT_RETURNTRANSFER, true);
     // grab URL and pass it to the browser
     $xml = curl_exec($datosxml);
     // close cURL resource, and free up system resources
     curl_close($datosxml);
     //definimos elchorizo, que es la url completa
     $elchorizo = $query . $query_as_q . $query_as_epq . $query_as_oq . $query_as_eq . $query_as_filetype . $query_as_qdr . $query_as_sitesearch . $filtro;
     $id = '';
     $url = '';
     $titulo = '';
     $bajada = '';
     $articulos = '';
     $data = array();
     $paginador = '';
     $doc = phpQuery::newDocumentXML($xml, $charset = 'utf-8');
     $sugerencia = pq('Spelling')->find('Suggestion')->text();
     $nroResultado = pq('M')->text();
     foreach (pq('R') as $articulo) {
         $destacado = 0;
         $id = pq($articulo)->attr('N');
         $url = pq($articulo)->children('U')->text();
         $titulo = pq($articulo)->children('T')->text();
         $bajada = pq($articulo)->find('S')->text();
         foreach (pq($articulo)->find('SL_MAIN') as $artDestacado) {
             $destacado = 1;
             $tmpdestacado = 1;
             foreach (pq($artDestacado)->find('BLOCK') as $artDestacadoInterior) {
                 $bajada = pq($artDestacadoInterior)->children('T')->text();
             }
         }
         if ($destacado) {
             $data['destacados'][$id] = '
                 <div class="box-art-dest" id="link_' . $id . '">
                     <h3><a href="' . $url . '">' . $titulo . '</a></h3>
                     <p>' . $bajada . '</p>
                     <a href="' . $url . '">' . $url . '</a>
                 </div>
                 ';
         } else {
             $data['articulos'][$id] = '
                 <div class="box-art" id="link_' . $id . '">
                     <h3><a href="' . $url . '">' . $titulo . '</a></h3>
                     <p>' . $bajada . '</p>
                     <a href="' . $url . '">' . $url . '</a>
                 </div>
                 ';
         }
     }
     //obtengo la url que entrega el xml para la pagina anterior(PU) y siguiente(NU)
     //y lo convierto a un arreglo, de esta forma es mas facil. Como se que el penultimo
     //valor del arreglo es el que me da el numero de la pagina, le resto 2 al total del arreglo
     if (pq('NU')->text()) {
         $parametros = explode('&', pq('NU')->text());
         $nroParametros = count(explode('&', pq('NU')->text()));
         $parametro = explode('=', $parametros[$nroParametros - 2]);
         $pagSiguiente = '&start=' . $parametro[1];
     }
     if (pq('PU')->text()) {
         $parametros = explode('&', pq('PU')->text());
         $nroParametros = count(explode('&', pq('PU')->text()));
         $parametro = explode('=', $parametros[$nroParametros - 2]);
         $pagAnterior = '&start=' . $parametro[1];
     }
     $paginador = '';
     if (!empty($pagAnterior)) {
         $paginador = '<div><a href="consulta?q=' . $elchorizo . $pagAnterior . '">Anterior</a></div>';
     }
     if (!empty($pagSiguiente)) {
         $paginador .= '<div><a href="consulta?q=' . $elchorizo . $pagSiguiente . '">Siguiente</a></div>';
     }
     $data['title'] = 'Buscador ChileAtiende - Resultado para: ' . $q;
     $data['sugerencia'] = $sugerencia;
     $data['paginador'] = $paginador;
     $data['nroresultado'] = $nroResultado;
     //if (!empty($q))
     $vista = 'resultado';
     //else
     //    $vista = 'avanzado';
     $data['content'] = $vista;
     $data['q'] = $query_final_buscador;
     $this->load->view('template', $data);
 }