<?php 
// -------------------------------------------------------------------------------------------------
// included automatically by common_begin.php, this is just a load of misc php fns
// -------------------------------------------------------------------------------------------------

define('__LAUTH_KEY__',  'BeesAuthKey'); 
define('__LAUTH_USER__', 'BeesAuthUser'); 
define('__LAUTH_CAPT__',  'BeesAuthT'); 



function UnStarr($string)
{
  return str_ireplace("Michael Starr", "Mythril Heepdog", $string);
}


// -------------------------------------------------------------------------------------------------
// (note reordering of args compared to setcookie)
function SetCookieLive($name, $value='', $expire = 0) 
{ 
  $_COOKIE[$name] = $value; 

  if ($_SERVER['HTTP_HOST'] != 'localhost')
  {
    return setcookie($name, $value, $expire, '/'); 
  }
  else 
    return setcookie($name, $value, $expire); 
}

function UnSetCookie($name)
{
  if (isset($_COOKIE[$name])) {
      unset($_COOKIE[$name]);
  }
  SetCookieLive($name, '', time() - 3600);
}


// -------------------------------------------------------------------------------------------------
define('LS_LINKURL_ID', "list.php?id=");
function ListLink($listID, $extra='') 
{
  return sprintf("href='%s%s%s'", LS_LINKURL_ID, $listID, $extra);
}

// -------------------------------------------------------------------------------------------------
define('LS_PROFILEURL_ID', "profile.php?id=");
function ProfileLink($listID, $extra='') 
{
  return sprintf("href='%s%s%s'", LS_PROFILEURL_ID, $listID, $extra);
}

// -------------------------------------------------------------------------------------------------
function startsWith($haystack, $needle)
{
  $length = strlen($needle);
  return (substr($haystack, 0, $length) === $needle);
}

// -------------------------------------------------------------------------------------------------
function isContentImageStream($content, $thedb)
{
  return (startsWith($content, $thedb->escape_string("data:image/png;base64")));
}

// -------------------------------------------------------------------------------------------------
function getCurrentFileNoExt()
{
    $currentFile = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $currentFile);
    $currentFile = substr($parts[count($parts) - 1],0,-4);
    return $currentFile;
}

// -------------------------------------------------------------------------------------------------
function PleasantDate($unpleasant_date)
{
  if (intval(substr($unpleasant_date, 0, 4)) < intval(date("Y")))
  {
    $pleasant_date = date("M j Y", mktime(0, 0, 0, substr($unpleasant_date, 5, 2), substr($unpleasant_date, 8, 2), substr($unpleasant_date, 0, 4)));   
  }
  elseif (intval(substr($unpleasant_date, 0, 4)) == intval(date("Y")) && 
          intval(substr($unpleasant_date, 5, 2)) == intval(date("n")) &&
          intval(substr($unpleasant_date, 8, 2)) == intval(date("j"))) 
  {  
    $pleasant_date = date("g:ia", mktime(substr($unpleasant_date, 11, 2), substr($unpleasant_date, 14, 2), substr($unpleasant_date, 17, 2), 0, 0, 0)); $prep="at";  
  }
  else
  {  
    $pleasant_date = date("F j", mktime(0, 0, 0, substr($unpleasant_date, 5, 2), substr($unpleasant_date, 8, 2), substr($unpleasant_date, 0, 4)));      
  }
  
  return $pleasant_date;
}

// -------------------------------------------------------------------------------------------------
function Truncate($string, $length, $stopanywhere=false) 
{
  $procString = UnStarr($string);
  
  //truncates a string to a certain char length, stopping on a word if not specified otherwise.
  if (strlen($procString) > $length) 
  {
    //limit hit!
    $procString = substr($procString,0,($length -3));
    if ($stopanywhere) 
    {
      //stop anywhere
      $procString .= '...';
    } 
    else
    {
      //stop on a word.
      $procString = substr($procString, 0, strrpos($procString,' ')) . '...';
    }
  }
  
  return $procString;
}

// -------------------------------------------------------------------------------------------------
function stringBreakCallback( $matches) {
  return chunk_split($matches[1], 25, '&#8203'); // &#8203 is the magic zero-space break character in HTML
}

function StringWordBreak($str) 
{ 
  return preg_replace_callback('#(\w{25,})#', 'stringBreakCallback', $str); 
} 

function httpSplitCallback( $matches) {
  return '<a href="'. $matches[1] . '" target="_blank">' .chunk_split($matches[1], 25, '&#8203;') . '</a>';
}

// -------------------------------------------------------------------------------------------------
function MakeClickableLinks($string) 
{
  return preg_replace_callback("@(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))@", 
    'httpSplitCallback', 
    $string);
}

// -------------------------------------------------------------------------------------------------
function MakeThumbUpIcons($string)
{
  return preg_replace("/{(d|b)}/", "<img style='top: 3px; position: relative; padding-right: 0px;' src='http://www.listopia.co.uk/images/thumb-up.png' width='14' height='15'>", $string);
}

// -------------------------------------------------------------------------------------------------
// we use this on all list entries, comments, etc to ensure they are properly formatted for display:
// convert slashes 
// break up huge words
// process http links into anchors
//
function ConditionTextForDisplay($string)
{
  $procString = UnStarr($string);

  $procString = StringWordBreak(
                  MakeClickableLinks(
                    stripslashes($procString)
                    )
                );

  $procString = MakeThumbUpIcons($procString);

  return $procString;
}

// -------------------------------------------------------------------------------------------------
function ConditionCommentForDisplay($theDB, $string)
{
  $commentMsg = StringWordBreak(
            MakeClickableLinks(
              stripslashes($string)
              )
           );

    preg_match('/\$([0-9]+)\$/', $commentMsg, $matches);
    if ($matches != null)
    {
      $query = $theDB->select(array(
                                'fields' => 'list_headline',
                                'table' => 't_lists',
                                'condition' => 'list_id = '.$matches[1],
                                'limit' => 1
                                ));
      if (!empty($query[0]))
      {
        $listLinkA = sprintf("<a %s>%s</a>", ListLink($matches[1]), stripslashes($query[0]['t_lists']['list_headline']));
        $commentMsg = str_replace("$".$matches[1]."$", $listLinkA, $commentMsg);
      }
    }

    $commentMsg = MakeThumbUpIcons($commentMsg);
    $commentMsg = str_replace("{AIDS}", "<img style='top: 3px; position: relative; padding-right: 0px;' src='http://www.listopia.co.uk/images/horseaids.gif' width='16' height='16'>", $commentMsg);

    $commentMsg = preg_replace("/({-})([^{]+)({-})/", "<strike>$2</strike>", $commentMsg);

    $commentMsg = UnStarr($commentMsg);

    return $commentMsg;
}


// -------------------------------------------------------------------------------------------------
function closestKeyNumberInArray($array, $number) 
{
  foreach ($array as $key => $value)
  {
    if ($key >= $number) 
      return $value;
  }
  return end($array); // or return NULL;
}
