<?php 
require("common_begin.php");

$itemID = $_GET['id'];
if (!isset($itemID))
  die("no item ID set");

$elementID = $_POST['id'];
$newContent = $_POST['value'];
if (!isset($elementID) || !isset($newContent))
  die("editable components not sent");

$lst = Listopia::getInstance();

if ($lst->isLoggedIn())
{
  if ($lst->isUserOnProbation())
  {
    die($newContent);
  }

  $query = $lst->Database()->select(array(
                      'fields' => 't_items.item_createdby, t_items.item_created, t_items.item_extra, t_items.item_blurb, t_lists.list_maxchars',
                      'table' => 't_items',
                      'join' => 't_lists on t_lists.list_id = t_items.item_list',
                      'condition' => 't_items.item_id = ' . ((int)$itemID),
                      'limit' => 1
                      ));
  // ensure this is OUR item we're trying to edit
  if (!empty($query[0]))
  {
    $newContent = trim($newContent);
    
    // check the new message fits inside the list limits, and isn't empty
    $contentSize = strlen(stripslashes(htmlspecialchars_decode($newContent)));
    if ($contentSize < 2)
    {
      echo ConditionTextForDisplay($query[0]['t_items']['item_blurb']);
    }
    else if ($contentSize > $query[0]['t_lists']['list_maxchars'] && 
             $query[0]['t_items']['item_extra'] != 'image')
    {
      echo "[ERROR: new post too large!] " . ConditionTextForDisplay($newContent);
    }
    else
    {
      $madeByMe = $query[0]['t_items']['item_createdby'] == Session::getInstance()->gl_userid;
      
      // double check the time / permissions / etc
      $entryCreatedUnix = strtotime($query[0]['t_items']['item_created']);
      if (($madeByMe && $entryCreatedUnix > strtotime(LS_GRACE_PERIOD)) || $lst->isAdminUser())
      {
        $newContent = htmlspecialchars($newContent);
      
        // post the modification
        $data = array(
          'item_blurb'    => $newContent
        );
        $ok = $lst->Database()->update('t_items', $data, 't_items.item_id = ' . ((int)$itemID) );
        
        if ($ok !== false)
        {
          echo ConditionTextForDisplay($newContent);
        }
        else
        {
          echo "[update failed]";
        }
      }
      else
      {
        echo "[access denied]";
      }
    }
  }
  else
  {
    echo "[not your item]";
  }
}
else
{
  echo "[not logged in]";
}

require("common_end.php");

