Главная > Статьи > Облако тегов для joomla 1.6+ - Административная часть (1)

Облако тегов для joomla 1.6+ - Административная часть (1)

Содержание материала
Облако тегов для joomla 1.6+
База дынных
Языковые константы
Административная часть (1)
Административная часть (2)
Установка плагинов, модулей
Все страницы
23.09.2012 12:54

   Теперь самое долго мучительное, не буду расписывать, какой кусок кода - что делает, просто буду писать куда и что вставлять.

   Файл administrator\components\com_content\views\article\tmpl\edit_metadata.php перед закрывающим тегом </ul> дописываем:

<li><?php echo $this->form->getLabel('cloudtaglist'); ?>
<?php echo $this->form->getInput('cloudtaglist'); ?></li>
<li><?php echo $this->form->getLabel('cloudtagforarticle'); ?>
<?php echo $this->form->getInput('cloudtagforarticle'); ?></li>

   Файл administrator\components\com_content\models\article.php находим кусочек кода:

if (parent::save($data)) {

   и вставляем за ним:

$this->addCloudTag($data);

   дальше в этом же файле перед самым последним символом "}" дописываем:

   public function getArticlesWithThisTags($tags_id){
      $return = false;
      if(!empty($tags_id)){
         $db = $this->getDbo();
         $string_tags_id = implode(',',$tags_id);
         $sql = "SELECT COUNT(id) FROM #__content
               LEFT JOIN #__cloud_tags_x_content ON tag_x_content_content_id = id
               LEFT JOIN #__cloud_tags ON tag_x_content_tag_id = tag_id
               WHERE tag_id IN(".$string_tags_id.")
               GROUP BY title";
         $db->setQuery($sql);
         if (!$db->query()){
            throw new Exception($db->getErrorMsg());
         }
         $result = $db->loadResult();
         if(!empty($result))
         {
            $return = $result;
         }
      }
      return $return;
   }

   public function getTagCloudByArticle($id)
   {
      $return = false;
      $db   = JFactory::getDBO();
      $db->setQuery(
         'SELECT *
          FROM #__cloud_tags
          LEFT JOIN #__cloud_tags_x_content ON tag_id = tag_x_content_tag_id '.(!is_null($id) && $id !==0?'AND tag_x_content_content_id = '.$id:'').'
          GROUP BY tag_id
          ORDER BY tag_x_content_id DESC ,tag_text ASC'
      );
      if(!$db->query())
      {
         $return = false;
      }
      else
      {
         $return = $db->loadObjectList();
      }
      return $return;
   }
   
   public function assetSearchTag($search_text,$id = null)
   {
      if(!empty($search_text))
      {
         $db   = JFactory::getDBO();
         if(is_null($id) || $id == 0)
         {
            $sql = "SELECT tag_text,tag_id FROM #__cloud_tags
                  WHERE tag_text LIKE '%".$search_text."%'";
         }
         else
         {
            $sql = "SELECT tag_text,tag_id,tag_x_content_tag_id FROM #__cloud_tags
                  LEFT JOIN #__cloud_tags_x_content ON tag_x_content_tag_id = tag_id AND tag_x_content_content_id = {$id}
                  WHERE tag_text LIKE '%".$search_text."%'
                  GROUP BY tag_id";
         }
         $db->setQuery($sql);
         if(!$db->query())
         {
            $return = false;
         }
         else
         {
            $return = $db->loadObjectList();
            if(!is_null($id) || $id !== 0)
            {
               foreach($return as $numArray => $tag)
               {
                  if($tag->tag_id == $tag->tag_x_content_tag_id)
                  {
                     unset($return[$numArray]);
                  }
               }
            }
         }
         return $return;
      }
      else return false;
   }
   
   public function rmCloudTags($ids,$only_tags = false){
      $result = false;
      if(is_array($ids)){
         $db = $this->getDbo();
         $data = implode(',',$ids);
         if($only_tags){
            $sql = "DELETE FROM #__cloud_tags
                  WHERE tag_id IN({$data})";
         }
         else{
            $sql = "DELETE FROM #__cloud_tags_x_content,#__cloud_tags
                  USING #__cloud_tags_x_content
                  INNER JOIN #__cloud_tags
                  WHERE tag_x_content_tag_id IN({$data}) AND tag_id IN({$data})";
         }
         $db->setQuery($sql);
         if (!$db->query()){
            throw new Exception($db->getErrorMsg());
         }
         $result = true;
      }
      return $result;
   }
   
   public function addCloudTag($data){
         if(!empty($data['cloudtagforarticle']))
         {
            $content_id = $data['id'] = JRequest::getVar('id');
            $db = $this->getDbo();
            if(empty($content_id) || $content_id == 0)
            {
               $db->setQuery("SELECT MAX(id) FROM #__content");
               if (!$db->query()){
                  throw new Exception($db->getErrorMsg());
               }
               $content_id = $db->loadResult();
            }
            $sql_tag_need_create = 'INSERT INTO #__cloud_tags (tag_text,tag_count) VALUES ';
            $tag_need_create = '';
            $db->setQuery("SELECT tag_text FROM #__cloud_tags");
            if (!$db->query()){
               throw new Exception($db->getErrorMsg());
            }
            $current_isset_tags = $db->loadResultArray();
            $arrayCloudTags = ContentHelper::creatArrayCloudTagsFromString($data['cloudtagforarticle']);
            $arrays_tag_to_sql = '';
            $arrayCloudTags = array_unique($arrayCloudTags);
            foreach($arrayCloudTags as $taggad){
               $arrays_tag_to_sql[] = "'".$taggad."'";
            }
            foreach($arrayCloudTags as $tag){
               if(!in_array($tag,$current_isset_tags))
               {
                  $tag_need_create .= "('".$tag."',1),";
               }
            }
            $string_tags = implode(',',$arrays_tag_to_sql);
            $tag_need_create = JString::substr($tag_need_create,0,-1);
            if(!empty($tag_need_create)){
               $db->setQuery($sql_tag_need_create.$tag_need_create);
               if (!$db->query()){
                  throw new Exception($db->getErrorMsg());
               }
            }
            if(!empty($content_id))
            {
               
               $current_tags = '';
               $sqlCloudTag = "SELECT     tag_id,
                                  tag_count,
                                  tag_x_content_id,
                                  tag_text,
                                  IF(tag_text IN(".$string_tags."),'true','false') need_drop_from_article
                              FROM #__cloud_tags
                              LEFT JOIN #__cloud_tags_x_content ON tag_x_content_tag_id = tag_id
                                                       WHERE tag_x_content_content_id = {$content_id}";
               $db->setQuery($sqlCloudTag);
               if (!$db->query()){
                  throw new Exception($db->getErrorMsg());
               }
               $result_iseet_tag = $db->loadObjectList();
               foreach($result_iseet_tag as $tag_current){
                  $current_tags[] = $tag_current->tag_text;
               }
               $sqlSelectDataForNeedsTags = "SELECT tag_id,tag_count,tag_text
                                     FROM #__cloud_tags
                                     WHERE tag_text IN(".$string_tags.")";
               $db->setQuery($sqlSelectDataForNeedsTags);
               if (!$db->query()){
                  throw new Exception($db->getErrorMsg());
               }
               $result_iseet_tags_tag = $db->loadObjectList();
               $tag_need_attach = $tag_need_downgrade = $sql_tag_drop_from_article = $tag_need_drop_from_article = '';
               $arrayCloudTags = array_unique($arrayCloudTags);
               foreach($arrayCloudTags as $key => $tag_need)
               {
                  if(!in_array($tag_need,$current_tags)){
                     foreach($result_iseet_tags_tag as $tag_isset_tag){
                        if($tag_isset_tag->tag_text == $tag_need){
                           $need_object_id = $tag_isset_tag->tag_id;
                           break;
                        }
                     }
                     $tag_need_attach .= "({$content_id},'".$need_object_id."'),";
                     $where_sql_part_for_upgrade = $need_object_id.",";
                  }
               }
               if(!empty($tag_need_attach)){
                  $tag_need_attach = JString::substr($tag_need_attach,0,-1);
                  $where_sql_part_for_upgrade = JString::substr($where_sql_part_for_upgrade,0,-1);
                  $sql_tag_attach = "INSERT INTO #__cloud_tags_x_content (tag_x_content_content_id,tag_x_content_tag_id) VALUES ".$tag_need_attach;
                  $db->setQuery($sql_tag_attach);
                  if (!$db->query()){
                     throw new Exception($db->getErrorMsg());
                  }
                  $sql_upgrade_tag = "UPDATE #__cloud_tags SET tag_count = tag_count + 1 WHERE tag_id IN(".$where_sql_part_for_upgrade.")";
                  $db->setQuery($sql_upgrade_tag);
                  if (!$db->query()){
                     throw new Exception($db->getErrorMsg());
                  }
               }
               foreach($result_iseet_tag as $tag_need_drop)
               {
                  if(!in_array($tag_need_drop->tag_text,$arrayCloudTags)){
                     $tag_need_drop_from_article .= $tag_need_drop->tag_x_content_id.",";
                     $tag_need_downgrade .= $tag_need_drop->tag_id.",";
                  }
               }
               if(!empty($tag_need_drop_from_article)){
                  $tag_need_drop_from_article = JString::substr($tag_need_drop_from_article,0,-1);
                  $tag_need_downgrade = JString::substr($tag_need_downgrade,0,-1);
                  $sql_tag_drop_from_article = "DELETE FROM #__cloud_tags_x_content WHERE tag_x_content_id IN(".$tag_need_drop_from_article.")";
                  $sql_downgrade_tag = "UPDATE #__cloud_tags SET tag_count = if(tag_count < 2,tag_count,tag_count - 1) WHERE tag_id IN(".$tag_need_downgrade.")";
                  $db->setQuery($sql_tag_drop_from_article);
                  if (!$db->query()){
                     throw new Exception($db->getErrorMsg());
                  }
                  $db->setQuery($sql_downgrade_tag);
                  if (!$db->query()){
                     throw new Exception($db->getErrorMsg());
                  }
               }
            }
         }
         else{
            $db = $this->getDbo();
            $content_id = $data['id'] = JRequest::getVar('id');
            if(isset($content_id) && $content_id !== 0){
               $sql_tag_drop_from_article = "DELETE FROM #__cloud_tags_x_content WHERE tag_x_content_content_id = {$content_id}";
               $db->setQuery($sql_tag_drop_from_article);
               if (!$db->query()){
                  throw new Exception($db->getErrorMsg());
               }
            }
         }
   }

    Дальше окрываем файл new\administrator\components\com_content\controller.php и тоже самое перед самым последним символом "}" добавляем:

public function rm_ct()
   {
      $ids = JRequest::getVar('tag_ids');
      $ids = explode(',',$ids);
      $work_type = JRequest::getVar('wt');
      $id = JRequest::getInt('id',null);
      $confirm = JRequest::getInt('confirm');
      $model = $this->getModel('Article', '', array());
      if($work_type == 'delete'){
         $current_attached_article = $model->getArticlesWithThisTags($ids);
         if(!empty($current_attached_article)){
            if($confirm == 1){
               $result = $model->rmCloudTags($ids,false);
               $html_to_show = $this->getIssetsTags($id,$model);
               if(!empty($html_to_show)) echo $html_to_show;
            }
            else
            {
               echo "WITH_ARTICLE";
            }
         }
         elseif(empty($current_attached_article) || $current_attached_article === false){
            $result = $model->rmCloudTags($ids,true);
            $html_to_show = $this->getIssetsTags($id,$model);
            if(!empty($html_to_show)) echo $html_to_show;
         }
      }
      elseif($work_type == 'string'){
         $tag_string = $this->getTagsString($id);
         if(!empty($tag_string)) echo $tag_string;
      }
      elseif($work_type == 'search'){
         $search_text = JRequest::getVar('sw');
         $resut_search = $this->searchTag($id,$model,$search_text);
         if(!empty($resut_search)) echo $resut_search;
      }
   }
   
   public function getIssetsTags($id = null,$model){
      
      $tagList = $model->getTagCloudByArticle($id);
      $html = $this->getOptionList($tagList,$id);
      return $html;
   }
   
   public function searchTag($id = null,$model,$search_text)
   {
      if(!empty($search_text))
      {
         $tagList = $model->assetSearchTag($search_text,$id);
         $html = $this->getOptionList($tagList,$id);
      }
      else
      {
         $tagList = $model->getTagCloudByArticle($id);
         $html = $this->getOptionList($tagList,$id);
      }
      return $html;
   }
   
   public function getOptionList($tagList,$id)
   {
      $pre_counter = 1;
      $num_tags = count($tagList);
      $html = '';
      $num_of_current_tag = 0;
      if($num_tags == 0)
      {
         $html = "";
         $html .= "\n<input size=\"40\" placeholder=\"".JText::_('TAGS_SEARCH_TEXT')."\" class=\"searchCloudTag\" type=\"text\" id=\"searchCloudTag\">
<select class=\"tagcloudstring\" size=\"15\" cols=\"10\" multiple=\"multiple\" id=\"".$this->id."\" name=\"".$this->name."\">";
$html .= "\n<option>".JText::_('NO_TAGS_ALL')."</option>";
$html .= "\n</select>";
      }
      else
      {
         foreach($tagList as $nummer){
            if($nummer->tag_x_content_content_id == $id && $id !== 0){
               $num_of_current_tag++;
            }
         }
         foreach($tagList as $tag)
         {
            if($pre_counter == 1)$html .= "\n<optgroup label=\"".JText::_('CURREN_ATTACHED_TAGS')."\">";
            if($pre_counter == ($num_of_current_tag + 1))$html .= "\n<optgroup label=\"".JText::_('FREE_ATTACHED_TAGS')."\">";
            $html .= "\n<option ".($tag->tag_x_content_content_id == $id && $id !== 0?" ":" ondblclick=\"addTheTag(this);\" ")." value=\"".$tag->tag_id."\">".$tag->tag_text."</option>";
            if($pre_counter == $num_of_current_tag)$html .= "\n</optgroup>";
            if($pre_counter == $num_tags)$html .= "\n</optgroup>";
            $pre_counter++;
         }
      }
      return $html;
   }
   
   public function getTagsString($id = null){
      $db   = JFactory::getDBO();
      $db->setQuery(
         'SELECT tag_text FROM #__cloud_tags_x_content LEFT JOIN #__cloud_tags ON tag_id = tag_x_content_tag_id WHERE tag_x_content_content_id = '.$id
      );
      if(!$db->query())
      {
         $tagList = false;
      }
      else
      {
         $html = '';
         $tagList = $db->loadObjectList();
         $count = count($tagList);
         foreach($tagList as $key => $tag)
         {
            $html .= "".$tag->tag_text.($key < $count-1?",\n":"\n");
         }
         return $html;
      }
   }

   потом в файле administrator\components\com_content\helpers\content.php тоже самое, перед последним символом "}" добавляем код:

public static function creatArrayCloudTagsFromString($string){
      $string = trim($string);
      if(JString::substr($string,-1) == ',')$string = JString::substr($string,0,-1);
      $array_tags = explode(',',$string);
      $new_array_tags = '';
      foreach($array_tags as $tag){
         $tag = trim($tag);
         if(!empty($tag))$new_array_tags[] = $tag;
      }
      return $new_array_tags;
   }

   Дальше осталось только отображение в самой админке.



 

Комментарии 

 
# Alex 24.09.2012 09:35
Супер, наконец то, что то бесплатное и адекватное. Хоть немного пришлось потрудиться конечно, но оно того стояло. Спасибо
Ответить | Ответить с цитатой | Цитировать
 
 
# Doroti 26.09.2012 08:09
Спасибо, было немного возни, но справилась:)
Ответить | Ответить с цитатой | Цитировать
 

Добавить комментарий



Обновить

 

Сторонние

Модуль новостей для Joomla - JU News Ultra
14.11.2011 |  4166
Модуль вывода новостей JU News Ultra - еще один способ...

Новости

BlackBerry Q10 – телефон для фанатов
IT мир
06.06.2013 |  49
Смартфон BlackBerry Q10 весьма недешевый гаджет, стоимость данного устройства составляет...
Раскрутка Lumia 928
IT мир
04.06.2013 |  55
Компания Nokia готовится вплотную заняться рекламой аппарата Lumia 928. Некоторое...
Прокачанные новинки HTC
IT мир
30.05.2013 |  146
На днях известная компания HTC заявила о выпуске сразу 2-х...
Samsung Galaxy Core – Android-смартфон для всех
IT мир
30.05.2013 |  221
Устройство Samsung Galaxy Core позиционируется производителем, как доступный смартфон, обладающий...

посл. Комментарии

Вход