Exemple #1
0
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     $item->body = FinderIndexerHelper::prepareContent($item->getElement('body'));
     $item->summary = FinderIndexerHelper::prepareContent($item->getElement('body'));
     $item->addTaxonomy('Type', 'FSF_FINDER_GLOSSARY');
     $word = $item->title;
     $anchor = strtolower(preg_replace("/[^A-Za-z0-9]/", '-', $word));
     $letter = strtolower(substr($word, 0, 1));
     $item->url = 'index.php?option=com_fsf&view=glossary&letter=' . $letter . '#' . $anchor;
     $item->route = $item->url;
     $item->state = $item->published;
     $item->access = 1;
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     if (FSFJ3Helper::IsJ3()) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
Exemple #2
0
 /**
  * Override method to index a certain result
  *
  * @param   FinderIndexerResult  $item    Finder item
  * @param   string               $format  Formatting (html or text)
  *
  * @return  null
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     /*
     if (JComponentHelper::isEnabled($this->extension) == false)
     {
         return;
     }
     */
     // Prepare the item
     $item->access = 1;
     // Define these items as songs
     $item->addTaxonomy('Type', 'Song');
     // Add artist information
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'artist');
     $item->addTaxonomy('Artist', $item->artist);
     // Set language
     //$item->setLanguage();
     //$item->addTaxonomy('Language', $item->language);
     // Set URLs
     $item->route = 'index.php?option=com_music&view=song&id=' . $item->id;
     $item->url = $item->route;
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Allow others to hook into our $item as well
     FinderIndexerHelper::getContentExtras($item);
     $this->indexer->index($item);
 }
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param	object		The item to index as an FinderIndexerResult object.
  * @throws	Exception on database error.
  */
 protected function _index(FinderIndexerResult $item)
 {
     // Build the necessary route and path information.
     $item->url = $this->_getURL($item->topic);
     $item->itemid = '100065';
     $item->route = $item->url . '&post=' . $item->id . '&Itemid=' . $item->itemid . '#p' . $item->id;
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'display_name');
     // Strip slashes!
     $item->title = stripslashes($item->title);
     $item->summary = stripslashes($item->summary);
     $item->display_name = stripslashes($item->display_name);
     $item->text = FinderIndexerHelper::prepareContent($item->summary);
     // Translate the access group to an access level.
     //$item->cat_access = $this->_getAccessLevel($item->cat_access);
     // Inherit state and access form the category.
     $item->state = 1;
     $item->access = 0;
     // Set the language.
     $item->language = FinderIndexerHelper::getDefaultLanguage();
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Forum Post');
     // Add the author taxonomy data.
     if (!empty($item->author)) {
         $item->addTaxonomy('Forum User', $item->display_name);
     }
     // Index the item.
     FinderIndexer::index($item);
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @return  void
  *
  * @since   3.1
  */
 protected function setUp()
 {
     parent::setUp();
     // Store the factory state so we can mock the necessary objects
     $this->saveFactoryState();
     // Set up our mock database
     JFactory::$database = $this->getMockDatabase('Mysqli');
     FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance('porter_en');
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  *
  * @return  void
  *
  * @since   3.1
  */
 protected function setUp()
 {
     // Store the factory state so we can mock the necessary objects
     $this->saveFactoryState();
     // Set up our mock database
     $db = JFactory::getDbo();
     $db->name = 'mysqli';
     JFactory::$database = $db;
     FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance('porter_en');
 }
Exemple #6
0
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     $item->body = FinderIndexerHelper::prepareContent($item->getElement('body'));
     $item->summary = FinderIndexerHelper::prepareContent($item->getElement('body'));
     $item->addTaxonomy('Type', 'FSS_FINDER_KB_ARTICLE');
     $item->url = 'index.php?option=com_fss&view=kb&kbartid=' . $item->getElement('id');
     $item->route = $item->url;
     $item->state = $item->getElement('pub');
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     if (FSSJ3Helper::IsJ3()) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false || !$item->id) {
         return;
     }
     if (!($zoo_item = $this->app->table->item->get($item->id, true))) {
         return;
     }
     $registry = new JRegistry();
     $registry->loadArray($zoo_item->getParams()->get("metadata."));
     $item->metadata = $registry;
     $item->metaauthor = $zoo_item->getParams()->get("metadata.author");
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'link');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_alias');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'element_data');
     $item->summary = $this->renderer->render('item.default', array('item' => $zoo_item));
     $item->url = $this->getURL($item->id, $this->extension, $this->layout);
     $item->route = $this->app->route->item($zoo_item, false);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     $item->state = $zoo_item->searchable == 1 && $zoo_item->state == 1;
     $item->element_data = $this->app->database->queryResultArray('SELECT value FROM ' . ZOO_TABLE_SEARCH . ' WHERE item_id = ' . (int) $item->id);
     $item->addTaxonomy('Type', $zoo_item->getType()->name);
     foreach ($zoo_item->getRelatedCategories(true) as $category) {
         $item->addTaxonomy('Category', $category->name);
     }
     foreach ($zoo_item->getTags() as $tag) {
         $item->addTaxonomy('Tag', $tag);
     }
     FinderIndexerHelper::getContentExtras($item);
     if ($this->app->joomla->version->isCompatible('3.0')) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
 /**
  * Tests the getPrimaryLanguage method
  *
  * @return  void
  *
  * @since   3.0
  */
 public function testGetPrimaryLanguage()
 {
     $this->assertThat(FinderIndexerHelper::getPrimaryLanguage('en-GB'), $this->StringContains('en'), 'The primary language is en');
 }
Exemple #9
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format.  Not used.
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     $item->setLanguage();
     // Check if the extension is enabled.
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Initialise the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = JComponentHelper::getParams('com_content', true);
     $item->params->merge($registry);
     $registry = new JRegistry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     // Trigger the onContentPrepare event.
     $item->summary = FinderIndexerHelper::prepareContent($item->summary, $item->params);
     $item->body = FinderIndexerHelper::prepareContent($item->body, $item->params);
     // Build the necessary route and path information.
     $item->url = $this->getURL($item->id, $this->extension, $this->layout);
     $item->route = ContentHelperRoute::getArticleRoute($item->slug, $item->catslug, $item->language);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Get the menu title if it exists.
     $title = $this->getItemMenuTitle($item->url);
     // Adjust the title if necessary.
     if (!empty($title) && $this->params->get('use_menu_title', true)) {
         $item->title = $title;
     }
     // Add the meta-author.
     $item->metaauthor = $item->metadata->get('author');
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_alias');
     // Translate the state. Articles should only be published if the category is published.
     $item->state = $this->translateState($item->state, $item->cat_state);
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Article');
     // Add the author taxonomy data.
     if (!empty($item->author) || !empty($item->created_by_alias)) {
         $item->addTaxonomy('Author', !empty($item->created_by_alias) ? $item->created_by_alias : $item->author);
     }
     // Add the category taxonomy data.
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     $this->indexer->index($item);
 }
Exemple #10
0
 /**
  * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
  *
  * @param   string  $ordering   An optional ordering field. [optional]
  * @param   string  $direction  An optional direction. [optional]
  *
  * @return  void
  *
  * @since   2.5
  */
 protected function populateState($ordering = null, $direction = null)
 {
     // Get the configuration options.
     $app = JFactory::getApplication();
     $input = $app->input;
     $params = $app->getParams();
     $user = JFactory::getUser();
     $filter = JFilterInput::getInstance();
     $this->setState('filter.language', JLanguageMultilang::isEnabled());
     // Setup the stemmer.
     if ($params->get('stem', 1) && $params->get('stemmer', 'porter_en')) {
         FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance($params->get('stemmer', 'porter_en'));
     }
     $request = $input->request;
     $options = array();
     // Get the empty query setting.
     $options['empty'] = $params->get('allow_empty_query', 0);
     // Get the static taxonomy filters.
     $options['filter'] = $request->getInt('f', $params->get('f', ''));
     // Get the dynamic taxonomy filters.
     $options['filters'] = $request->get('t', $params->get('t', array()), '', 'array');
     // Get the query string.
     $options['input'] = $request->getString('q', $params->get('q', ''));
     // Get the query language.
     $options['language'] = $request->getCmd('l', $params->get('l', ''));
     // Get the start date and start date modifier filters.
     $options['date1'] = $request->getString('d1', $params->get('d1', ''));
     $options['when1'] = $request->getString('w1', $params->get('w1', ''));
     // Get the end date and end date modifier filters.
     $options['date2'] = $request->getString('d2', $params->get('d2', ''));
     $options['when2'] = $request->getString('w2', $params->get('w2', ''));
     // Load the query object.
     $this->query = new FinderIndexerQuery($options);
     // Load the query token data.
     $this->excludedTerms = $this->query->getExcludedTermIds();
     $this->includedTerms = $this->query->getIncludedTermIds();
     $this->requiredTerms = $this->query->getRequiredTermIds();
     // Load the list state.
     $this->setState('list.start', $input->get('limitstart', 0, 'uint'));
     $this->setState('list.limit', $input->get('limit', $app->get('list_limit', 20), 'uint'));
     /* Load the sort ordering.
      * Currently this is 'hard' coded via menu item parameter but may not satisfy a users need.
      * More flexibility was way more user friendly. So we allow the user to pass a custom value
      * from the pool of fields that are indexed like the 'title' field.
      * Also, we allow this parameter to be passed in either case (lower/upper).
      */
     $order = $input->getWord('filter_order', $params->get('sort_order', 'relevance'));
     $order = JString::strtolower($order);
     switch ($order) {
         case 'date':
             $this->setState('list.ordering', 'l.start_date');
             break;
         case 'price':
             $this->setState('list.ordering', 'l.list_price');
             break;
         case $order == 'relevance' && !empty($this->includedTerms):
             $this->setState('list.ordering', 'm.weight');
             break;
             // custom field that is indexed and might be required for ordering
         // custom field that is indexed and might be required for ordering
         case 'title':
             $this->setState('list.ordering', 'l.title');
             break;
         default:
             $this->setState('list.ordering', 'l.link_id');
             break;
     }
     /* Load the sort direction.
      * Currently this is 'hard' coded via menu item parameter but may not satisfy a users need.
      * More flexibility was way more user friendly. So we allow to be inverted.
      * Also, we allow this parameter to be passed in either case (lower/upper).
      */
     $dirn = $input->getWord('filter_order_Dir', $params->get('sort_direction', 'desc'));
     $dirn = JString::strtolower($dirn);
     switch ($dirn) {
         case 'asc':
             $this->setState('list.direction', 'ASC');
             break;
         default:
         case 'desc':
             $this->setState('list.direction', 'DESC');
             break;
     }
     // Set the match limit.
     $this->setState('match.limit', 1000);
     // Load the parameters.
     $this->setState('params', $params);
     // Load the user state.
     $this->setState('user.id', (int) $user->get('id'));
     $this->setState('user.groups', $user->getAuthorisedViewLevels());
 }
Exemple #11
0
 /**
  * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
  *
  * @param   string  $ordering   An optional ordering field.
  * @param   string  $direction  An optional direction (asc|desc).
  *
  * @return  void
  *
  * @since   2.5
  */
 protected function populateState($ordering = null, $direction = null)
 {
     // Get the configuration options.
     $app = JFactory::getApplication();
     $input = $app->input;
     $params = JComponentHelper::getParams('com_finder');
     $user = JFactory::getUser();
     // Get the query input.
     $this->setState('input', $input->request->get('q', '', 'string'));
     // Set the query language
     if (JLanguageMultilang::isEnabled()) {
         $lang = JFactory::getLanguage()->getTag();
     } else {
         $lang = FinderIndexerHelper::getDefaultLanguage();
     }
     $lang = FinderIndexerHelper::getPrimaryLanguage($lang);
     $this->setState('language', $lang);
     // Load the list state.
     $this->setState('list.start', 0);
     $this->setState('list.limit', 10);
     // Load the parameters.
     $this->setState('params', $params);
     // Load the user state.
     $this->setState('user.id', (int) $user->get('id'));
 }
Exemple #12
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Initialize the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = $registry;
     $registry = new JRegistry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     // Build the necessary route and path information.
     $item->url = $this->getURL($item->id, $this->extension, $this->layout);
     $item->route = WeblinksHelperRoute::getWeblinkRoute($item->slug, $item->catslug);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     /*
      * Add the meta-data processing instructions based on the newsfeeds
      * configuration parameters.
      */
     // Add the meta-author.
     $item->metaauthor = $item->metadata->get('author');
     // Handle the link to the meta-data.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'link');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_alias');
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Web Link');
     // Add the category taxonomy data.
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     FinderIndexer::index($item);
 }
Exemple #13
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Initialize the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = JComponentHelper::getParams('com_jshopping', true);
     $item->params->merge($registry);
     // Trigger the onContentPrepare event.
     $item->summary = FinderIndexerHelper::prepareContent($item->summary, $item->params);
     $item->body = FinderIndexerHelper::prepareContent($item->body, $item->params);
     // Build the necessary route and path information.
     $item->url = 'index.php?option=com_jshopping&controller=product&task=view&category_id=' . $item->category_id . '&product_id=' . $item->product_id;
     $item->route = 'index.php?option=com_jshopping&controller=product&task=view&category_id=' . $item->category_id . '&product_id=' . $item->product_id;
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Get the menu title if it exists.
     $title = $this->getItemMenuTitle($item->url);
     // Adjust the title if necessary.
     if (!empty($title) && $this->params->get('use_menu_title', true)) {
         $item->title = $title;
     }
     // Add the meta-author.
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'link');
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Product');
     // Add the category taxonomy data.
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     if (version_compare(JVERSION, '3.0.0', 'ge')) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
Exemple #14
0
 /**
  * Method to setup the indexer to be run.
  *
  * @return  boolean  True on success.
  *
  * @since   2.5
  */
 protected function setup()
 {
     // Load dependent classes.
     require_once JPATH_SITE . '/components/com_contact/helpers/route.php';
     // This is a hack to get around the lack of a route helper.
     FinderIndexerHelper::getContentPath('index.php?option=com_contact');
     return true;
 }
Exemple #15
0
 /**
  * Method to process the query input string and extract required, optional,
  * and excluded tokens; taxonomy filters; and date filters.
  *
  * @param   string  $input  The query input string.
  * @param   string  $lang   The query input language.
  * @param   string  $mode   The query matching mode.
  *
  * @return  boolean  True on success.
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function processString($input, $lang, $mode)
 {
     // Clean up the input string.
     $input = html_entity_decode($input, ENT_QUOTES, 'UTF-8');
     $input = JString::strtolower($input);
     $input = preg_replace('#\\s+#mi', ' ', $input);
     $input = JString::trim($input);
     $debug = JFactory::getConfig()->get('debug_lang');
     /*
      * First, we need to handle string based modifiers. String based
      * modifiers could potentially include things like "category:blah" or
      * "before:2009-10-21" or "type:article", etc.
      */
     $patterns = array('before' => JText::_('COM_FINDER_FILTER_WHEN_BEFORE'), 'after' => JText::_('COM_FINDER_FILTER_WHEN_AFTER'));
     // Add the taxonomy branch titles to the possible patterns.
     foreach (FinderIndexerTaxonomy::getBranchTitles() as $branch) {
         // Add the pattern.
         $patterns[$branch] = JString::strtolower(JText::_(FinderHelperLanguage::branchSingular($branch)));
     }
     // Container for search terms and phrases.
     $terms = array();
     $phrases = array();
     // Cleared filter branches.
     $cleared = array();
     /*
      * Compile the suffix pattern. This is used to match the values of the
      * filter input string. Single words can be input directly, multi-word
      * values have to be wrapped in double quotes.
      */
     $quotes = html_entity_decode('‘’'', ENT_QUOTES, 'UTF-8');
     $suffix = '(([\\w\\d' . $quotes . '-]+)|\\"([\\w\\d\\s' . $quotes . '-]+)\\")';
     /*
      * Iterate through the possible filter patterns and search for matches.
      * We need to match the key, colon, and a value pattern for the match
      * to be valid.
      */
     foreach ($patterns as $modifier => $pattern) {
         $matches = array();
         if ($debug) {
             $pattern = substr($pattern, 2, -2);
         }
         // Check if the filter pattern is in the input string.
         if (preg_match('#' . $pattern . '\\s*:\\s*' . $suffix . '#mi', $input, $matches)) {
             // Get the value given to the modifier.
             $value = isset($matches[3]) ? $matches[3] : $matches[1];
             // Now we have to handle the filter string.
             switch ($modifier) {
                 // Handle a before and after date filters.
                 case 'before':
                 case 'after':
                     // Get the time offset.
                     $offset = JFactory::getApplication()->get('offset');
                     // Array of allowed when values.
                     $whens = array('before', 'after', 'exact');
                     // The value of 'today' is a special case that we need to handle.
                     if ($value === JString::strtolower(JText::_('COM_FINDER_QUERY_FILTER_TODAY'))) {
                         $today = JFactory::getDate('now', $offset);
                         $value = $today->format('%Y-%m-%d');
                     }
                     // Try to parse the date string.
                     $date = JFactory::getDate($value, $offset);
                     // Check if the date was parsed successfully.
                     if ($date->toUnix() !== null) {
                         // Set the date filter.
                         $this->date1 = $date->toSQL();
                         $this->when1 = in_array($modifier, $whens) ? $modifier : 'before';
                     }
                     break;
                     // Handle a taxonomy branch filter.
                 // Handle a taxonomy branch filter.
                 default:
                     // Try to find the node id.
                     $return = FinderIndexerTaxonomy::getNodeByTitle($modifier, $value);
                     // Check if the node id was found.
                     if ($return) {
                         // Check if the branch has been cleared.
                         if (!in_array($modifier, $cleared)) {
                             // Clear the branch.
                             $this->filters[$modifier] = array();
                             // Add the branch to the cleared list.
                             $cleared[] = $modifier;
                         }
                         // Add the filter to the list.
                         $this->filters[$modifier][$return->title] = (int) $return->id;
                     }
                     break;
             }
             // Clean up the input string again.
             $input = str_replace($matches[0], '', $input);
             $input = preg_replace('#\\s+#mi', ' ', $input);
             $input = JString::trim($input);
         }
     }
     /*
      * Extract the tokens enclosed in double quotes so that we can handle
      * them as phrases.
      */
     if (JString::strpos($input, '"') !== false) {
         $matches = array();
         // Extract the tokens enclosed in double quotes.
         if (preg_match_all('#\\"([^"]+)\\"#mi', $input, $matches)) {
             /*
              * One or more phrases were found so we need to iterate through
              * them, tokenize them as phrases, and remove them from the raw
              * input string before we move on to the next processing step.
              */
             foreach ($matches[1] as $key => $match) {
                 // Find the complete phrase in the input string.
                 $pos = JString::strpos($input, $matches[0][$key]);
                 $len = JString::strlen($matches[0][$key]);
                 // Add any terms that are before this phrase to the stack.
                 if (JString::trim(JString::substr($input, 0, $pos))) {
                     $terms = array_merge($terms, explode(' ', JString::trim(JString::substr($input, 0, $pos))));
                 }
                 // Strip out everything up to and including the phrase.
                 $input = JString::substr($input, $pos + $len);
                 // Clean up the input string again.
                 $input = preg_replace('#\\s+#mi', ' ', $input);
                 $input = JString::trim($input);
                 // Get the number of words in the phrase.
                 $parts = explode(' ', $match);
                 // Check if the phrase is longer than three words.
                 if (count($parts) > 3) {
                     /*
                      * If the phrase is longer than three words, we need to
                      * break it down into smaller chunks of phrases that
                      * are less than or equal to three words. We overlap
                      * the chunks so that we can ensure that a match is
                      * found for the complete phrase and not just portions
                      * of it.
                      */
                     for ($i = 0, $c = count($parts); $i < $c; $i += 2) {
                         // Set up the chunk.
                         $chunk = array();
                         // The chunk has to be assembled based on how many
                         // pieces are available to use.
                         switch ($c - $i) {
                             /*
                              * If only one word is left, we can break from
                              * the switch and loop because the last word
                              * was already used at the end of the last
                              * chunk.
                              */
                             case 1:
                                 break 2;
                                 // If there words are left, we use them both as
                                 // the last chunk of the phrase and we're done.
                             // If there words are left, we use them both as
                             // the last chunk of the phrase and we're done.
                             case 2:
                                 $chunk[] = $parts[$i];
                                 $chunk[] = $parts[$i + 1];
                                 break;
                                 // If there are three or more words left, we
                                 // build a three word chunk and continue on.
                             // If there are three or more words left, we
                             // build a three word chunk and continue on.
                             default:
                                 $chunk[] = $parts[$i];
                                 $chunk[] = $parts[$i + 1];
                                 $chunk[] = $parts[$i + 2];
                                 break;
                         }
                         // If the chunk is not empty, add it as a phrase.
                         if (count($chunk)) {
                             $phrases[] = implode(' ', $chunk);
                             $terms[] = implode(' ', $chunk);
                         }
                     }
                 } else {
                     // The phrase is <= 3 words so we can use it as is.
                     $phrases[] = $match;
                     $terms[] = $match;
                 }
             }
         }
     }
     // Add the remaining terms if present.
     if (!empty($input)) {
         $terms = array_merge($terms, explode(' ', $input));
     }
     // An array of our boolean operators. $operator => $translation
     $operators = array('AND' => JString::strtolower(JText::_('COM_FINDER_QUERY_OPERATOR_AND')), 'OR' => JString::strtolower(JText::_('COM_FINDER_QUERY_OPERATOR_OR')), 'NOT' => JString::strtolower(JText::_('COM_FINDER_QUERY_OPERATOR_NOT')));
     // If language debugging is enabled you need to ignore the debug strings in matching.
     if (JDEBUG) {
         $debugStrings = array('**', '??');
         $operators = str_replace($debugStrings, '', $operators);
     }
     /*
      * Iterate through the terms and perform any sorting that needs to be
      * done based on boolean search operators. Terms that are before an
      * and/or/not modifier have to be handled in relation to their operator.
      */
     for ($i = 0, $c = count($terms); $i < $c; $i++) {
         // Check if the term is followed by an operator that we understand.
         if (isset($terms[$i + 1]) && in_array($terms[$i + 1], $operators)) {
             // Get the operator mode.
             $op = array_search($terms[$i + 1], $operators);
             // Handle the AND operator.
             if ($op === 'AND' && isset($terms[$i + 2])) {
                 // Tokenize the current term.
                 $token = FinderIndexerHelper::tokenize($terms[$i], $lang, true);
                 $token = $this->getTokenData($token);
                 // Set the required flag.
                 $token->required = true;
                 // Add the current token to the stack.
                 $this->included[] = $token;
                 $this->highlight = array_merge($this->highlight, array_keys($token->matches));
                 // Skip the next token (the mode operator).
                 $this->operators[] = $terms[$i + 1];
                 // Tokenize the term after the next term (current plus two).
                 $other = FinderIndexerHelper::tokenize($terms[$i + 2], $lang, true);
                 $other = $this->getTokenData($other);
                 // Set the required flag.
                 $other->required = true;
                 // Add the token after the next token to the stack.
                 $this->included[] = $other;
                 $this->highlight = array_merge($this->highlight, array_keys($other->matches));
                 // Remove the processed phrases if possible.
                 if (($pk = array_search($terms[$i], $phrases)) !== false) {
                     unset($phrases[$pk]);
                 }
                 if (($pk = array_search($terms[$i + 2], $phrases)) !== false) {
                     unset($phrases[$pk]);
                 }
                 // Remove the processed terms.
                 unset($terms[$i]);
                 unset($terms[$i + 1]);
                 unset($terms[$i + 2]);
                 // Adjust the loop.
                 $i += 2;
                 continue;
             } elseif ($op === 'OR' && isset($terms[$i + 2])) {
                 // Tokenize the current term.
                 $token = FinderIndexerHelper::tokenize($terms[$i], $lang, true);
                 $token = $this->getTokenData($token);
                 // Set the required flag.
                 $token->required = false;
                 // Add the current token to the stack.
                 if (count($token->matches)) {
                     $this->included[] = $token;
                     $this->highlight = array_merge($this->highlight, array_keys($token->matches));
                 } else {
                     $this->ignored[] = $token;
                 }
                 // Skip the next token (the mode operator).
                 $this->operators[] = $terms[$i + 1];
                 // Tokenize the term after the next term (current plus two).
                 $other = FinderIndexerHelper::tokenize($terms[$i + 2], $lang, true);
                 $other = $this->getTokenData($other);
                 // Set the required flag.
                 $other->required = false;
                 // Add the token after the next token to the stack.
                 if (count($other->matches)) {
                     $this->included[] = $other;
                     $this->highlight = array_merge($this->highlight, array_keys($other->matches));
                 } else {
                     $this->ignored[] = $other;
                 }
                 // Remove the processed phrases if possible.
                 if (($pk = array_search($terms[$i], $phrases)) !== false) {
                     unset($phrases[$pk]);
                 }
                 if (($pk = array_search($terms[$i + 2], $phrases)) !== false) {
                     unset($phrases[$pk]);
                 }
                 // Remove the processed terms.
                 unset($terms[$i]);
                 unset($terms[$i + 1]);
                 unset($terms[$i + 2]);
                 // Adjust the loop.
                 $i += 2;
                 continue;
             }
         } elseif (isset($terms[$i + 1]) && array_search($terms[$i], $operators) === 'OR') {
             // Skip the next token (the mode operator).
             $this->operators[] = $terms[$i];
             // Tokenize the next term (current plus one).
             $other = FinderIndexerHelper::tokenize($terms[$i + 1], $lang, true);
             $other = $this->getTokenData($other);
             // Set the required flag.
             $other->required = false;
             // Add the token after the next token to the stack.
             if (count($other->matches)) {
                 $this->included[] = $other;
                 $this->highlight = array_merge($this->highlight, array_keys($other->matches));
             } else {
                 $this->ignored[] = $other;
             }
             // Remove the processed phrase if possible.
             if (($pk = array_search($terms[$i + 1], $phrases)) !== false) {
                 unset($phrases[$pk]);
             }
             // Remove the processed terms.
             unset($terms[$i]);
             unset($terms[$i + 1]);
             // Adjust the loop.
             $i += 1;
             continue;
         } elseif (isset($terms[$i + 1]) && array_search($terms[$i], $operators) === 'NOT') {
             // Skip the next token (the mode operator).
             $this->operators[] = $terms[$i];
             // Tokenize the next term (current plus one).
             $other = FinderIndexerHelper::tokenize($terms[$i + 1], $lang, true);
             $other = $this->getTokenData($other);
             // Set the required flag.
             $other->required = false;
             // Add the next token to the stack.
             if (count($other->matches)) {
                 $this->excluded[] = $other;
             } else {
                 $this->ignored[] = $other;
             }
             // Remove the processed phrase if possible.
             if (($pk = array_search($terms[$i + 1], $phrases)) !== false) {
                 unset($phrases[$pk]);
             }
             // Remove the processed terms.
             unset($terms[$i]);
             unset($terms[$i + 1]);
             // Adjust the loop.
             $i += 1;
             continue;
         }
     }
     /*
      * Iterate through any search phrases and tokenize them. We handle
      * phrases as autonomous units and do not break them down into two and
      * three word combinations.
      */
     for ($i = 0, $c = count($phrases); $i < $c; $i++) {
         // Tokenize the phrase.
         $token = FinderIndexerHelper::tokenize($phrases[$i], $lang, true);
         $token = $this->getTokenData($token);
         // Set the required flag.
         $token->required = true;
         // Add the current token to the stack.
         $this->included[] = $token;
         $this->highlight = array_merge($this->highlight, array_keys($token->matches));
         // Remove the processed term if possible.
         if (($pk = array_search($phrases[$i], $terms)) !== false) {
             unset($terms[$pk]);
         }
         // Remove the processed phrase.
         unset($phrases[$i]);
     }
     /*
      * Handle any remaining tokens using the standard processing mechanism.
      */
     if (!empty($terms)) {
         // Tokenize the terms.
         $terms = implode(' ', $terms);
         $tokens = FinderIndexerHelper::tokenize($terms, $lang, false);
         // Make sure we are working with an array.
         $tokens = is_array($tokens) ? $tokens : array($tokens);
         // Get the token data and required state for all the tokens.
         foreach ($tokens as $token) {
             // Get the token data.
             $token = $this->getTokenData($token);
             // Set the required flag for the token.
             $token->required = $mode === 'AND' ? $token->phrase ? false : true : false;
             // Add the token to the appropriate stack.
             if (count($token->matches) || $token->required) {
                 $this->included[] = $token;
                 $this->highlight = array_merge($this->highlight, array_keys($token->matches));
             } else {
                 $this->ignored[] = $token;
             }
         }
     }
     return true;
 }
Exemple #16
0
 /**
  * Method to construct the token object.
  *
  * @param   mixed   $term    The term as a string for words or an array for phrases.
  * @param   string  $lang    The simple language identifier.
  * @param   string  $spacer  The space separator for phrases. [optional]
  *
  * @since   2.5
  */
 public function __construct($term, $lang, $spacer = ' ')
 {
     $this->language = $lang;
     // Tokens can be a single word or an array of words representing a phrase.
     if (is_array($term)) {
         // Populate the token instance.
         $this->term = implode($spacer, $term);
         $this->stem = implode($spacer, array_map(array('FinderIndexerHelper', 'stem'), $term, array($lang)));
         $this->numeric = false;
         $this->common = false;
         $this->phrase = true;
         $this->length = JString::strlen($this->term);
         /*
          * Calculate the weight of the token.
          *
          * 1. Length of the token up to 30 and divide by 30, add 1.
          * 2. Round weight to 4 decimal points.
          */
         $this->weight = ($this->length >= 30 ? 30 : $this->length) / 30 + 1;
         $this->weight = round($this->weight, 4);
     } else {
         // Populate the token instance.
         $this->term = $term;
         $this->stem = FinderIndexerHelper::stem($this->term, $lang);
         $this->numeric = is_numeric($this->term) || (bool) preg_match('#^[0-9,.\\-\\+]+$#', $this->term);
         $this->common = $this->numeric ? false : FinderIndexerHelper::isCommon($this->term, $lang);
         $this->phrase = false;
         $this->length = JString::strlen($this->term);
         /*
          * Calculate the weight of the token.
          *
          * 1. Length of the token up to 15 and divide by 15.
          * 2. If common term, divide weight by 8.
          * 3. If numeric, multiply weight by 1.5.
          * 4. Round weight to 4 decimal points.
          */
         $this->weight = ($this->length >= 15 ? 15 : $this->length) / 15;
         $this->weight = $this->common == true ? $this->weight / 8 : $this->weight;
         $this->weight = $this->numeric == true ? $this->weight * 1.5 : $this->weight;
         $this->weight = round($this->weight, 4);
     }
 }
Exemple #17
0
 * @since 1.5
 */
class plgSearchStreams extends JPlugin
{
    /**
	 * Constructor
	 *
	 * For php4 compatability we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @param 	object $subject The object to observe
	 * @param 	array  $config  An array that holds the plugin configuration
	 * @since 1.5
	 */
    public function __construct(&$subject, $config)
    {
        parent::__construct($subject, $config);
        //$this->loadLanguage();
    }
    /**
	 * Display the button
	 *
	 * @return array A two element array of ( imageName, textToInsert )
	 */
    function onContentSearch()
    {
        //global $mainframe;
        $mainframe = JFactory::getApplication();
        $args = func_get_args();
        if (empty($args[0])) {
            return array();
        }
        // array(4) { [0]=> string(10) "she is asd" [1]=> string(5) "exact/all/any" [2]=> string(6) "oldest/newest/alpha/category/popular" [3]=> NULL }
        // Group ID and Filter Range will be from "areas" parameter in com_search form
        if (is_null($args[3])) {
            $areas = 0;
        } else {
            $areas = is_array($args[3]) ? $args[3][0] : $args[3];
        }
        if (preg_match('/_\\d\\w$/', $areas)) {
            $splitVal = explode('_', $areas);
            $groupId = $splitVal[0];
            $filterRange = $splitVal[1];
            // _2w (2 weeks), _1m (1 month), _3m (3 months), _0a (all)
            $rangeCond = $this->_getDateRange($filterRange);
        } else {
            // no filter range info provided;
            $groupId = $areas;
            $filterRange = '0a';
            $rangeCond = $this->_getDateRange($filterRange);
        }
        // search for all/streams/comments/files/people is from "searchphrase" parameter in com_search form
        $searchFor = $args[1];
        // custom class loader
        JLoader::register('FinderIndexerStemmer', FINDER_PATH_INDEXER . '/stemmer.php');
        FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance('porter_en');
        // option porter_en/snowball
        //FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance('snowball'); // option porter_en/snowball
        $option = array("input" => $args[0], "empty" => "0", "language" => "", "filter" => 0, "filters" => array());
        $keyTerm = new FinderIndexerQuery($option);
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        // This part get all groups that the logined user is permitted to see.
        $my = JXFactory::getUser();
        if (!$my->isAdmin()) {
            $query->select('id');
            $query->from('#__groups');
            // group must not be archived and access is public
            $query->where(' ( ' . $db->quoteName('archived') . ' = 0 AND ' . $db->quoteName('access') . ' = 0 ) ', 'OR');
            // OR group is private and user is a member of the private group
            $query->where('( ' . $db->quoteName('access') . ' = 1 AND `members` REGEXP \'^' . $my->id . '[^0-9]|[^0-9]' . $my->id . '[^0-9]|[^0-9]' . $my->id . '$\'' . ' )');
            $db->setQuery($query);
            $allowGroups = $db->loadObjectList();
            for ($i = 0; $i < count($allowGroups); $i++) {
                $allowGroupId[] = $allowGroups[$i]->id;
            }
            $allowGroupId[] = 0;
            $allowGroupCond = ' ( group_id IN (' . implode(',', $allowGroupId) . ') ) ';
        } else {
            $allowGroupCond = '';
        }
        //$limit		= 20;
        $condStream = $condComment = $condFile = $condProfile = array();
        $stream = $comment = $files = $people = $user = $rec = array();
        $streamId = $userId = $keywords = array();
        $condition = '';
        $count = 0;
        foreach ($keyTerm->included as $searchKey) {
            $keywords[] = $searchKey->term;
            // prepare stream condition
            $condStream[$count] = " ( message LIKE " . $db->quote('%' . $searchKey->term . '%');
            // prepare comment condition
            //$condComment[$count]	= " ( comment LIKE ".$db->quote('%'.$searchKey->term.'%');
            // prepare files condition
            $condFile[$count] = " ( filename LIKE " . $db->quote('%' . $searchKey->term . '%');
            // prepare people condition
            $condProfile[$count] = " ( value LIKE " . $db->quote('%' . $searchKey->term . '%');
            $condUser[$count] = " ( name LIKE " . $db->quote('%' . $searchKey->term . '%') . " OR username LIKE " . $db->quote('%' . $searchKey->term . '%');
            if ($searchKey->term != $searchKey->stem) {
                $keywords[] = $searchKey->stem;
                $condStream[$count] .= " OR message LIKE " . $db->quote('%' . $searchKey->stem . '%');
                //$condComment[$count]	.= " OR comment LIKE ".$db->quote('%'.$searchKey->stem.'%');
                $condFile[$count] .= " OR filename LIKE " . $db->quote('%' . $searchKey->stem . '%');
                $condProfile[$count] .= " OR value LIKE " . $db->quote('%' . $searchKey->stem . '%');
                $condUser[$count] .= " OR name LIKE " . $db->quote('%' . $searchKey->stem . '%') . " OR username LIKE " . $db->quote('%' . $searchKey->stem . '%');
            }
            $condStream[$count] .= ' ) ';
            //$condComment[$count]	.= ' ) ';
            $condFile[$count] .= ' ) ';
            $condProfile[$count] .= ' ) ';
            $condUser[$count] .= ' ) ';
            $count++;
        }
        if ($searchFor == 'all' || $searchFor == 'streams') {
            // The following part search for the stream message itself
            $query->clear();
            $query->select('id, id as message_id, type, user_id, message, created');
            $query->from('#__stream');
            if (!empty($condStream)) {
                $query->where('(' . implode(" OR ", $condStream) . ')');
            }
            if ($groupId) {
                $query->where('group_id = ' . $db->quote($groupId));
            } else {
                if (!empty($allowGroupCond)) {
                    $query->where($allowGroupCond, 'OR');
                }
            }
            if (!empty($rangeCond)) {
                $query->where($rangeCond);
            }
            $query->order('created DESC');
            $stream = $this->_arrangeRecords($query, $streamId);
        }
        /*if ($searchFor == 'all' || $searchFor == 'comments')
		{
			// Get all stream messages where comment contains the search key words.
			$query->clear();
			$query->select('id, stream_id as message_id, "comment" as type, user_id, group_id, comment as message, created');
			$query->from('#__stream_comments');
			if (!empty($condComment))
			{
				$query->where('('.implode(" OR ", $condComment).')');
			}
			if ($groupId)
			{
				$query->where('group_id = '.$db->quote($groupId));	
			}
			if (!empty($rangeCond))
			{
				$query->where($rangeCond);
			}
			$query->order('created DESC');
			//echo $query;
			$comment = $this->_arrangeRecords($query, &$streamId);
		}
		*/
        if ($searchFor == 'all' || $searchFor == 'files') {
            // Get all files where filename contains the search key words.
            $query->clear();
            $query->select('id, stream_id as message_id, "files" as type, user_id, group_id, filename as message, created');
            $query->from('#__stream_files');
            if (!empty($condFile)) {
                $query->where('(' . implode(" OR ", $condFile) . ')');
            }
            if ($groupId) {
Exemple #18
0
 /**
  * Indexes a post on the site
  *
  * @since	5.0
  * @access	public
  * @param	FinderIndexerResult		The item to index
  * @param	string	The item's format
  * @return	void
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (!$this->exists()) {
         return;
     }
     // Build the necessary route and path information.
     $item->url = 'index.php?option=com_easyblog&view=entry&id=' . $item->id;
     $item->route = EBR::getRoutedURL($item->url, false, true);
     // Remove any /administrator/ segments from the url since the indexer could be executed from the back end
     $item->route = $this->removeAdminSegment($item->route);
     // Get the content path
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // If there is access defined, just set it to 2 which is special privileges.
     if (!$item->access || $item->access == 0) {
         $item->access = 1;
     } else {
         if ($item->access > 0) {
             $item->access = 2;
         }
     }
     // Load up the post item
     $post = EB::post();
     $post->load($item->id);
     // Get the intro text of the content
     $item->summary = $post->getIntro();
     // Get the contents
     $item->body = $post->getContent('entry', false);
     // If the post is password protected, we do not want to display the contents
     if ($post->isPasswordProtected()) {
         $item->summary = JText::_('PLG_FINDER_EASYBLOG_PASSWORD_PROTECTED');
     } else {
         // we want to get custom fields values.
         $fields = $post->getCustomFields();
         $fieldlib = EB::fields();
         $customfields = array();
         if ($fields) {
             foreach ($fields as $field) {
                 if ($field->group->hasValues($post)) {
                     foreach ($field->fields as $customField) {
                         $eachField = $fieldlib->get($customField->type);
                         $customfields[] = $eachField->text($customField, $post);
                     }
                 }
             }
             $customfieldvalues = implode(' ', $customfields);
             $item->body = $item->body . ' ' . $customfieldvalues;
         }
     }
     // Add the author's meta data
     $item->metaauthor = !empty($item->created_by_alias) ? $item->created_by_alias : $item->author;
     $item->author = !empty($item->created_by_alias) ? $item->created_by_alias : $item->author;
     // If the post has an image, use it
     $image = $post->getImage('thumbnail', false, true);
     // If there's no image, try to scan the contents for an image to be used
     if (!$image && $post->isLegacy()) {
         $image = EB::string()->getImage($item->body);
     }
     // If we still can't locate any images, use the placeholder image
     if (!$image) {
         $image = EB::getPlaceholderImage();
     }
     $registry = new JRegistry();
     $registry->set('image', $image);
     $item->params = $registry;
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'EasyBlog');
     // Add the author taxonomy data.
     if (!empty($item->author) || !empty($item->created_by_alias)) {
         $item->addTaxonomy('Author', !empty($item->created_by_alias) ? $item->created_by_alias : $item->author);
     }
     // Add the category taxonomy data.
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     if (empty($item->language)) {
         $item->language = '*';
     }
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // For Joomla 3.0, the indexer is assigned to the property
     // Index the item.
     if (EB::isJoomla30()) {
         return $this->indexer->index($item);
     }
     return FinderIndexer::index($item);
 }
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     $access = 1;
     if (is_null($item->privacy)) {
         $privacy = FD::privacy($item->user_id);
         $privacyValue = $privacy->getValue('photos', 'view');
         $item->privacy = $privacyValue;
     }
     if ($item->privacy == SOCIAL_PRIVACY_PUBLIC) {
         $access = 1;
     } else {
         if ($item->privacy == SOCIAL_PRIVACY_MEMBER) {
             $access = 2;
         } else {
             // this is not public / member items. do not index this item
             return;
         }
     }
     // $sql->select('a.id, a.title, a.alias, a.introtext AS summary, a.fulltext AS body');
     // $sql->select('a.state, a.catid, a.created AS start_date, a.created_by');
     // $sql->select('a.created_by_alias, a.modified, a.modified_by, a.attribs AS params');
     // $sql->select('a.metakey, a.metadesc, a.metadata, a.language, a.access, a.version, a.ordering');
     // $sql->select('a.publish_up AS publish_start_date, a.publish_down AS publish_end_date');
     // $sql->select('c.title AS category, c.published AS cat_state, c.access AS cat_access');
     // album onwer
     $user = FD::user($item->user_id);
     $userAlias = $user->getAlias(false);
     $photo = FD::table('Photo');
     $photo->load($item->id);
     // Build the necessary route and path information.
     // index.php?option=com_easysocial&view=photos&layout=item&id=510:00000690&type=user&uid=84:jenny-siew
     $item->url = 'index.php?option=com_easysocial&view=photos&layout=item&id=' . $photo->getAlias() . '&type=' . $photo->type . '&uid=' . $userAlias;
     $item->route = $photo->getPermalink();
     $item->route = $this->removeAdminSegment($item->route);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     $category = 'user photo';
     if ($item->type == SOCIAL_TYPE_GROUP) {
         $category = 'group photo';
     }
     $item->access = $access;
     $item->alias = $photo->getAlias();
     $item->state = 1;
     $item->catid = $photo->type == SOCIAL_TYPE_GROUP ? 2 : 1;
     $item->start_date = $photo->created;
     $item->created_by = $photo->user_id;
     $item->created_by_alias = $userAlias;
     $item->modified = $photo->assigned_date == '0000-00-00 00:00:00' ? $photo->created : $photo->assigned_date;
     $item->modified_by = $photo->user_id;
     $item->params = '';
     $item->metakey = $category . ' ' . $photo->title;
     $item->metadesc = $category . ' ' . $photo->title;
     $item->metadata = '';
     $item->publish_start_date = $item->modified;
     $item->category = $category;
     $item->cat_state = 1;
     $item->cat_access = 0;
     $item->summary = $photo->title;
     $item->body = $photo->title;
     // Add the meta-author.
     $item->metaauthor = $userAlias;
     $item->author = $userAlias;
     // add image param
     $registry = FD::registry();
     $registry->set('image', $photo->getSource());
     $item->params = $registry;
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'EasySocial.Photos');
     // Add the author taxonomy data.
     $item->addTaxonomy('Author', $userAlias);
     // Add the category taxonomy data.
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     $langParams = JComponentHelper::getParams('com_languages');
     $item->language = $langParams->get('site', 'en-GB');
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     if (FD::isJoomla30()) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
Exemple #20
0
 protected function createIndexerResult($message)
 {
     // Convert the item to a result object.
     $item = new FinderIndexerResult();
     $item->id = $message->id;
     $item->catid = $message->catid;
     // Set title context.
     $item->title = $message->subject;
     // Build the necessary url, route, path and alias information.
     $item->url = $this->getUrl($message->id, $this->extension, $this->layout);
     $item->route = $item->url . '&Itemid=' . KunenaRoute::getItemId($item->url);
     $item->path = FinderIndexerHelper::getContentPath($item->url);
     //route);
     $item->alias = KunenaRoute::stringURLSafe($message->subject);
     // Set body context.
     $item->body = KunenaHtmlParser::stripBBCode($message->message);
     $item->summary = $item->body;
     // Set other information.
     $item->published = intval($message->hold == 0);
     // TODO: add topic state
     //$item->state = intval($message->getCategory()->published == 1);
     $item->state = $item->published;
     $item->language = '*';
     // TODO: add access control
     $item->access = $this->getAccessLevel($item);
     // Set the item type.
     $item->type_id = $this->type_id;
     // Set the mime type.
     $item->mime = $this->mime;
     // Set the item layout.
     $item->layout = $this->layout;
     return $item;
 }
Exemple #21
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   3.1
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     $item->setLanguage();
     // Initialize the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = JComponentHelper::getParams('com_tags', true);
     $item->params->merge($registry);
     $registry = new JRegistry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     // Build the necessary route and path information.
     $item->url = $this->getURL($item->id, $this->extension, $this->layout);
     $item->route = TagsHelperRoute::getTagRoute($item->slug);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Get the menu title if it exists.
     $title = $this->getItemMenuTitle($item->url);
     // Adjust the title if necessary.
     if (!empty($title) && $this->params->get('use_menu_title', true)) {
         $item->title = $title;
     }
     // Add the meta-author.
     $item->metaauthor = $item->metadata->get('author');
     // Handle the link to the meta-data.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'link');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_alias');
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Tag');
     // Add the author taxonomy data.
     if (!empty($item->author) || !empty($item->created_by_alias)) {
         $item->addTaxonomy('Author', !empty($item->created_by_alias) ? $item->created_by_alias : $item->author);
     }
     // Add the language taxonomy data.
     $item->addTaxonomy('Language', $item->language);
     // Index the item.
     $this->indexer->index($item);
 }
Exemple #22
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Initialize the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = JComponentHelper::getParams('com_jevents', true);
     $item->params->merge($registry);
     $registry = new JRegistry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     // Trigger the onContentPrepare event.
     $item->summary = FinderIndexerHelper::prepareContent($item->summary, $item->params);
     $item->body = FinderIndexerHelper::prepareContent($item->body, $item->params);
     // Build the necessary route and path information.
     $itemid = $this->params->get("target_itemid", 0);
     $item->url = "index.php?option=com_jevents&task=icalevent.detail&evid=" . $item->eventid . "&Itemid=" . $itemid;
     //$this->getURL($item->id, $this->extension, $this->layout);
     $item->route = "index.php?option=com_jevents&task=icalevent.detail&evid=" . $item->eventid . "&Itemid=" . $itemid;
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // title is already set
     //$item->title;
     // Events should only be published if the category is published.etc. - do this later
     //$item->state;
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Event');
     // Add the creator taxonomy data.
     if (!empty($item->creator) || !empty($item->created_by_alias)) {
         $item->addTaxonomy('Creator', !empty($item->created_by_alias) ? $item->created_by_alias : $item->creator);
     }
     // Add the category taxonomy data. - can we do multiple categories?
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     //$item->addTaxonomy('Language', $item->language);
     // Get jevents extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     if (JevJoomlaVersion::isCompatible("3.0.0")) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
Exemple #23
0
 /**
  * Method to index a content item.
  *
  * @param   FinderIndexerResult  $item    The content item to index.
  * @param   string               $format  The format of the content. [optional]
  *
  * @return  integer  The ID of the record in the links table.
  *
  * @since   3.0
  * @throws  Exception on database error.
  */
 public function index($item, $format = 'html')
 {
     // Mark beforeIndexing in the profiler.
     static::$profiler ? static::$profiler->mark('beforeIndexing') : null;
     $db = JFactory::getDbo();
     $nd = $db->getNullDate();
     // Check if the item is in the database.
     $query = $db->getQuery(true)->select($db->quoteName('link_id') . ', ' . $db->quoteName('md5sum'))->from($db->quoteName('#__finder_links'))->where($db->quoteName('url') . ' = ' . $db->quote($item->url));
     // Load the item  from the database.
     $db->setQuery($query);
     $link = $db->loadObject();
     // Get the indexer state.
     $state = static::getState();
     // Get the signatures of the item.
     $curSig = static::getSignature($item);
     $oldSig = isset($link->md5sum) ? $link->md5sum : null;
     // Get the other item information.
     $linkId = empty($link->link_id) ? null : $link->link_id;
     $isNew = empty($link->link_id) ? true : false;
     // Check the signatures. If they match, the item is up to date.
     if (!$isNew && $curSig == $oldSig) {
         return $linkId;
     }
     /*
      * If the link already exists, flush all the term maps for the item.
      * Maps are stored in 16 tables so we need to iterate through and flush
      * each table one at a time.
      */
     if (!$isNew) {
         for ($i = 0; $i <= 15; $i++) {
             // Flush the maps for the link.
             $query->clear()->delete($db->quoteName('#__finder_links_terms' . dechex($i)))->where($db->quoteName('link_id') . ' = ' . (int) $linkId);
             $db->setQuery($query);
             $db->execute();
         }
         // Remove the taxonomy maps.
         FinderIndexerTaxonomy::removeMaps($linkId);
     }
     // Mark afterUnmapping in the profiler.
     static::$profiler ? static::$profiler->mark('afterUnmapping') : null;
     // Perform cleanup on the item data.
     $item->publish_start_date = (int) $item->publish_start_date != 0 ? $item->publish_start_date : $nd;
     $item->publish_end_date = (int) $item->publish_end_date != 0 ? $item->publish_end_date : $nd;
     $item->start_date = (int) $item->start_date != 0 ? $item->start_date : $nd;
     $item->end_date = (int) $item->end_date != 0 ? $item->end_date : $nd;
     // Prepare the item description.
     $item->description = FinderIndexerHelper::parse($item->summary);
     /*
      * Now, we need to enter the item into the links table. If the item
      * already exists in the database, we need to use an UPDATE query.
      * Otherwise, we need to use an INSERT to get the link id back.
      */
     if ($isNew) {
         $columnsArray = array($db->quoteName('url'), $db->quoteName('route'), $db->quoteName('title'), $db->quoteName('description'), $db->quoteName('indexdate'), $db->quoteName('published'), $db->quoteName('state'), $db->quoteName('access'), $db->quoteName('language'), $db->quoteName('type_id'), $db->quoteName('object'), $db->quoteName('publish_start_date'), $db->quoteName('publish_end_date'), $db->quoteName('start_date'), $db->quoteName('end_date'), $db->quoteName('list_price'), $db->quoteName('sale_price'));
         // Insert the link.
         $query->clear()->insert($db->quoteName('#__finder_links'))->columns($columnsArray)->values($db->quote($item->url) . ', ' . $db->quote($item->route) . ', ' . $db->quote($item->title) . ', ' . $db->quote($item->description) . ', ' . $query->currentTimestamp() . ', ' . '1, ' . (int) $item->state . ', ' . (int) $item->access . ', ' . $db->quote($item->language) . ', ' . (int) $item->type_id . ', ' . $db->quote(serialize($item)) . ', ' . $db->quote($item->publish_start_date) . ', ' . $db->quote($item->publish_end_date) . ', ' . $db->quote($item->start_date) . ', ' . $db->quote($item->end_date) . ', ' . (double) ($item->list_price ? $item->list_price : 0) . ', ' . (double) ($item->sale_price ? $item->sale_price : 0));
         $db->setQuery($query);
         $db->execute();
         // Get the link id.
         $linkId = (int) $db->insertid();
     } else {
         // Update the link.
         $query->clear()->update($db->quoteName('#__finder_links'))->set($db->quoteName('route') . ' = ' . $db->quote($item->route))->set($db->quoteName('title') . ' = ' . $db->quote($item->title))->set($db->quoteName('description') . ' = ' . $db->quote($item->description))->set($db->quoteName('indexdate') . ' = ' . $query->currentTimestamp())->set($db->quoteName('state') . ' = ' . (int) $item->state)->set($db->quoteName('access') . ' = ' . (int) $item->access)->set($db->quoteName('language') . ' = ' . $db->quote($item->language))->set($db->quoteName('type_id') . ' = ' . (int) $item->type_id)->set($db->quoteName('object') . ' = ' . $db->quote(serialize($item)))->set($db->quoteName('publish_start_date') . ' = ' . $db->quote($item->publish_start_date))->set($db->quoteName('publish_end_date') . ' = ' . $db->quote($item->publish_end_date))->set($db->quoteName('start_date') . ' = ' . $db->quote($item->start_date))->set($db->quoteName('end_date') . ' = ' . $db->quote($item->end_date))->set($db->quoteName('list_price') . ' = ' . (double) ($item->list_price ? $item->list_price : 0))->set($db->quoteName('sale_price') . ' = ' . (double) ($item->sale_price ? $item->sale_price : 0))->where('link_id = ' . (int) $linkId);
         $db->setQuery($query);
         $db->execute();
     }
     // Set up the variables we will need during processing.
     $count = 0;
     // Mark afterLinking in the profiler.
     static::$profiler ? static::$profiler->mark('afterLinking') : null;
     // Truncate the tokens tables.
     $db->truncateTable('#__finder_tokens');
     // Truncate the tokens aggregate table.
     $db->truncateTable('#__finder_tokens_aggregate');
     /*
      * Process the item's content. The items can customize their
      * processing instructions to define extra properties to process
      * or rearrange how properties are weighted.
      */
     foreach ($item->getInstructions() as $group => $properties) {
         // Iterate through the properties of the group.
         foreach ($properties as $property) {
             // Check if the property exists in the item.
             if (empty($item->{$property})) {
                 continue;
             }
             // Tokenize the property.
             if (is_array($item->{$property})) {
                 // Tokenize an array of content and add it to the database.
                 foreach ($item->{$property} as $ip) {
                     /*
                      * If the group is path, we need to a few extra processing
                      * steps to strip the extension and convert slashes and dashes
                      * to spaces.
                      */
                     if ($group === static::PATH_CONTEXT) {
                         $ip = JFile::stripExt($ip);
                         $ip = str_replace('/', ' ', $ip);
                         $ip = str_replace('-', ' ', $ip);
                     }
                     // Tokenize a string of content and add it to the database.
                     $count += $this->tokenizeToDb($ip, $group, $item->language, $format);
                     // Check if we're approaching the memory limit of the token table.
                     if ($count > static::$state->options->get('memory_table_limit', 30000)) {
                         $this->toggleTables(false);
                     }
                 }
             } else {
                 /*
                  * If the group is path, we need to a few extra processing
                  * steps to strip the extension and convert slashes and dashes
                  * to spaces.
                  */
                 if ($group === static::PATH_CONTEXT) {
                     $item->{$property} = JFile::stripExt($item->{$property});
                     $item->{$property} = str_replace('/', ' ', $item->{$property});
                     $item->{$property} = str_replace('-', ' ', $item->{$property});
                 }
                 // Tokenize a string of content and add it to the database.
                 $count += $this->tokenizeToDb($item->{$property}, $group, $item->language, $format);
                 // Check if we're approaching the memory limit of the token table.
                 if ($count > static::$state->options->get('memory_table_limit', 30000)) {
                     $this->toggleTables(false);
                 }
             }
         }
     }
     /*
      * Process the item's taxonomy. The items can customize their
      * taxonomy mappings to define extra properties to map.
      */
     foreach ($item->getTaxonomy() as $branch => $nodes) {
         // Iterate through the nodes and map them to the branch.
         foreach ($nodes as $node) {
             // Add the node to the tree.
             $nodeId = FinderIndexerTaxonomy::addNode($branch, $node->title, $node->state, $node->access);
             // Add the link => node map.
             FinderIndexerTaxonomy::addMap($linkId, $nodeId);
             // Tokenize the node title and add them to the database.
             $count += $this->tokenizeToDb($node->title, static::META_CONTEXT, $item->language, $format);
         }
     }
     // Mark afterProcessing in the profiler.
     static::$profiler ? static::$profiler->mark('afterProcessing') : null;
     /*
      * At this point, all of the item's content has been parsed, tokenized
      * and inserted into the #__finder_tokens table. Now, we need to
      * aggregate all the data into that table into a more usable form. The
      * aggregated data will be inserted into #__finder_tokens_aggregate
      * table.
      */
     $query = 'INSERT INTO ' . $db->quoteName('#__finder_tokens_aggregate') . ' (' . $db->quoteName('term_id') . ', ' . $db->quoteName('term') . ', ' . $db->quoteName('stem') . ', ' . $db->quoteName('common') . ', ' . $db->quoteName('phrase') . ', ' . $db->quoteName('term_weight') . ', ' . $db->quoteName('context') . ', ' . $db->quoteName('context_weight') . ', ' . $db->quoteName('language') . ')' . ' SELECT' . ' t.term_id, t1.term, t1.stem, t1.common, t1.phrase, t1.weight, t1.context,' . ' ROUND( t1.weight * COUNT( t2.term ) * %F, 8 ) AS context_weight, t1.language' . ' FROM (' . '   SELECT DISTINCT t1.term, t1.stem, t1.common, t1.phrase, t1.weight, t1.context, t1.language' . '   FROM ' . $db->quoteName('#__finder_tokens') . ' AS t1' . '   WHERE t1.context = %d' . ' ) AS t1' . ' JOIN ' . $db->quoteName('#__finder_tokens') . ' AS t2 ON t2.term = t1.term' . ' LEFT JOIN ' . $db->quoteName('#__finder_terms') . ' AS t ON t.term = t1.term' . ' WHERE t2.context = %d' . ' GROUP BY t1.term, t.term_id, t1.term, t1.stem, t1.common, t1.phrase, t1.weight, t1.context, t1.language' . ' ORDER BY t1.term DESC';
     // Iterate through the contexts and aggregate the tokens per context.
     foreach ($state->weights as $context => $multiplier) {
         // Run the query to aggregate the tokens for this context..
         $db->setQuery(sprintf($query, $multiplier, $context, $context));
         $db->execute();
     }
     // Mark afterAggregating in the profiler.
     static::$profiler ? static::$profiler->mark('afterAggregating') : null;
     /*
      * When we pulled down all of the aggregate data, we did a LEFT JOIN
      * over the terms table to try to find all the term ids that
      * already exist for our tokens. If any of the rows in the aggregate
      * table have a term of 0, then no term record exists for that
      * term so we need to add it to the terms table.
      */
     /* Emulation of IGNORE INTO behaviour */
     $db->setQuery(' SELECT ta.term' . ' FROM ' . $db->quoteName('#__finder_tokens_aggregate') . ' AS ta' . ' WHERE ta.term_id = 0');
     if ($db->loadRow() == null) {
         $db->setQuery('INSERT INTO ' . $db->quoteName('#__finder_terms') . ' (' . $db->quoteName('term') . ', ' . $db->quoteName('stem') . ', ' . $db->quoteName('common') . ', ' . $db->quoteName('phrase') . ', ' . $db->quoteName('weight') . ', ' . $db->quoteName('soundex') . ', ' . $db->quoteName('language') . ')' . ' SELECT ta.term, ta.stem, ta.common, ta.phrase, ta.term_weight, SOUNDEX(ta.term), ta.language' . ' FROM ' . $db->quoteName('#__finder_tokens_aggregate') . ' AS ta' . ' WHERE ta.term_id = 0' . ' GROUP BY ta.term, ta.stem, ta.common, ta.phrase, ta.term_weight, SOUNDEX(ta.term), ta.language');
         $db->execute();
     }
     /*
      * Now, we just inserted a bunch of new records into the terms table
      * so we need to go back and update the aggregate table with all the
      * new term ids.
      */
     $query = $db->getQuery(true)->update($db->quoteName('#__finder_tokens_aggregate') . ' AS ta')->join('INNER', $db->quoteName('#__finder_terms') . ' AS t ON t.term = ta.term')->set('ta.term_id = t.term_id')->where('ta.term_id = 0');
     $db->setQuery($query);
     $db->execute();
     // Mark afterTerms in the profiler.
     static::$profiler ? static::$profiler->mark('afterTerms') : null;
     /*
      * After we've made sure that all of the terms are in the terms table
      * and the aggregate table has the correct term ids, we need to update
      * the links counter for each term by one.
      */
     $query->clear()->update($db->quoteName('#__finder_terms') . ' AS t')->join('INNER', $db->quoteName('#__finder_tokens_aggregate') . ' AS ta ON ta.term_id = t.term_id')->set('t.' . $db->quoteName('links') . ' = t.links + 1');
     $db->setQuery($query);
     $db->execute();
     // Mark afterTerms in the profiler.
     static::$profiler ? static::$profiler->mark('afterTerms') : null;
     /*
      * Before we can insert all of the mapping rows, we have to figure out
      * which mapping table the rows need to be inserted into. The mapping
      * table for each term is based on the first character of the md5 of
      * the first character of the term. In php, it would be expressed as
      * substr(md5(substr($token, 0, 1)), 0, 1)
      */
     $query->clear()->update($db->quoteName('#__finder_tokens_aggregate'))->set($db->quoteName('map_suffix') . ' = SUBSTR(MD5(SUBSTR(' . $db->quoteName('term') . ', 1, 1)), 1, 1)');
     $db->setQuery($query);
     $db->execute();
     /*
      * At this point, the aggregate table contains a record for each
      * term in each context. So, we're going to pull down all of that
      * data while grouping the records by term and add all of the
      * sub-totals together to arrive at the final total for each token for
      * this link. Then, we insert all of that data into the appropriate
      * mapping table.
      */
     for ($i = 0; $i <= 15; $i++) {
         // Get the mapping table suffix.
         $suffix = dechex($i);
         /*
          * We have to run this query 16 times, one for each link => term
          * mapping table.
          */
         $db->setQuery('INSERT INTO ' . $db->quoteName('#__finder_links_terms' . $suffix) . ' (' . $db->quoteName('link_id') . ', ' . $db->quoteName('term_id') . ', ' . $db->quoteName('weight') . ')' . ' SELECT ' . (int) $linkId . ', ' . $db->quoteName('term_id') . ',' . ' ROUND(SUM(' . $db->quoteName('context_weight') . '), 8)' . ' FROM ' . $db->quoteName('#__finder_tokens_aggregate') . ' WHERE ' . $db->quoteName('map_suffix') . ' = ' . $db->quote($suffix) . ' GROUP BY ' . $db->quoteName('term') . ' ORDER BY ' . $db->quoteName('term') . ' DESC');
         $db->execute();
     }
     // Mark afterMapping in the profiler.
     static::$profiler ? static::$profiler->mark('afterMapping') : null;
     // Update the signature.
     $query->clear()->update($db->quoteName('#__finder_links'))->set($db->quoteName('md5sum') . ' = ' . $db->quote($curSig))->where($db->quoteName('link_id') . ' = ' . $db->quote($linkId));
     $db->setQuery($query);
     $db->execute();
     // Mark afterSigning in the profiler.
     static::$profiler ? static::$profiler->mark('afterSigning') : null;
     // Truncate the tokens tables.
     $db->truncateTable('#__finder_tokens');
     // Truncate the tokens aggregate table.
     $db->truncateTable('#__finder_tokens_aggregate');
     // Toggle the token tables back to memory tables.
     $this->toggleTables(true);
     // Mark afterTruncating in the profiler.
     static::$profiler ? static::$profiler->mark('afterTruncating') : null;
     return $linkId;
 }
Exemple #24
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     $item->setLanguage();
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Initialize the item parameters.
     $registry = new Registry();
     $registry->loadString($item->params);
     $item->params = JComponentHelper::getParams('com_knvbapi2', true);
     $item->params->merge($registry);
     $registry = null;
     //release memory
     $registry = new Registry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     $registry = null;
     //release memory
     // Trigger the onContentPrepare event.
     $item->summary = FinderIndexerHelper::prepareContent($item->summary, $item->params);
     $item->body = FinderIndexerHelper::prepareContent($item->body, $item->params);
     if ($this->sub_layout != 'default') {
         $view = $this->layout . '&layout=' . $this->sub_layout;
     } else {
         $view = $this->layout;
     }
     // Build the necessary route and path information.
     $item->url = $this->getURL($item->id, $this->extension, $view);
     $item->route = Knvbapi2HelperRoute::getTeamidRoute($item->slug, $item->language, $this->sub_layout);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Get the menu title if it exists.
     $title = $this->getItemMenuTitle($item->url);
     if (!empty($title) and $this->params->get('use_menu_title', true)) {
         $item->title = $title;
     } else {
         $item->title = $item->name;
     }
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_name');
     // Translate the state.
     $item->state = $this->translateState($item->state);
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Teamid');
     // Add the created_by taxonomy data.
     if (!empty($item->created_by_alias)) {
         $item->addTaxonomy('Author', !empty($item->created_by_name) ? $item->created_by_name : $item->created_by);
     }
     // Add the language taxonomy data.
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     $this->indexer->index($item);
 }
Exemple #25
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // Need to import component route helpers dynamically, hence the reason it's handled here
     if (JFile::exists(JPATH_SITE . '/components/' . $item->extension . '/helpers/route.php')) {
         include_once JPATH_SITE . '/components/' . $item->extension . '/helpers/route.php';
     }
     $extension = ucfirst(substr($item->extension, 4));
     // Initialize the item parameters.
     $registry = new JRegistry();
     $registry->loadString($item->params);
     $item->params = $registry;
     $registry = new JRegistry();
     $registry->loadString($item->metadata);
     $item->metadata = $registry;
     /* Add the meta-data processing instructions based on the categories
      * configuration parameters.
      */
     // Add the meta-author.
     $item->metaauthor = $item->metadata->get('author');
     // Handle the link to the meta-data.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'link');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     //$item->addInstruction(FinderIndexer::META_CONTEXT, 'created_by_alias');
     // Trigger the onContentPrepare event.
     $item->summary = FinderIndexerHelper::prepareContent($item->summary, $item->params);
     // Build the necessary route and path information.
     $item->url = $this->getURL($item->id, $item->extension, $this->layout);
     $class = $extension . 'HelperRoute';
     if (class_exists($class) && method_exists($class, 'getCategoryRoute')) {
         $item->route = $class::getCategoryRoute($item->id);
     } else {
         $item->route = ContentHelperRoute::getCategoryRoute($item->slug, $item->catid);
     }
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     // Get the menu title if it exists.
     $title = $this->getItemMenuTitle($item->url);
     // Adjust the title if necessary.
     if (!empty($title) && $this->params->get('use_menu_title', true)) {
         $item->title = $title;
     }
     // Translate the state. Categories should only be published if the parent category is published.
     $item->state = $this->translateState($item->state);
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'Category');
     // Add the language taxonomy data.
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     FinderIndexer::index($item);
 }
Exemple #26
0
 /**
  * Method to instantiate the indexer adapter.
  *
  * @param   object  &$subject  The object to observe.
  * @param   array   $config    An array that holds the plugin configuration.
  *
  * @since   2.5
  */
 public function __construct(&$subject, $config)
 {
     // Get the database object.
     $this->db = JFactory::getDbo();
     // Call the parent constructor.
     parent::__construct($subject, $config);
     // Get the type id.
     $this->type_id = $this->getTypeId();
     // Add the content type if it doesn't exist and is set.
     if (empty($this->type_id) && !empty($this->type_title)) {
         $this->type_id = FinderIndexerHelper::addContentType($this->type_title, $this->mime);
     }
     // Check for a layout override.
     if ($this->params->get('layout')) {
         $this->layout = $this->params->get('layout');
     }
     // Get the indexer object
     $this->indexer = FinderIndexer::getInstance();
 }
Exemple #27
0
 /**
  * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
  *
  * @param   string  $ordering   An optional ordering field. [optional]
  * @param   string  $direction  An optional direction. [optional]
  *
  * @return  void
  *
  * @since   2.5
  */
 protected function populateState($ordering = null, $direction = null)
 {
     // Get the configuration options.
     $app = JFactory::getApplication();
     $input = $app->input;
     $params = $app->getParams();
     $user = JFactory::getUser();
     $filter = JFilterInput::getInstance();
     $this->setState('filter.language', JLanguageMultilang::isEnabled());
     // Setup the stemmer.
     if ($params->get('stem', 1) && $params->get('stemmer', 'porter_en')) {
         FinderIndexerHelper::$stemmer = FinderIndexerStemmer::getInstance($params->get('stemmer', 'porter_en'));
     }
     $request = $input->request;
     $options = array();
     // Get the query string.
     $options['input'] = !is_null($request->get('q')) ? $request->get('q', '', 'string') : $params->get('q');
     $options['input'] = $filter->clean($options['input'], 'string');
     // Get the empty query setting.
     $options['empty'] = $params->get('allow_empty_query', 0);
     // Get the query language.
     $options['language'] = !is_null($request->get('l')) ? $request->get('l', '', 'cmd') : $params->get('l');
     $options['language'] = $filter->clean($options['language'], 'cmd');
     // Get the static taxonomy filters.
     $options['filter'] = !is_null($request->get('f')) ? $request->get('f', '', 'int') : $params->get('f');
     $options['filter'] = $filter->clean($options['filter'], 'int');
     // Get the dynamic taxonomy filters.
     $options['filters'] = !is_null($request->get('t', '', 'array')) ? $request->get('t', '', 'array') : $params->get('t');
     $options['filters'] = $filter->clean($options['filters'], 'array');
     JArrayHelper::toInteger($options['filters']);
     // Get the start date and start date modifier filters.
     $options['date1'] = !is_null($request->get('d1')) ? $request->get('d1', '', 'string') : $params->get('d1');
     $options['date1'] = $filter->clean($options['date1'], 'string');
     $options['when1'] = !is_null($request->get('w1')) ? $request->get('w1', '', 'string') : $params->get('w1');
     $options['when1'] = $filter->clean($options['when1'], 'string');
     // Get the end date and end date modifier filters.
     $options['date2'] = !is_null($request->get('d2')) ? $request->get('d2', '', 'string') : $params->get('d2');
     $options['date2'] = $filter->clean($options['date2'], 'string');
     $options['when2'] = !is_null($request->get('w2')) ? $request->get('w2', '', 'string') : $params->get('w2');
     $options['when2'] = $filter->clean($options['when2'], 'string');
     // Load the query object.
     $this->query = new FinderIndexerQuery($options);
     // Load the query token data.
     $this->excludedTerms = $this->query->getExcludedTermIds();
     $this->includedTerms = $this->query->getIncludedTermIds();
     $this->requiredTerms = $this->query->getRequiredTermIds();
     // Load the list state.
     $this->setState('list.start', $input->get('limitstart', 0, 'uint'));
     $this->setState('list.limit', $input->get('limit', $app->getCfg('list_limit', 20), 'uint'));
     // Load the sort ordering.
     $order = $params->get('sort_order', 'relevance');
     switch ($order) {
         case 'date':
             $this->setState('list.ordering', 'l.start_date');
             break;
         case 'price':
             $this->setState('list.ordering', 'l.list_price');
             break;
         case $order == 'relevance' && !empty($this->includedTerms):
             $this->setState('list.ordering', 'm.weight');
             break;
         default:
             $this->setState('list.ordering', 'l.link_id');
             break;
     }
     // Load the sort direction.
     $dirn = $params->get('sort_direction', 'desc');
     switch ($dirn) {
         case 'asc':
             $this->setState('list.direction', 'ASC');
             break;
         default:
         case 'desc':
             $this->setState('list.direction', 'DESC');
             break;
     }
     // Set the match limit.
     $this->setState('match.limit', 1000);
     // Load the parameters.
     $this->setState('params', $params);
     // Load the user state.
     $this->setState('user.id', (int) $user->get('id'));
     $this->setState('user.groups', $user->getAuthorisedViewLevels());
 }
Exemple #28
0
 /**
  * Method to index an item. The item must be a FinderIndexerResult object.
  *
  * @param   FinderIndexerResult  $item    The item to index as an FinderIndexerResult object.
  * @param   string               $format  The item format
  *
  * @return  void
  *
  * @since   2.5
  * @throws  Exception on database error.
  */
 protected function index(FinderIndexerResult $item, $format = 'html')
 {
     // Check if the extension is enabled
     if (JComponentHelper::isEnabled($this->extension) == false) {
         return;
     }
     // load foundry config
     $config = FD::config();
     $privacy = FD::privacy($item->user_id);
     //default access
     $access = 1;
     if ($config->get('users.indexer.privacy', 1)) {
         $privacyValue = $privacy->getValue('profiles', 'search');
         $item->privacy = $privacyValue;
         if ($item->privacy == SOCIAL_PRIVACY_PUBLIC) {
             $access = 1;
         } else {
             if ($item->privacy == SOCIAL_PRIVACY_MEMBER) {
                 $access = 2;
             } else {
                 // this is not public / member items. let set the access to 'special'
                 $access = 3;
             }
         }
     }
     $user = FD::user($item->user_id);
     $userAlias = $user->getAlias(false);
     $contentSnapshot = array();
     $userName = $user->getName($config->get('users.indexer.name'));
     $userEmail = $config->get('users.indexer.email') ? $user->email : '';
     $contentSnapshot[] = $userName;
     if ($userEmail) {
         // we need to check for the email field privacy
         if ($config->get('users.indexer.privacy', 1)) {
             $privacyModel = FD::model('Privacy');
             $fieldPrivacyValue = $privacyModel->getFieldValue('field.joomla_email', $user->id);
             if ($fieldPrivacyValue == SOCIAL_PRIVACY_PUBLIC || $fieldPrivacyValue == SOCIAL_PRIVACY_MEMBER) {
                 $contentSnapshot[] = $userEmail;
             } else {
                 $userEmail = '';
             }
         } else {
             $contentSnapshot[] = $userEmail;
         }
     }
     // get data from customfields
     // get customfields.
     // $fieldsLib		= FD::fields();
     // $fieldModel  	= FD::model( 'Fields' );
     // $fieldsResult 	= array();
     // $options = array();
     // $options['data'] 		= true;
     // $options['dataId'] 		= $user->user_id;
     // $options['dataType'] 	= SOCIAL_TYPE_USER;
     // $options['searchable'] 	= 1;
     // //todo: get customfields.
     // $fields = $fieldModel->getCustomFields( $options );
     // if( count( $fields ) > 0 )
     // {
     // 	//foreach( $fields as $item )
     // 	foreach( $fields as $field )
     // 	{
     // 		$userFieldData = isset( $field->data ) ? $field->data : '';
     // 		$args 			= array( $userFieldData );
     // 		$f 				= array( &$field );
     // 		$dataResult 	= @$fieldsLib->trigger( 'onIndexer' , SOCIAL_FIELDS_GROUP_USER , $f , $args );
     // 		if( $dataResult !== false && count( $dataResult ) > 0 )
     // 			$fieldsResult[]  	= $dataResult[0];
     // 	}
     // 	if( $fieldsResult )
     // 	{
     // 		$customFieldsContent 	= implode( ' ', $fieldsResult );
     // 		$contentSnapshot[] 		= $customFieldsContent;
     // 	}
     // }
     $content = implode(' ', $contentSnapshot);
     // Build the necessary route and path information.
     // we need to pass in raw url so that if the site on sef, smart serach will not create new item.
     // index.php?option=com_easysocial&view=profile&id=84:jenny-siew
     // $item->url		= 'index.php?option=com_easysocial&view=profile&id=' . $userAlias;
     $item->url = 'index.php?option=com_easysocial&view=profile&id=' . $user->id;
     $item->route = $user->getPermalink();
     $item->route = $this->removeAdminSegment($item->route);
     $item->path = FinderIndexerHelper::getContentPath($item->route);
     $userProfile = $user->getProfile();
     $metaKey = $userName;
     if ($userEmail) {
         $metaKey .= ', ' . $userEmail;
     }
     $item->title = $userName;
     $item->access = $access;
     $item->alias = $userAlias;
     $item->state = 1;
     $item->start_date = $user->registerDate;
     $item->created_by = $item->user_id;
     $item->created_by_alias = $userAlias;
     $item->modified = $user->registerDate;
     $item->modified_by = $item->user_id;
     $item->params = '';
     $item->metakey = $metaKey;
     $item->metadesc = $content;
     $item->metadata = '';
     $item->publish_start_date = $user->registerDate;
     // let put user profile as category
     $item->catid = $userProfile->id;
     $item->category = $userProfile->getTitle();
     $item->cat_state = 1;
     $item->cat_access = 0;
     $item->summary = $content;
     $item->body = $content;
     // Add the meta-author.
     $item->metaauthor = $userAlias;
     $item->author = $userAlias;
     // add image param
     $registry = FD::registry();
     $registry->set('image', $user->getAvatar());
     $item->params = $registry;
     // Add the meta-data processing instructions.
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metakey');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metadesc');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'metaauthor');
     $item->addInstruction(FinderIndexer::META_CONTEXT, 'author');
     // Add the type taxonomy data.
     $item->addTaxonomy('Type', 'EasySocial.Users');
     // Add the author taxonomy data.
     $item->addTaxonomy('Author', $userAlias);
     // Add the category taxonomy data.
     $item->addTaxonomy('Category', $item->category, $item->cat_state, $item->cat_access);
     // Add the language taxonomy data.
     // $langParams 	= JComponentHelper::getParams('com_languages');
     // $item->language = $langParams->get( 'site', 'en-GB');
     //
     $item->language = '*';
     $item->addTaxonomy('Language', $item->language);
     // Get content extras.
     FinderIndexerHelper::getContentExtras($item);
     // Index the item.
     if (FD::isJoomla30()) {
         $this->indexer->index($item);
     } else {
         FinderIndexer::index($item);
     }
 }
 /**
  * Method to check if a token is common in a language.
  *
  * @param   string  $token  The token to test.
  * @param   string  $lang   The language to reference.
  *
  * @return  boolean  True if common, false otherwise.
  *
  * @since   2.5
  */
 public static function isCommon($token, $lang)
 {
     static $data;
     // Load the common tokens for the language if necessary.
     if (!isset($data[$lang])) {
         $data[$lang] = FinderIndexerHelper::getCommonWords($lang);
     }
     // Check if the token is in the common array.
     if (in_array($token, $data[$lang])) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * Method to parse input, tokenize it, and then add it to the database.
  *
  * @param   mixed    $input    String or resource to use as input. A resource
  *                             input will automatically be chunked to conserve
  *                             memory. Strings will be chunked if longer than
  *                             2K in size.
  * @param   integer  $context  The context of the input. See context constants.
  * @param   string   $lang     The language of the input.
  * @param   string   $format   The format of the input.
  *
  * @return  integer  The number of tokens extracted from the input.
  *
  * @since   2.5
  */
 protected function tokenizeToDb($input, $context, $lang, $format)
 {
     $count = 0;
     $buffer = null;
     if (!empty($input)) {
         // If the input is a resource, batch the process out.
         if (is_resource($input)) {
             // Batch the process out to avoid memory limits.
             while (!feof($input)) {
                 // Read into the buffer.
                 $buffer .= fread($input, 2048);
                 /*
                  * If we haven't reached the end of the file, seek to the last
                  * space character and drop whatever is after that to make sure
                  * we didn't truncate a term while reading the input.
                  */
                 if (!feof($input)) {
                     // Find the last space character.
                     $ls = strrpos($buffer, ' ');
                     // Adjust string based on the last space character.
                     if ($ls) {
                         // Truncate the string to the last space character.
                         $string = substr($buffer, 0, $ls);
                         // Adjust the buffer based on the last space for the next iteration and trim.
                         $buffer = JString::trim(substr($buffer, $ls));
                     } else {
                         $string = $buffer;
                     }
                 } else {
                     $string = $buffer;
                 }
                 // Parse the input.
                 $string = FinderIndexerHelper::parse($string, $format);
                 // Check the input.
                 if (empty($string)) {
                     continue;
                 }
                 // Tokenize the input.
                 $tokens = FinderIndexerHelper::tokenize($string, $lang);
                 // Add the tokens to the database.
                 $count += $this->addTokensToDb($tokens, $context);
                 // Check if we're approaching the memory limit of the token table.
                 if ($count > self::$state->options->get('memory_table_limit', 30000)) {
                     $this->toggleTables(false);
                 }
                 unset($string);
                 unset($tokens);
             }
         } elseif (strlen($input) > 2048) {
             $start = 0;
             $end = strlen($input);
             $chunk = 2048;
             /*
              * As it turns out, the complex regular expressions we use for
              * sanitizing input are not very efficient when given large
              * strings. It is much faster to process lots of short strings.
              */
             while ($start < $end) {
                 // Setup the string.
                 $string = substr($input, $start, $chunk);
                 // Find the last space character if we aren't at the end.
                 $ls = $start + $chunk < $end ? strrpos($string, ' ') : false;
                 // Truncate to the last space character.
                 if ($ls !== false) {
                     $string = substr($string, 0, $ls);
                 }
                 // Adjust the start position for the next iteration.
                 $start += $ls !== false ? $ls + 1 - $chunk + $chunk : $chunk;
                 // Parse the input.
                 $string = FinderIndexerHelper::parse($string, $format);
                 // Check the input.
                 if (empty($string)) {
                     continue;
                 }
                 // Tokenize the input.
                 $tokens = FinderIndexerHelper::tokenize($string, $lang);
                 // Add the tokens to the database.
                 $count += $this->addTokensToDb($tokens, $context);
                 // Check if we're approaching the memory limit of the token table.
                 if ($count > self::$state->options->get('memory_table_limit', 30000)) {
                     $this->toggleTables(false);
                 }
             }
         } else {
             // Parse the input.
             $input = FinderIndexerHelper::parse($input, $format);
             // Check the input.
             if (empty($input)) {
                 return $count;
             }
             // Tokenize the input.
             $tokens = FinderIndexerHelper::tokenize($input, $lang);
             // Add the tokens to the database.
             $count = $this->addTokensToDb($tokens, $context);
         }
     }
     return $count;
 }