// ------------------------------------------------------------
// Snippet: ListRelated - modified for mindspill.net 22/01/2006
// ------------------------------------------------------------
// Version: 1.0 beta 1
// Date: September 6, 2005
// ryan@vertexworks.com
//
// This snippet was designed to show a list of pages that are
// related based on specified keywords, or those used in the
// current page
//
// Based on ListRelated by Jaredc and updated for MODx.
// jaredc@honeydewdesign.com
//
// Needs to be updated to support Webuser Logins Menu Items
// and also possibly "in menu" items.
//
// Modified by Stephan Dale for mindspill.net to add some new request parameters.
// &showDescriptions - if true, shows the docs description next to it's link. Defaults to false.
// &linkText - [ 'pagetitle' | 'longtitle' ] Choice of link text. Defaults to 'pagetitle'.

// Configuration Settings

   // LR_keywords [ string ]
   // This is a comma separated list of keywords that can be set
   // from the snippet parameter ONLY. Ex:
   // [[ListRelated?LR_keywords=fun,functional,good stuff]]
   // If no snippet variable is set, related pages will be found
   // based on the host page's keywords.

   // $maxRelated [ int ]
   // The maximum number of related pages you want to have. Can also
   // be set/overridden as the snippet variable "LR_max" as in:
   // [[ListRelated?LR_max=5]]
   $maxRelated = 10;

   // $relatedListTitle [ string ]
   // Give your related list of links a title if you desire- otherwise
   // set as an empty string ''. Can also be declared in snippet call
   // with "LR_title" like:
   // [[ListRelated?LR_title=Other links you might like]]
   $relatedListTitle = 'Related links:';

   // $linkToSearch [ true | false ]
   // If you would like to have a link at the end of your list for more
   // links based on search results of the current keywords.
   // FUTURE FEATURE - NOT CURRENTLY USED
   $linkToSearch = false;

   // $removeNewlines [ true | false ]
   // As always, with lists, it's best NOT to have new lines and whitespace
   // with IE. For debugging and reading source code, set to false, for live
   // implementation and styling, try setting to true.
   $removeNewlines = true;
   
   // $sortBy [ 'date' | 'pagetitle' ]
   // Field you would like to sort by. Options include:
   // date       - dates will be sorted by pub_date if it exists, else createdon
   // pagetitle  - page title
   // Can also be set in snippet call with $LR_sortBy (see example under $sortDir)
   $sortBy = 'date';

   // $sortDir [ 'ASC' | 'DESC' ]
   // Choose to sort in ascending (ASC) or descending (DESC) order. Can be set
   // in snippet call with $LR_sortDir:
   // [[ListRelated?LR_sortBy=date&LR_sortDir=DESC]]
   $sortDir = 'DESC';

   // $nonefound [ 'string' ]
   // What to return when no related  records are found.
   $nonefound = '<p>No related pages or links.</p>';

   // $linkText [ 'pagetitle' | 'longtitle' ]
   // Choice of link text. Can be set in snippet call with LR_linkText:
   // [[ListRelated?LR_linkText=longtitle]]
   // Defaults to 'pagetitle'.
   $linkText = 'pagetitle';
   
   // $showDescriptions [ true | false ]
   // if true, shows the docs description next to it's link.
   // Can be set in snippet call with LR_showDescription:
   // [[ListRelated?LR_showDescriptions=true]]   
   // Defaults to false.
   $showDescriptions = false;

// Styles

   // .LR_listTitle     class for list title
   // .LR_linksList     class for ul element

// ***********************************
// END CONFIG SETTINGS
// THE REST SHOULD TAKE CARE OF ITSELF
// ***********************************

// assign IE variable
$newline = ($removeNewlines)? '':"\n";

// assign appropriate default or passed variables
$maxRelated = (isset($LR_max))? $LR_max : $maxRelated;
$relatedListTitle = (isset($LR_title))? $LR_title : $relatedListTitle ;
$sortBy = (isset($LR_sortBy))? $LR_sortBy: $sortBy ;
$sortDir = (isset($LR_sortDir))? $LR_sortDir :$sortDir ;
$linkText = (isset($LR_linkText))? $LR_linkText :$linkText ;
$showDescriptions = (isset($LR_showDescriptions))? $LR_showDescriptions :$showDescriptions ;

// Make array of keywords from snippet or from current page. Snippet
// variables have priority.

if (isset($LR_keywords)){
  $kArray= explode(",",$LR_keywords);
} else {
  $kArray = $modx->getKeywords();
}

// if there are keywords, make the list
$relatedOutput = '';
if ($kArray) {
  $keyString = '';
  foreach ($kArray as $key){
    $keyString .= "'".$key."',";
  } 
  $keyString = substr($keyString,0,strlen($keyString)-1);

  // make sql statement for retreiving similar pages
  $pre= $modx->dbConfig['dbase'].".".$modx->dbConfig['table_prefix'];

  $relatedSql = "
    SELECT DISTINCT content.id, content.".$linkText.", content.description, 
      IF(content.pub_date > 0, content.pub_date, content.createdon) AS date
    FROM 
    ".$pre."site_content AS content,
    ".$pre."keyword_xref AS xref,
    ".$pre."site_keywords AS keywords
    WHERE keywords.keyword IN (".$keyString.")
    AND xref.keyword_id = keywords.id
    AND content.id = xref.content_id
    AND content.id != ".$modx->documentObject['id']."
    ORDER BY ". $sortBy . ' ' . $sortDir ."
    LIMIT ".$maxRelated.";";

  $relatives = $modx->dbQuery($relatedSql);
  $relativeCount = $modx->recordCount($relatives);
  $relArray = array();
  for($i=0;$i<$relativeCount;$i++)  {
    array_push($relArray,$modx->fetchRow($relatives));
  }

  // start output if we have results
  if ($relativeCount) {
    $relatedOutput .= ($relatedListTitle )?'<span class="LR_listTitle">' . $relatedListTitle . '</span>' : '' ;
    $relatedOutput .= '<ul class="LR_linksList">'.$newline;
    if (!$showDescriptions) {
      for ($li=0;$li<$relativeCount;$li++){
        $relatedOutput .= '<li><a href="[~' . $relArray[$li]['id'] . '~]">' . $relArray[$li][$linkText] . '</a></li>'.$newline;
      }
    }
    else {
      for ($li=0;$li<$relativeCount;$li++){
        $relatedOutput .= '<li><a href="[~' . $relArray[$li]['id'] . '~]">' . $relArray[$li][$linkText] . '</a> - '.$relArray[$li]['description'].'</li>'.$newline;
      }
    }
    $relatedOutput .= '</ul>'.$newline;
  } 
}
if (empty($relatedOutput)) {
  // there are no related records for this page
  $relatedOutput .= $nonefound.$newline;
}

return $relatedOutput;