将书签应用程序与社交网站集成

时间:2011-10-01 12:03:35

标签: php mysql social-networking bookmarks

我有一个功能完善的书签应用程序。截至目前,它是非排他性的;当我按下“保存”书签时,它会将URL发送到DB中的通用表。我需要弄清楚如何将其与在线社区集成,因此其用户特定以及每次用户“保存”故事时,它会将URL发送到数据库中该用户的行并输出回来该用户的个人资料。

代码如下。 这是一个演示: http://demo.tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/demo.php

Bookmark.php

 <?php

 // Error reporting:
 error_reporting(E_ALL^E_NOTICE);

 require "connect.php";
 require "functions.php";

 // Setting the content-type header to javascript:
header('Content-type: application/javascript');

 // Validating the input data
if(empty($_GET['url']) || empty($_GET['title']) || !validateURL($_GET['url'])) die();

// Sanitizing the variables
$_GET['url'] = sanitize($_GET['url']);
$_GET['title'] = sanitize($_GET['title']);

// Inserting, notice the use of the hash field and the md5 function:
mysql_query("   INSERT INTO bookmark_app (hash,url,title)
            VALUES (
                '".md5($_GET['url'])."',
                '".$_GET['url']."',
                '".$_GET['title']."'
            )");

$message = '';
if(mysql_affected_rows($link)!=1)
{
$message = 'You have already saved this Headline';
}
else
$message = 'The URL was shared!';


 ?>

 /* JavaScript Code */

  function displayMessage(str)
   {
// Using pure JavaScript to create and style a div element

var d = document.createElement('div');

with(d.style)
{
    // Applying styles:

    position='fixed';
    width = '350px';
    height = '20px';
    top = '50%';
    left = '50%';
    margin = '-30px 0 0 -195px';
    backgroundColor = '#f7f7f7';
    border = '1px solid #ccc';
    color = '#777';
    padding = '20px';
    fontSize = '18px';
    fontFamily = '"Myriad Pro",Arial,Helvetica,sans-serif';
    textAlign = 'center';
    zIndex = 100000;

    textShadow = '1px 1px 0 white';

    MozBorderRadius = "12px";
    webkitBorderRadius = "12px";
    borderRadius = "12px";

    MozBoxShadow = '0 0 6px #ccc';
    webkitBoxShadow = '0 0 6px #ccc';
    boxShadow = '0 0 6px #ccc';
 }

 d.setAttribute('onclick','document.body.removeChild(this)');

   // Adding the message passed to the function as text:
 d.appendChild(document.createTextNode(str));

   // Appending the div to document
 document.body.appendChild(d);

   // The message will auto-hide in 3 seconds:

 setTimeout(function(){
    try{
        document.body.removeChild(d);
    }   catch(error){}
 },3000);
     }

   <?php 

 // Adding a line that will call the JavaScript function:
 echo 'displayMessage("'.$message.'");';

 ?>

Connect.php     

/* Database config */

$db_host        = 'xxxxx';
$db_user        = 'xxxxx';
$db_pass        = 'xxxxx';
$db_database    = 'xxxxx'; 

/* End config */


$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

mysql_set_charset('utf8');
mysql_select_db($db_database,$link);

?>

Demo.php     

// Error reporting:
error_reporting(E_ALL^E_NOTICE);

require "connect.php";
require "functions.php";

$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"]);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bookmarking App With PHP, JavaScript &amp; MySQL | Tutorialzine demo</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<h1>Bookmarking App...</h1>
<h2><a href="http://google.com">Return to the homepage &raquo;</a></h2>

<div id="main">

<div class="bookmarkHolder">

    <!--    The link contains javascript functionallity which is preserved
            when the user drops it to their bookmark/favorites bar  -->

      <a href="javascript:(function(){var jsScript=document.createElement('script');
   jsScript.setAttribute('type','text/javascript');
   jsScript.setAttribute('src', '<?php echo  $url?>/bookmark.php?url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title));
  document.getElementsByTagName('head')[0].appendChild(jsScript);
  })();" class="bookmarkButton">Bookmark this!</a>

    <em>Drag this button to your bookmarks bar and click it when visiting a web site. The title and URL of the page will be saved below.</em>
   </div>

  <ul class="latestSharesUL">
    <?php

    $shares = mysql_query("SELECT * FROM bookmark_app ORDER BY id DESC LIMIT 6");

    while($row=mysql_fetch_assoc($shares))
    {
        // Shortening the title if it is too long:
        if(mb_strlen($row['title'],'utf-8')>80)
            $row['title'] = mb_substr($row['title'],0,80,'utf-8').'..';

        // Outputting the list elements:
        echo '
        <li>
            <div class="title"><a href="'.$row['url'].'" class="bookmrk">'.$row['title'].'</a></div>
            <div class="dt">'.relativeTime($row['dt']).'</div>
        </li>';
    }

        ?>
    </ul>

 </div>

 </body>
 </html>

的functions.php      

 /* Helper functions */

 function validateURL($str)
 {
return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:\/~\+#]* [\w\-\@?^=%&amp;\/~\+#])?/i',$str);
 }

 function sanitize($str)
 {
if(ini_get('magic_quotes_gpc'))
    $str = stripslashes($str);

$str = strip_tags($str);
$str = trim($str);
$str = htmlspecialchars($str);
$str = mysql_real_escape_string($str);

return $str;
 }


 function relativeTime($dt,$precision=2)
 {
if(is_string($dt)) $dt = strtotime($dt);

$times=array(   365*24*60*60    => "year",
                30*24*60*60     => "month",
                7*24*60*60      => "week",
                24*60*60        => "day",
                60*60           => "hour",
                60              => "minute",
                1               => "second");

$passed=time()-$dt;

if($passed<5)
{
    $output='less than 5 seconds ago';
}
else
{
    $output=array();
    $exit=0;

    foreach($times as $period=>$name)
    {
        if($exit>=$precision || ($exit>0 && $period<60)) break;

        $result = floor($passed/$period);
        if($result>0)
        {
            $output[]=$result.' '.$name.($result==1?'':'s');
            $passed-=$result*$period;
            $exit++;
        }
        else if($exit>0) $exit++;
    }

    $output=implode(' and ',$output).' ago';
  }

  return $output;
  }

 // Defining fallback functions for mb_substr and 
 // mb_strlen if the mb extension is not installed:

 if(!function_exists('mb_substr'))
 {
function mb_substr($str,$start,$length,$encoding)
{
    return substr($str,$start,$length);
}
 }

 if(!function_exists('mb_strlen'))
 {
function mb_strlen($str,$encoding)
{
    return strlen($str);
}
 }
 ?>

Table.sql

CREATE TABLE `bookmark_app` (
`id` int(10) unsigned NOT NULL auto_increment,
`hash` varchar(32) collate utf8_unicode_ci NOT NULL default '',
`url` text collate utf8_unicode_ci NOT NULL,
`title` text collate utf8_unicode_ci NOT NULL,
`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY  (`id`),
UNIQUE KEY `hash` (`hash`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

0 个答案:

没有答案