Jul 03 2009

LinkIt Link Manager Wordpress Plugin

Category: PHP, WordPress Pluginszach @ 3:22 am

I found myself inserting links all over the place on my blogs – many of them were the same link. And many of the links I knew I wanted to use but didn’t have the actual address at the time I was writing. So rather than typing out the html for a link everytime and then going back to update, I wrote the LinkIt plugin. As you edit a post or a page, you can just type in a string that’s easy to recognize from a regular expression. For example [MyLink]. Then in the LinkIt options add an entry for /\[MyLink\]/, set the link and display name, and presto! All the occurrences of [MyLink] in the content are replaced with the link.

The code for this plugin is really simple, here’s the 2 files:

Open Unformatted Code In New Window

<?php
/*  Copyright 2009  R-Link Research and Consulting, Inc.  (email : zach@rlinkconsulting.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
/*
Plugin Name: LinkIt
Plugin URI: http://www.codezach.com
Description: Auto-insert links into posts via associative text.
Version: 0.1
Author: R-Link Research and Consulting, Inc.
Author URI: http://www.rlinkconsulting.com
*/

//**************************************************************
// Globals
//**************************************************************
global $linkit_pluginroot, $linkit_curLink;

$linkit_rootdir = dirname(dirname(dirname(dirname(__FILE__))));
$linkit_pluginroot = dirname(__FILE__);
$linkit_webdir = '/wp-content/plugins/' . basename($linkit_pluginroot);

//**************************************************************
// Options
//**************************************************************

//--------------------------------------------------------------
// Get link array
//--------------------------------------------------------------
function rlink_linkit_links_array()
{
	global $wpdb;
	
	$sql = 'select * from rlink_linkit_links;';
	
	$ret = $wpdb->get_results($sql);
	
	return $ret;
}

//**************************************************************
// Includes
//**************************************************************
$include = $linkit_pluginroot . '/options.php';
require_once $include;

//**************************************************************
// Initialize
//**************************************************************

register_activation_hook(__FILE__,'rlink_linkit_install');
register_deactivation_hook(__FILE__,'rlink_linkit_uninstall');


add_action('wp_head', 'rlink_linkit_do_head');
add_filter('the_content', 'rlink_linkit_do_content');

//**************************************************************
// Execute
//**************************************************************

//--------------------------------------------------------------
// Install
//--------------------------------------------------------------
function rlink_linkit_install()
{	
	global $wpdb;
	
	$tableName = "rlink_linkit_links";
	
	if($wpdb->get_var("show tables like '$tableName'") != $tableName) 
	{ 
		$sql = 
			"CREATE TABLE `rlink_linkit_links` (
				`id` int(11) NOT NULL auto_increment,
	  			`displayName` varchar(256) default NULL,
	  			`regex` varchar(256) default NULL,
				`target` varchar(32) default NULL,
				`link` varchar(1024) default NULL,
				`linkTemplate` varchar(512) default NULL,
				PRIMARY KEY  (`id`)
				) ENGINE=MyISAM DEFAULT CHARSET=utf8;";

	      require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	      dbDelta($sql);
	      
	      add_option("rlink_linkit_db_version", "1.0");
	}
}

//--------------------------------------------------------------
// Uninstall
//--------------------------------------------------------------
function rlink_linkit_uninstall()
{	
}

//--------------------------------------------------------------
// Header
//--------------------------------------------------------------
function rlink_linkit_do_head()
{
}


//--------------------------------------------------------------
// Content
//--------------------------------------------------------------
function rlink_linkit_do_content($content)
{
	global $linkit_curLink, $linkit_pluginroot, $linkit_webdir;
	
	$links = rlink_linkit_links_array();
	
	$ret = $content;
	
	foreach($links as $link)
	{
		$linkit_curLink = $link;
		
		$ret = preg_replace_callback($link->regex, "rlink_linkit_cb", $ret);
	}
	
	return $ret;
}

//--------------------------------------------------------------
// Content Callback
//--------------------------------------------------------------
function rlink_linkit_cb($matches)
{
	global $linkit_rootdir, $linkit_curLink;
	
	$link = $linkit_curLink;
	
	$ret = str_replace('%target%', $link->target, $link->linkTemplate);
	
	$ret = str_replace('%link%', $link->link, $ret);
	
	$ret = str_replace('%displayName%', $link->displayName, $ret);
	
	return $ret;
}


?>

Options

Open Unformatted Code In New Window

<?php

$linkit_modes = array(
	'save' => 'Save', 
	'add' => 'Add New Link', 
	'edit' => 'Edit', 
	'delete' => 'Delete',
	'discard' => 'Discard');

add_action('admin_menu', 'rlink_linkit_menu');

function rlink_linkit_home_link($title = null)
{
	if(isset($title) != true)
	{
		$title = 'Continue &gt;&gt;';
	}
	
	$url = $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'];
	
	echo '<a href="' . $url . '">' . $title . '</a>';
}

function normalizeREQUEST()
{
	foreach($_REQUEST as $key => $val)
	{
		$_REQUEST[$key] = stripslashes($val);
	}
}

function rlink_linkit_div_msg($msg)
{
	echo '<div style="padding:5px;border:1px solid black;margin:50px;background-color:#FFFF88;width:80%;text-align:center;font-size:16pt;font-weight:bold;">';
	echo $msg;
	echo '</div>';
	
	echo '<div style="width:80%;margin:0 auto;text-align:left;"><h3>';
	rlink_linkit_home_link();
	echo '</h3></div>';
}

function rlink_linkit_menu() 
{
  add_options_page('LinkIt Options', 'LinkIt Options', 8, __FILE__, 'rlink_linkit_options');
}

function rlink_linkit_save()
{
	global $linkit_modes, $wpdb;
	
	$id = $_REQUEST['id'];
	$regex = $_REQUEST['regex'];
	$displayName = $_REQUEST['displayName'];
	$target = $_REQUEST['target'];
	$link = $_REQUEST['link'];
	$template = $_REQUEST['template'];

	if(isset($id) && strlen($id) > 0)
	{
		$sql = 
			'update rlink_linkit_links ' .
			"set regex=%s, displayName=%s, target=%s, link=%s, linkTemplate=%s where id=%s;";
		
		$sql = $wpdb->prepare($sql, $regex, $displayName, $target, $link, $template, $id);
	}
	else
	{
		$sql = 
			'insert into rlink_linkit_links (regex,displayName,target,link,linkTemplate) ' .
			"values(%s, %s, %s, %s, %s);";
		
		$sql = $wpdb->prepare($sql, $regex, $displayName, $target, $link, $template);
	}
	
	$err = $wpdb->query($sql);
	
	rlink_linkit_div_msg('Saved!');
}

function rlink_linkit_edit($new)
{
	global $linkit_modes, $wpdb;
	
	if($new == false)
	{
		$id = $_REQUEST['id'];
	}
	
	$link->regex = '/\[My Link\]/';
	$link->displayName = 'My Link';
	$link->target = '_blank';
	$link->link = 'http://www.google.com';
	$link->linkTemplate = '<a target="%target%" href="%link%">%displayName%</a>';
	
	if($new == false)
	{
		$sql = "select * from rlink_linkit_links where id='" . $id . "';";
		
		$wpdb->escape($sql);
		
		$link = $wpdb->get_row($sql);
	}
	
	htmlentities($link->linkTemplate);
	
	if($new == true)
	{
?>
<h1>Add New Link</h1>
<hr />
<?php 
	}
	else
	{
?>
<h1>Edit Link</h1>
<hr />
<?php 
	}
?>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<table>
<tr>
<td>Regular Expression</td>
<td><input name="regex" type="text" value="<?php echo $link->regex; ?>"/></td>
</tr>

<tr>
<td>Link Display Name</td>
<td><input name="displayName" type="text" value="<?php echo $link->displayName; ?>"/></td>
</tr>

<tr>
<td>Target</td>
<td>
<select name="target" id="themeSelect">
<?php 
$options = array('_self', '_blank', '_parent', '_new');

foreach($options as $opt)
{
	$sel = '';
	
	if($opt == $link->target)
	{
		$sel = 'selected';
	}
	
	echo '<option ' . $sel . '>' . $opt . '</option>';
}
?>
</select>
</td>

<tr>
<td>Link</td>
<td><input name="link" type="text" style="width:100%" value="<?php echo $link->link; ?>"/></td>
</tr>

<tr>
<td>Link Template</td>
<td><textarea name="template" rows="5" cols="80"><?php echo $link->linkTemplate; ?></textarea></td>
</tr>

<tr>
<td>
</td>
<td>
<table>
<tr><td><input name="mode" type="submit" value="<?php echo $linkit_modes['save']; ?>"/></td>
<td>&nbsp;&nbsp;<?php rlink_linkit_home_link('Discard Changes'); ?></td></tr>
</table>
</td>
</tr>

</table>

</form>
<?php 
}

function rlink_linkit_delete()
{
	global $wpdb;
	
	$id = $_REQUEST['id'];
	
	$sql = 'delete from rlink_linkit_links where id=%d';
	
	$sql = $wpdb->prepare($sql, $id);
	
	$msg = 'Deleted Link (id=' . $id . ')';
	
	$success = $wpdb->query($sql);
	
	if($success === false)
	{
		$msg = 'Delete failed with a database error.';
	}
	
	rlink_linkit_div_msg($msg);
}

function rlink_linkit_list()
{
	global $linkit_modes, $wpdb;
	
	$links = $wpdb->get_results("select * from rlink_linkit_links;");
	
?>
<script type="text/javascript">

function confirmDelete()
{
	var ret = confirm("Delete this link?");

	return ret;
}
</script>
<?php 

	echo '<table>';
	echo '<tr><td colspan="9">';
	
?>
<h1>LinkIt Links</h1>
<hr />
<p style="width:60%;">
Click the "Add" button below to get started. Each regular expression will be used to insert links into
the content of posts and pages. The display name, link, target, and template come together to allow 
precise control over the final link display.
</p>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input name="mode" type="submit" value="<?php echo $linkit_modes['add']; ?>" />
</form>
<?php 
	
	echo '</td></tr><tr><td>';
	
	if(count($links) > 0)
	{
		echo '<table cellspacing="10px" style="border:1px solid black;background-color:#EEEEEE;margin:0px;"><tr><th>Regex</th><th>Display Name</th><th>Link</th></tr>';
		
		foreach($links as $link)
		{
			echo 
				'<tr><td>' . 
				$link->regex . 
				'</td><td>' . 
				$link->displayName . 
				'</td><td>' .
				$link->link .
				'</td><td>' .
				'<a href="' . $_SERVER['REQUEST_URI'] . '&mode=' . $linkit_modes['edit'] . '&id=' . $link->id . '">Edit</a>' .
				'</td><td>' .
				'<a href="' . $_SERVER['REQUEST_URI'] . '&mode=' . $linkit_modes['delete'] . '&id=' . $link->id . '" onclick="return confirmDelete()">Delete</a>' .
				'</td></tr>';
		}
		
		echo '</table>';
	}
	
	echo '</td></tr></table>';
}

function rlink_linkit_options() 
{
	global $upcomingEvents_pluginroot, $wpdb, $linkit_modes;
	
	normalizeREQUEST();
	
	$mode = $_REQUEST['mode'];
	
	if($mode == $linkit_modes['edit'])
	{
		rlink_linkit_edit(false);
	}
	else if($mode == $linkit_modes['add'])
	{
		rlink_linkit_edit(true);
	}
	else if($mode == $linkit_modes['save'])
	{
		rlink_linkit_save();
	}
	else if($mode == $linkit_modes['delete'])
	{
		rlink_linkit_delete();
	}
	else 
	{
		rlink_linkit_list();
	}
}

?>

Bookmark and Share

8 Responses to “LinkIt Link Manager Wordpress Plugin”

  1. Carrie says:

    I think your plugin is just what I’m looking for – except it’s giving me this error on 2.8.4:

    Warning: preg_replace_callback() [function.preg-replace-callback]: Delimiter must not be alphanumeric or backslash in /home/circa31/public_html/wp-content/plugins/linkit-link-manager/main.php on line 134

  2. admin says:

    Thanks for the feedback. I am slammed with other projects + I’m in Siberia at the moment, but because you were cool enough to actually comment on the thing I’ll check it out tomorrow and update soon. Can you give some info though:

    1) Did this error occur as soon as it was installed or after you added some links?
    2) If you added some links, can you send me the regex’s you used?

    Cheers,

    Zach

  3. Carrie says:

    Zach, the error occured as soon as I activated. It actually replaced the text in ALL my posts with that error message.

  4. admin says:

    Great, thanks for the info. I think I’ve tracked this down to a magic_quotes problem (www.php.net/magic_quotes) – PHP has some really bad “features” like magic_quotes (it’s FINALLY been removed in PHP6…). I added a regex tester and some other features to the plugin but I still need to finish testing before I update for you to download. I’ll keep ya posted…

  5. Carrie says:

    Awesome, thanks. If you get it working, I’ll be spreading the word to several other bloggers that want a plugin like this!

  6. Carrie says:

    Any update on this plugin? I’m dying to start using it!

  7. Terry says:

    I am very interested in this plugin and am curious if there’s any more documentation on how to implement it.

  8. Terry says:

    Five minutes of tinkering and I think I figured it out. Can I just say how amazing this plugin is! And where can I send you a few dollars for making life easier.

    Now if only I can find a plugin that will list all existing links currently in use throughout all my posts.

Leave a Reply