<?php
#CMS - CMS Made Simple
#(c)2004 by Ted Kulp (wishy@users.sf.net)
#This project's homepage is: http://cmsmadesimple.sf.net
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#### fixes by Fernando Morgado aka Jo Morg 17 July 2014

function smarty_cms_function_autometa($params, &$smarty)
{
  $gCms = cmsms();
  # params
  $wordcount = isset($params['key_number'])?$params['key_number']:10;
  $wordlength = isset($params['key_length'])?$params['key_length']:5;
  $worddensity = isset($params['key_density'])?$params['key_density']:4;
  $keywords = (isset($params['keywords']) && !$params['keywords'])?0:1;
  $description = (isset($params['description']) && !$params['description'])?0:1;
  $desclength = (isset($params['desc_length']))?$params['desc_length']:150;
  $adddesc = (isset($params['desc_add']))?$params['desc_add']:'';
  $addkeys = array();
  if (isset($params['key_add'])) {
    $x = explode(',',$params['key_add']);
    foreach ($x as $key) {
      $addkeys[] = trim($key);
    }
  }
  $desc = '';

  # if News
  if (isset($_REQUEST['mact'])) {
    $ary = explode(',', $_REQUEST['mact'], 4);
    $modulename = (isset($ary[0])?$ary[0]:'');
    $id = (isset($ary[1])?$ary[1]:'');
    if ($modulename == 'News') {
      $extra_attr = 'article';
      $module_name = 'News';
      $content_id = $_REQUEST[$id.'articleid'];
      $desc = $smarty->get_template_vars('autodescription');
    }
  } 
  
  if (!isset($content_id) || empty($content_id)) {
    $extra_attr = 'content';
    $module_name = 'Search';
    $content_obj = $gCms->GetContentOperations()->getContentObject();
    if (is_object($content_obj))
    {    
      $content_id = $content_obj->Id();
      $manager = $gCms->GetHierarchyManager();
      $node = $manager->getNodeById($content_id);
      if( !isset($node) || $node === FALSE ) return;
      $content = $node->Getcontent();
      preg_match_all("|<meta[^>]+name=\"([^\"]*)\"[^>]+content=\"([^\"]*)\"[^>]+>|i",
      $gCms->GetContentOperations()->getContentObject()->Metadata(), $preg_array, PREG_SET_ORDER);
      
      // find existing meta data
      $found_meta = array();
      if (!empty($preg_array)) {
        foreach($preg_array as $meta) {
          $found_meta[$meta[1]] =  $meta[2];
        }
      }
      $desc = $content->GetPropertyValue('content_en');
    }
  }

  $do_keywords = isset($found_meta['keywords'])?false:true;
  $do_description = isset($found_meta['description'])?false:true;

  if ($do_keywords && $keywords) {
    if (CmsModule::GetModuleInstance('Search')) {
      $db = $gCms->GetDb();
      $query = 'SELECT b.word
              FROM '.cms_db_prefix().'module_search_items a, 
                   '.cms_db_prefix().'module_search_index b 
             WHERE a.content_id = ? 
               AND a.module_name = ? 
               AND a.extra_attr = ? 
               AND a.id = b.item_id 
               AND length(b.word) >= ? 
           AND b.count >= ?
       ORDER BY b.count DESC';

      $dbr = $db->SelectLimit( $query, $wordcount, 0, array($content_id, $module_name, $extra_attr, $wordlength, $worddensity));

      $wordlist = array();
      while( $dbr && ($row = $dbr->FetchRow() ) )
      {
        $wordlist[] = strip_tags(str_replace('"','',$row['word']));
      }
      $addkeys = array_diff($addkeys,$wordlist);
      $wordlist = array_merge($addkeys, $wordlist);
      if (!empty($wordlist)) {
        printf ('<meta name="keywords" content="'.implode(', ',$wordlist).'" />'."\n");
      }
    }
  }

  if ($do_description && $description) {
    $desc = preg_replace('/[\n\r]/','',$desc);
    $desc = str_replace('><','> <',$desc);
    $desc = strip_tags(str_replace('"','',$desc));
    $desc = preg_replace('/{.*}/','',$desc);
    if (mb_strlen($desc) > $desclength) {
      $break = '.';
      if (false !== ($breakpoint = mb_strpos($desc, $break, $desclength))) {
        if ($breakpoint < mb_strlen($desc) - 1) {
          $desc = mb_substr($desc, 0, $breakpoint).'.';
        }
      }
    }
    if (!empty($desc)) {
      printf ('<meta name="description" content="'.$adddesc.' '.trim($desc).'" />'."\n");
    }
  }

}

function smarty_cms_help_function_autometa() {
  ?>
  <h3>What does this do?</h3>
  <p>Creates meta tags "keywords" and "description" on-the-fly if these tags are not found in the page metadata field. Keywords are taken from Search module. Description includes first characters of the page content.</p>
    <h3>How do I use it?</h3>
    <p>Just insert the tag into your template/page like: <code>{autometa}</code></p>

    <h3>Module News</h3>
    <p>Keywords meta for detail view of news is supported automatically. To add auto description from news article, open detail template of news and add {assign var="autodescription" value=$entry->summary} or {assign var="autodescription" value=$entry->content} at the top of the template. Tip: you would add the second example if you do not use summary field for your news articles.</p>
    
    <h3>What parameters does it take?</h3>
    <p>
    </p><ul>
    <li><em>(optional)</em> <tt>keywords 1/0</tt> - Set to 1 by default (requires Search module). If set to 0 keywords meta tag will not be generated</li>
    <li><em>(optional)</em> <tt>description 1/0</tt> - Set to 1 by default (requires mb string functions). If set to 0 description meta tag will not be generated</li> 
    <li><em>(optional)</em> <tt>key_number</tt> - Maximum number of keywords (default: 10 words)</li>
        <li><em>(optional)</em> <tt>key_length</tt> - Ignore words of characters in length or less (default: 5 characters). </li> 
    <li><em>(optional)</em> <tt>key_density</tt> - Minimum occurrencies of keywords found on the page. (default: 4 times)</li>
    <li><em>(optional)</em> <tt>key_add</tt> - Define keywords separated with comma that always added and merged to the search keys. </li>
    <li><em>(optional)</em> <tt>desc_length</tt> - Maximum length of description (default: 150 characters). The description is automatically truncated at the end of sentence and therefore can be shorter as the value given.</li>
    <li><em>(optional)</em> <tt>desc_add</tt> - Define some text that always added at the start of the description.</li>
    </ul>

  <?php
}

function smarty_cms_about_function_autometa() {
  ?>
  <h3>About</h3>
  <p>Author: iCMS.info</p>
  <p>fixes by Fernando Morgado aka Jo Morg 17 July 2014</p>
  <p>Version: 1.2.2</p>
  <h3>Change Log</h3>
  <ul>
    <li><strong>1.2.1</strong>:
      <ul>
        <li>Changed the call to cmsms();</li>
      </ul>
    </li>
    <li><strong>1.2.2</strong>:
      <ul>
        <li>Changed some calls to CMSMS API;</li>
      </ul>
    </li>
  </ul>
  <?php
}
?>