<?php
/*
Plugin Name: Website Favorites
Description: Website favorites functions for allowing users to marking records as favorites or "saving" records to their profile
Version: 1.01
Requires at least: 2.53
*/

// UPDATE THESE VALUES

$GLOBALS['WSF_LOGIN_REQ_MESSAGE'] = "You must login to use this feature!";  // This is displayed if the user tries to add a favorite and isn't logged in


// DON'T UPDATE ANYTHING BELOW THIS LINE

$GLOBALS['WSF_TABLENAME'] = '_website_favorites';  // The name of the table for storing website favorites

addAction('admin_postlogin', '_wsf_createSchema',  null, 0);
addAction('viewer_postinit', '_wsf_init', 999, 0); // Set priority to 999 so this runs after websiteMembership plugin and $CURRENT_USER is already defined

//
function _wsf_init() {
  if (defined('IS_CMS_ADMIN')) { return; } // only run this from website viewers, not CMS admin pages

  // perform website login actions
  if (@$_REQUEST['_wsf_action'] == 'add') {
    wsf_addFavorite(@$_REQUEST['tableOrTag'], @$_REQUEST['recordNum']);
    exit; // this is called by ajax - only return content if there are errors
  }
  if (@$_REQUEST['_wsf_action'] == 'remove') {
    wsf_removeFavorite(@$_REQUEST['tableOrTag'], @$_REQUEST['recordNum']);
    exit; // this is called by ajax - only return content if there are errors
  }

}


//
function wsf_cssClassFor($tableOrTag, $recordNum, $action) {
  $escapedTableOrTag = escapeJs($tableOrTag);
  $escapedRecordNum  = (int) $recordNum;

  //
  $cssClass = '';
  if     ($action == 'add')    { $cssClass = "wsf_add_{$tableOrTag}_$recordNum"; }
  elseif ($action == 'remove') { $cssClass = "wsf_remove_{$tableOrTag}_$recordNum"; }

  //
  echo $cssClass;
}

//
function wsf_displayStyleFor($tableOrTag, $recordNum, $action) {
  $isFavorite = wsf_isFavorite($tableOrTag, $recordNum);

  $style = '';
  if     ($action == 'add'    && $isFavorite)  { $style = "display: none"; }
  elseif ($action == 'remove' && !$isFavorite) { $style = "display: none"; }

  echo $style;
}


//
function wsf_onClickFor($tableOrTag, $recordNum, $action) {
  $escapedTableOrTag = escapeJs($tableOrTag);
  $escapedRecordNum  = (int) $recordNum;

  //
  $onClick = '';
  if     ($action == 'add')             { $onClick = "wsf_add('$escapedTableOrTag','$escapedRecordNum'); return false;"; }
  elseif ($action == 'addAndReload')    { $onClick = "wsf_add('$escapedTableOrTag','$escapedRecordNum', true); return false;"; }
  elseif ($action == 'remove')          { $onClick = "wsf_remove('$escapedTableOrTag','$escapedRecordNum'); return false;"; }
  elseif ($action == 'removeAndReload') { $onClick = "wsf_remove('$escapedTableOrTag','$escapedRecordNum', true); return false;"; }
  else                                  { $onClick = "alert('Unknown action specified! Must be add, remove, or removeAndReload!'); return false;"; }

  // override onclick with error messages (if any)
  if (!$GLOBALS['CURRENT_USER'])        { $onClick = "alert('" .escapeJs($GLOBALS['WSF_LOGIN_REQ_MESSAGE']). "'); return false;"; }
  if (!@$GLOBALS['WSF_SCRIPTS_LOADED']) { $onClick = "alert('Website Favorites Error: You must add the javascript files to the header!'); return false;"; }

  //
  echo $onClick;
}

//
function wsf_isFavorite($tableOrTag, $recordNum) {
  global $CURRENT_USER;
  if (!@$CURRENT_USER) { return false; }

  // Future Idea: Add caching here and load all favorites by createdByUserNum at same time

  //
  $where  = "createdByUserNum = '" .mysql_real_escape_string($CURRENT_USER['num']). "' AND\n";
  $where .= "tableOrTag       = '" .mysql_real_escape_string($tableOrTag). "' AND\n";
  $where .= "recordNum        = '" .mysql_real_escape_string($recordNum). "'\n";
  $count = mysql_count($GLOBALS['WSF_TABLENAME'], $where);
  return (bool) $count;

}


// returns true on success, false if already a favorite, and dies on mysql errors
function wsf_addFavorite($tableOrTag, $recordNum) {
  global $CURRENT_USER;
  if (!@$CURRENT_USER) { die($GLOBALS['WSF_LOGIN_REQ_MESSAGE']); }

  //
  if (function_exists('wsf_addFavorite_callback')) {
    $ok = wsf_addFavorite_callback($tableOrTag, $recordNum);
    if (!$ok) { return; }
  }

  // skip if already favorite
  $exists = wsf_isFavorite($tableOrTag, $recordNum);
  if ($exists) { return false; }

  // add favorite
  $query  = "INSERT INTO `" .getTableNameWithPrefix($GLOBALS['WSF_TABLENAME']). "` SET\n";
  $query .= "createdByUserNum = '" .mysql_real_escape_string($CURRENT_USER['num']). "',\n";
  $query .= "tableOrTag       = '" .mysql_real_escape_string($tableOrTag). "',\n";
  $query .= "recordNum        = '" .mysql_real_escape_string($recordNum). "'\n";
  mysql_query($query) or dieAsCaller('MySQL Error: '. htmlencode(mysql_error()) . "\n", 0);
  return true;
}


//
function wsf_removeFavorite($tableOrTag, $recordNum) {
  global $CURRENT_USER;
  if (!@$CURRENT_USER) { die($GLOBALS['WSF_LOGIN_REQ_MESSAGE']); }

  // remove favorite
  $query  = "DELETE FROM `" .getTableNameWithPrefix($GLOBALS['WSF_TABLENAME']). "` WHERE\n";
  $query .= "createdByUserNum = '" .mysql_real_escape_string($CURRENT_USER['num']). "' AND\n";
  $query .= "tableOrTag       = '" .mysql_real_escape_string($tableOrTag). "' AND\n";
  $query .= "recordNum        = '" .mysql_real_escape_string($recordNum). "'\n";
  mysql_query($query) or dieAsCaller('MySQL Error: '. htmlencode(mysql_error()) . "\n", 0);
}

//
function _wsf_createSchema() {
  //
  $schemaDir  = realpath(DATA_DIR . '/schema');
  $schemaPath = "$schemaDir/{$GLOBALS['WSF_TABLENAME']}.ini.php";
  if (file_exists($schemaPath)) { return; }

  // create schema
  $schema = array(
    'menuName'             => 'Website Favorites',
    'menuType'             => 'multi',
    'menuOrder'            => time(),
    'listPageFields'       => 'createdBy.username, tableOrTag, recordNum',
    'listPageOrder'        => '',
    'listPageSearchFields' => '',
    '_disableAdd'          => 1,
    '_disableErase'        => 1,
    '_disableModify'       => 1,
    'menuHidden'           => 1,

    'createdByUserNum' => array('order'            => '1',
                                'type'             => 'textfield',
                                'label'            => 'User Num',
                                'isSystemField'    => '1',
                                'customColumnType' => 'INT NOT NULL' ),

    'tableOrTag'       => array('order'            => '2',
                                'type'             => 'textfield',
                                'label'            => 'Table Or Tag',
                                'isSystemField'    => '1',
                                'customColumnType' => 'VARCHAR(255) NOT NULL' ),

    'recordNum'        => array('order'            => '3',
                                'type'             => 'textfield',
                                'label'            => 'Record Num',
                                'isSystemField'    => '1',
                                'customColumnType' => 'INT NOT NULL' ),
  );

  //
  saveSchema($GLOBALS['WSF_TABLENAME'], $schema);
  notice("Created new '{$schema['menuName']}' section<br/>\n");
  createMissingSchemaTablesAndFields();

  // drop num field
  @mysql_query("ALTER TABLE `{$GLOBALS['TABLE_PREFIX']}{$GLOBALS['WSF_TABLENAME']}` DROP COLUMN `num`"); // or die('MySQL Error: '. htmlencode(mysql_error()) . "\n");

}

// eof