<?php

/*
 * Plugin Name: Webshare-API
 * Version: 1.0.0
 * Plugin URI: https://www.flatpress.org
 * Author: Freankiman
 * Author URI: https://frank-web.dedyn.io
 * Description: Adds webshare button in single posts using the [webshare] tag. <a href="./fp-plugins/webshare/doc_webshare.txt" title="Instructions" target="_blank">[Instructions]</a>
 * 
 * License: share-api-polyfill is licensed under the MIT License
 * https://github.com/on2-dev/share-api-polyfill
 */


function plugin_webshare_head() { // webshare-api
	global $smarty;
	$smarty->display('plugin:webshare/plugin.webshare');
}

function plugin_webshare_main($string) {
	global $fp_params;

	$MODE = 'manual'; // using $MODE = 'manual'

	$CHOP_AT = 8; // characters or sentences

	$lang = lang_load('plugin:webshare');
	$webshareString = $lang ['plugin'] ['webshare'] ['share'];

	global $fpdb;
	$q = & $fpdb->getQuery();

	if (($q && !$q->single) && !isset($_GET ['page'])) {
		if ($q)
			list ($id) = $q->getLastEntry();
		else
			$id = '';

		if ($MODE == 'auto' || $MODE == 'semiauto') {
			if (strlen($string) > $CHOP_AT) {
				return substr($string, 0, $CHOP_AT) . "<div><p><input href=\"javascript:void(0);\" type=\"button\" value=\"" . $webshareString . "\" class=\"the-share-button\" onclick=\"shareTheLink()\"></p></div>";
			}
		}

		if ($MODE == 'manual' || $MODE == 'semiauto') {
			if (($p = strpos($string, '[webshare]')) !== false) {
				return substr($string, 0, $p) . "<div><p><input href=\"javascript:void(0);\" type=\"button\" value=\"" . $webshareString . "\" class=\"the-share-button\" onclick=\"shareTheLink()\"></p></div>";
			}
		} elseif ($MODE == 'sentence') {
			$matches = array();
			if ($v = preg_match_all('|[.!?]\s|', $string, $matches, PREG_OFFSET_CAPTURE)) {
				if (count($matches [0]) > $CHOP_AT) {
					$string = substr($string, 0, $matches [0] [$CHOP_AT - 1] [1]);
				}
			}
		}
	}

	if (($q && $q->single) || isset($fp_params ['entry'])) {
		$string = str_replace('[webshare]', "<div><p><input href=\"javascript:void(0);\" type=\"button\" value=\"" . $webshareString . "\" class=\"the-share-button\" onclick=\"shareTheLink()\"></p></div>", $string);
	}

	return $string;
}

add_action('wp_head', 'plugin_webshare_head'); // webshare-api
add_filter('the_content', 'plugin_webshare_main', 10); // webshare-tag

?>
