From 339a92fe1b7a0ed2b528a7c91c08c8b3ad5f96f6 Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Sun, 6 Feb 2011 17:22:15 +0100 Subject: [PATCH 01/36] added Slinky library by Beau Lebens for shortening the post url --- addon/twitter/slinky.php | 704 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 704 insertions(+) create mode 100644 addon/twitter/slinky.php diff --git a/addon/twitter/slinky.php b/addon/twitter/slinky.php new file mode 100644 index 00000000..51432c3f --- /dev/null +++ b/addon/twitter/slinky.php @@ -0,0 +1,704 @@ +url_get() and ->url_post() +define( 'SLINKY_BODY', 1 ); // Default +define( 'SLINKY_HEADERS', 2 ); // Not implemented yet +define( 'SLINKY_FINAL_URL', 3 ); // Default for lengthening URLs + +// So that services may decide what to do with us +define( 'SLINKY_USER_AGENT', 'Slinky v1.0 +http://dentedreality.com.au/projects/slinky/' ); + +// How many seconds until remote requests should be cut? +define( 'SLINKY_TIMEOUT', 10 ); + +/** + * Slinky allows you to go back and forth between "long" and shortened URLs + * using popular URL shortening services. + * + * Slinky assumes you have cURL installed and working, and requires the JSON + * extension installed if you're working with a service that uses JSON. + * + * Slinky will ONLY work with PHP5+ + * + * It supports some of the more popular services, with easy extensibility for + * adding your own relatively easily. It defaults to using TinyURL + * for shortening URLs. If you want to use some of the other services, you need + * to set some configuration options before actually shortening/lengthening + * URLs. I'd strongly suggest that you cache results using memcached, a local + * DB or whatever to avoid having to hit APIs etc every time you encounter a + * URL. + * + * Slinky supports shortening, and auto-detection (for lengthening URLs) + * using these services: + * - Bit.ly + * - Tr.im + * - TinyURL + * - Is.Gd + * - Fon.gs + * - Micurl.com + * - ur1.ca + * - Ptiturl + * - Tighturl + * - 2tu.us + * - Snipr / Snipurl / Snurl.com / Sn.im + * + * + * To use Slinky: + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * - Creates a new Slinky instance, will default to using TinyURL for ->short(); + * + * $slinky = new Slinky( 'http://dentedreality.com.au', new Slinky_Bitly() ); + * - Creates new Slinky, forces use of Bit.ly for ->short(); + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * echo $slinky->short(); + * - echos the short version of http://dentedreality.com.au/ (default to TinyURL) + * + * $slinky = new Slinky( 'http://tinyurl.com/jw5sh' ); + * echo $slinky->long(); + * - echos out the long version of http://tinyurl.com/jw5sh (which should be http://dentedreality.com.au/) + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * echo $slinky->long(); + * - Attempts to lengthen the URL, but will not auto-detect which service it is + * so it will just output the original URL. Useful for always attempting to + * lengthen any URL you come across (fails gracefully) + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * $slinky->set_cascade( array( new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) ); + * echo $slinky->short(); + * - Uses the powerful cascade mode to make sure that we get a short URL from + * Tr.im, Is.Gd or TinyURL (in that order). + * + * See specific service class definitions below for examples of how to use them, + * as some services allow (or require) additional properties before you can use + * them (for authentication etc). + * + * To use a different service with Slinky, just create your own class and + * extend Slinky_Service(). Make sure you implement url_is_short(), url_is_long(), + * make_short() and make_long(). If you need to GET or POST a URL, you can use + * ->url_get() and ->url_post(), which your class will have inherited. +**/ +class Slinky { + var $url = false; + var $service = false; + var $cascade = false; + + function __construct( $url = false, $service = false ) { + $this->url = $url; + $this->service = $service; + } + + /** + * Specify which URL Service to use + * + * @param Slinky_Service $service Packaged or custom Service object + * @return void + */ + public function set_service( $service = false ) { + if ( is_object( $service ) ) { + $this->service = $service; + } + } + + /** + * If you pass an array of Slinky_Service objects to this method, they will + * be used in order to try to get a short URL, so if one fails, it will + * try the next and so on, until it gets a valid short URL, or it runs + * out of options. + * + * @param array $services List of Slinky_Service objects as an array + **/ + public function set_cascade( $services = false ) { + if ( !$services || !is_array( $services ) ) + return false; + + $this->cascade = $services; + } + + /** + * Guess the URL service to use from known domains of short URLs + * + * @param string $url + */ + public function set_service_from_url( $url = false ) { + if ( !$url ) + $url = $this->url; + + $host = parse_url( $url, PHP_URL_HOST ); + switch ( str_replace( 'www.', '', $host ) ) { + case 'bit.ly': + if ( class_exists( 'Slinky_Bitly' ) ) { + $this->service = new Slinky_Bitly(); + break; + } + case 'tr.im': + if ( class_exists( 'Slinky_Trim' ) ) { + $this->service = new Slinky_Trim(); + break; + } + case 'tinyurl.com': + if ( class_exists( 'Slinky_TinyURL' ) ) { + $this->service = new Slinky_TinyURL(); + break; + } + case 'is.gd': + if ( class_exists( 'Slinky_IsGd' ) ) { + $this->service = new Slinky_IsGd(); + break; + } + case 'fon.gs': + if ( class_exists( 'Slinky_Fongs' ) ) { + $this->service = new Slinky_Fongs(); + break; + } + case 'micurl.com': + if ( class_exists( 'Slinky_Micurl' ) ) { + $this->service = new Slinky_Micurl(); + break; + } + case 'ur1.ca': + if ( class_exists( 'Slinky_Ur1ca' ) ) { + $this->service = new Slinky_Ur1ca(); + break; + } + case 'ptiturl.com': + if ( class_exists( 'Slinky_PtitURL' ) ) { + $this->service = new Slinky_PtitURL(); + break; + } + case 'tighturl.com': + case '2tu.us': + if ( class_exists( 'Slinky_TightURL' ) ) { + $this->service = new Slinky_TightURL(); + break; + } + case 'snipr.com': + case 'snipurl.com': + case 'snurl.com': + case 'sn.im': + if ( class_exists( 'Slinky_Snipr' ) ) { + $this->service = new Slinky_Snipr(); + break; + } + default: + $this->service = new Slinky_Default(); + break; + } + } + + /** + * Take a long URL and make it short. Will avoid "re-shortening" a URL if it + * already seems to be short. + * + * @param string $url Optional URL to shorten, otherwise use $this->url + * @return The short version of the URL + */ + public function short( $url = false ) { + if ( $url ) + $this->url = $url; + + if ( !$this->service ) + $this->set_service( new Slinky_TinyURL() ); // Defaults to tinyurl because it doesn't require any configuration + + if ( !$this->cascade ) + $this->cascade = array( $this->service ); // Use a single service in cascade mode + + foreach ( $this->cascade as $service ) { + if ( $service->url_is_short( $this->url ) ) + return trim( $this->url ); // Identified as already short, using this service + + $response = trim( $service->make_short( $this->url ) ); + if ( $response && $this->url != $response ) + return trim( $response ); + } + + return $this->url; // If all else fails, just send back the URL we already know about + } + + /** + * Take a short URL and make it long ("resolve" it). + * + * @param string $url The short URL + * @return A long URL + */ + public function long( $url = false ) { + if ( $url ) + $this->url = $url; + + if ( !$this->service ) + $this->set_service_from_url(); + + if ( $this->service->url_is_long( $this->url ) ) + return trim( $this->url ); + + return trim( $this->service->make_long( $this->url ) ); + } +} + +/** + * Use this class to create a Service implementation for your own URL + * shortening service. Extend the class and customize methods to suit your + * service. Note that it is an "abstract" class, so there are certain methods + * which you *must* define. +**/ +abstract class Slinky_Service { + + /** + * Determine, based on the input URL, if it's already a short URL, from + * this particular service. e.g. a Bit.ly URL contains "bit.ly/" + **/ + abstract function url_is_short( $url ); + + /** + * Determine if this is a "long" URL (just means it hasn't been shortened) + * already. e.g. a no-Bit.ly URL would NOT contain "bit.ly/" + **/ + abstract function url_is_long( $url ); + + /** + * Handle taking the $url and converting it to a short URL via whatever + * means is provided at the remote service. + **/ + abstract function make_short( $url ); + + /** + * Return the long/expanded version of a URL via any API means available + * from this service. As a fallback, you might + * consider just following the URL and using SLINKY_FINAL_URL as the + * return method from a $this->url_get() call to find out. + * + * This one is optional for Services extending this class, if they don't + * then the following implementation will work on most services anyway. + **/ + public function make_long( $url ) { + return $this->url_get( $url, SLINKY_FINAL_URL ); + } + + /** + * Method for getting properties that you might need during the process + * of shortening/lengthening a URL (e.g. auth credentials) + **/ + public function get( $prop ) { + if ( empty( $this->$prop ) ) + return null; + + return $this->$prop; + } + + /** + * Method for setting properties that you might need during the process + * of shortening/lengthening a URL (e.g. auth credentials) + **/ + public function set( $prop, $val ) { + $this->$prop = $val; + } + + /** + * Internal helper for performing a GET request on a remote URL. + * + * @param string $url The URL to GET + * @param const $return The return method [ SLINKY_BODY | SLINKY_FINAL_URL | SLINKY_HEADERS ] + * @return Mixed, based on the $return var passed in. + **/ + protected function url_get( $url, $return = SLINKY_BODY ) { + $ch = curl_init( $url ); + curl_setopt( $ch, CURLOPT_USERAGENT, SLINKY_USER_AGENT ); + curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // Don't stress about SSL validity + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // Return the response, don't output it + curl_setopt( $ch, CURLOPT_TIMEOUT, SLINKY_TIMEOUT ); // Limit how long we'll wait for a response + curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); // Allow following of redirections + $r = curl_exec( $ch ); + if ( curl_errno( $ch ) ) { + return false; + } + + // Return whatever we were asked for + if ( SLINKY_FINAL_URL == $return ) + return curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL ); + else if ( SLINKY_BODY == $return ) + return $r; + + return false; + } + + /** + * Internal helper for performing a POST request on a remote URL. + * + * @param string $url The URL to POST to + * @param array $payload Array containing name/value pairs of the parameters to POST + * @param const $return The return method [ SLINKY_BODY | SLINKY_FINAL_URL | SLINKY_HEADERS ] + * @return Mixed, based on the $return var passed in. + **/ + protected function url_post( $url, $payload = array(), $return = SLINKY_BODY ) { + $ch = curl_init( $url ); + curl_setopt( $ch, CURLOPT_POST, true ); + curl_setopt( $ch, CURLOPT_POSTFIELDS, (array) $payload ); + curl_setopt( $ch, CURLOPT_USERAGENT, SLINKY_USER_AGENT ); + curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // Don't stress about SSL validity + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // Return the response, don't output it + curl_setopt( $ch, CURLOPT_TIMEOUT, SLINKY_TIMEOUT ); // Limit how long we'll wait for a response + curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); // Allow following of redirections + $r = curl_exec( $ch ); + if ( curl_errno( $ch ) ) { + return false; + } + + // Return whatever we were asked for + if ( SLINKY_FINAL_URL == $return ) + return curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL ); + else if ( SLINKY_BODY == $return ) + return $r; + + return false; + } +} + +// This default service is used in cases when you try to do something based +// on auto-detection, but we can't detect anything. It will also resolve URLs +// to their "long" version by following all redirects. +class Slinky_Default extends Slinky_Service { + function url_is_short( $url ) { + return false; + } + + function url_is_long( $url ) { + return false; + } + + function make_short( $url ) { + return $url; + } +} + +// Implementation of TinyURL as a Slinky Service +class Slinky_TinyURL extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'tinyurl.com/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'tinyurl.com/' ); + } + + function make_short( $url ) { + return $this->url_get( 'http://tinyurl.com/api-create.php?url=' . urlencode( $url ) ); + } + + function make_long( $url ) { + $bits = parse_url( $url ); + $result = $this->url_get( 'http://tinyurl.com/preview.php?num=' . substr( $bits['path'], 1 ) ); + if ( preg_match('//is', $result, $matches ) ) + return $matches[1]; + else + return $url; + } +} + +// Implementation of Bit.ly as a Slinky Service +/* +To use Bit.ly, you MUST set your login and apiKey for the service first, e.g. + +$bitly = new Slinky_Bitly(); +$bitly->set( 'login', 'bitly_login' ); +$bitly->set( 'apiKey', 'bitly_apiKey' ); + +$slinky = new Slinky( $url, $bitly ); +echo $slinky->short(); + +You could also do this if the URL was already a bit.ly URL and you +were going to make it longer, since Bitly is supported for auto-detection: + +$slinky = new Slinky( $url ); +$slinky->set_service_from_url(); +$slinky->service->set( 'login', 'bitly_login' ); +$slinky->service->set( 'apiKey', 'bitly_apiKey' ); +echo $slinky->long(); + +*/ +class Slinky_Bitly extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'bit.ly/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'bit.ly/' ); + } + + function make_short( $url ) { + // Can't do anything unless these 2 properties are set first + if ( !$this->get( 'login' ) || !$this->get( 'apiKey' ) ) + return $url; + + $result = $this->url_post( 'http://api.bit.ly/shorten?version=2.0.1&format=json&login=' . $this->get( 'login' ) . '&apiKey=' . $this->get( 'apiKey' ) . '&longUrl=' . urlencode( $url ) ); + $result = json_decode( $result ); + if ( !$result->errorCode ) { + foreach ( $result->results as $detail ) { + return $detail->shortUrl; + } + } else { + return false; + } + } + + function make_long( $url ) { + // Can't do anything unless these 2 properties are set first + if ( !$this->get( 'login' ) || !$this->get( 'apiKey' ) ) + return $url; + + $result = $this->url_post( 'http://api.bit.ly/expand?version=2.0.1&format=json&login=' . $this->get( 'login' ) . '&apiKey=' . $this->get( 'apiKey' ) . '&shortUrl=' . urlencode( $url ) ); + $result = json_decode( $result ); + if ( !$result->errorCode ) { + foreach ( $result->results as $detail ) { + return $detail->longUrl; + } + } else { + return false; + } + } +} + +// Implementation of Tr.im as a Slinky Service +/* +When using Tr.im, you MAY optionally set your username and password to tie +URLs to your account, e.g. + +$trim = new Slinky_Trim(); +$trim->set( 'username', 'trim_username' ); +$trim->set( 'password', 'trim_password' ); + +$slinky = new Slinky( $url, $trim ); +echo $slinky->short(); + +You could also do this if the URL was already a tr.im URL and you +were going to make it longer, since Tr.im is supported for auto-detection: + +$slinky = new Slinky( $url ); +$slinky->set_service_from_url(); +echo $slinky->long(); + +*/ +class Slinky_Trim extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'tr.im/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'tr.im/' ); + } + + function make_short( $url ) { + $url = 'http://api.tr.im/api/trim_simple?url=' . urlencode( $url ); + + if ( $this->get( 'username' ) && $this->get( 'password' ) ) + $url .= '&username=' . urlencode( $this->get( 'username' ) ) . '&password=' . urlencode( $this->get( 'password' ) ); + + return $this->url_get( $url ); + } + + function make_long( $url ) { + $bits = parse_url( $url ); + $result = $this->url_get( 'http://api.tr.im/api/trim_destination.json?trimpath=' . substr( $bits['path'], 1 ) ); + $result = json_decode($result); + if ( 'OK' == $result->status->result ) + return $result->destination; + else + return $url; + } +} + +// Implementation of Is.Gd as a Slinky Service +class Slinky_IsGd extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'is.gd/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'is.gd/' ); + } + + function make_short( $url ) { + $response = $this->url_get( 'http://is.gd/api.php?longurl=' . urlencode( $url ) ); + if ( 'error' == substr( strtolower( $response ), 0, 5 ) ) + return false; + else + return $response; + } +} + +// Fon.gs +class Slinky_Fongs extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'fon.gs/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'fon.gs/' ); + } + + function make_short( $url ) { + $response = $this->url_get( 'http://fon.gs/create.php?url=' . urlencode( $url ) ); + if ( 'OK:' == substr( $response, 0, 3 ) ) + return str_replace( 'OK: ', '', $response ); + else + return $url; + } +} + +// Micu.rl +class Slinky_Micurl extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'micurl.com/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'micurl.com/' ); + } + + function make_short( $url ) { + $result = $this->url_get( 'http://micurl.com/api.php?url=' . urlencode( $url ) ); + if ( 1 != $result && 2 != $result ) + return 'http://micurl.com/' . $result; + else + return $url; + } +} + +// ur1.ca +class Slinky_Ur1ca extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'ur1.ca/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'ur1.ca/' ); + } + + function make_short( $url ) { + $result = $this->url_post( 'http://ur1.ca/', array( 'longurl' => $url ) ); + if ( preg_match( '/

Your ur1 is: /', $result, $matches ) ) + return $matches[1]; + else + return $url; + } +} + +// PtitURL.com +class Slinky_PtitURL extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'ptiturl.com/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'ptiturl.com/' ); + } + + function make_short( $url ) { + $result = $this->url_get( 'http://ptiturl.com/index.php?creer=oui&url=' . urlencode( $url ) ); + if ( preg_match( '/

]+)\'?>/', $result, $matches ) )
+			return $matches[1];
+		else
+			return $url;
+	}
+}
+
+// Tighturl.com
+class Slinky_TightURL extends Slinky_Service {
+	function url_is_short( $url ) {
+		return stristr( $url, 'tighturl.com/' )
+				|| stristr( $url, '2tu.us/' );
+	}
+	
+	function url_is_long( $url ) {
+		return !stristr( $url, 'tighturl.com/' )
+				&& !stristr( $url, '2tu.us/' );
+	}
+	
+	function make_short( $url ) {
+		$response = $this->url_get( 'http://tighturl.com/?save=y&url=' . urlencode( $url ) );
+		if ( preg_match( '/Your tight URL is: /', $response, $matches ) ) {
+			return $matches[1];
+		} else {
+			return $url;
+		}
+	}
+}
+
+// Snipr for Slinky
+/*
+To use Snipr, you MUST set your user_id and API (key) for the service first, e.g.
+
+$snipr = new Slinky_Snipr();
+$snipr->set( 'user_id', 'Snipr User ID' );
+$snipr->set( 'API', 'Snipr API Key' );
+
+$slinky = new Slinky( $url, $snipr );
+echo $slinky->short();
+
+NOTE: Snipr requires the SimpleXML extension to be installed for lengthening URLs
+*/
+class Slinky_Snipr extends Slinky_Service {
+	// Snipurl, Snurl, Snipr, Sn.im
+	function url_is_short( $url ) {
+		return stristr( $url, 'snipr.com/' ) || stristr( $url, 'snipurl.com/' ) || stristr( $url, 'snurl.com/' ) || stristr( $url, 'sn.im/' );
+	}
+	
+	function url_is_long( $url ) {
+		return !stristr( $url, 'snipr.com/' ) || !stristr( $url, 'snipurl.com/' ) || !stristr( $url, 'snurl.com/' ) || !stristr( $url, 'sn.im/' );
+	}
+	
+	function make_short( $url ) {
+		if ( !$this->get( 'user_id' ) || !$this->get( 'API' ) )
+			return $url;
+		
+		$response = $this->url_post( 'http://snipr.com/site/getsnip', array( 'sniplink' => urlencode( $url ), 'snipuser' => $this->get( 'user_id'), 'snipapi' => $this->get( 'API' ), 'snipformat' => 'simple' ) );
+		if ( 'ERROR' != substr( $response, 0, 5 ) )
+			return $response;
+		else
+			return $url;
+	}
+}
+
+// If you're testing things out, http://dentedreality.com.au/ should convert to:
+// - http://tinyurl.com/jw5sh
+// - http://bit.ly/hEkAD
+// - http://tr.im/sk1H
+// - http://is.gd/1yJ81
+// - http://fon.gs/tc1p8c
+// - http://micurl.com/qen3uub
+// - http://ur1.ca/7dcd
+// - http://ptiturl.com/?id=bac8fb
+// - http://tighturl.com/kgd
+// - http://snipr.com/nbbw3
+// 
+// $slinky = new Slinky( 'http://dentedreality.com.au/' );
+// echo $slinky->short();

From fd6116296efd4dc9168b3fefa6ba586d83a1a454 Mon Sep 17 00:00:00 2001
From: Tobias Diekershoff 
Date: Sun, 6 Feb 2011 17:27:16 +0100
Subject: [PATCH 02/36] Post to Twitter plugin

With this plugin a user can choose to post every _public_ message that
s/he posts on Friendika also on Twitter. The message will be shortened
to if longer then 140 characters in length. If shortened a link to the
original posting will be append to the Twitter posting.
---
 addon/twitter/lighter.png | Bin 0 -> 2490 bytes
 addon/twitter/twitter.css |  41 +++++++++
 addon/twitter/twitter.php | 185 ++++++++++++++++++++++++++++++++++++--
 3 files changed, 220 insertions(+), 6 deletions(-)
 create mode 100644 addon/twitter/lighter.png
 create mode 100644 addon/twitter/twitter.css

diff --git a/addon/twitter/lighter.png b/addon/twitter/lighter.png
new file mode 100644
index 0000000000000000000000000000000000000000..297bb03404f2d7462ee9355aae38f5f5f3e47fbd
GIT binary patch
literal 2490
zcmV;r2}SmaP)dbVG7wVRUJ4ZXi@?ZDjy8FEKeU
zFgbGL({lg-0338hSaefwW^{L9a%BKPWN%_+AVz6&Wp{6KYjYq&Q#1y$)1UwV2@^>~
zK~!jg?VEdWl+_u=f8X9WA)72QVM!vF1VSK4AZQ?nK}o}NseS3JN$f
zgRQMIo!W~OJ6`ZouvAJ_K&eH%O=zU35Dd9+OGJ}EvYTu++57IdU;kJVc9XpY6B?a;
zX3k{ZIp=-eC+|7m`<-)kR{+>vQ7sWi9D|5ebEgWz_KIq$s4!>9f*d_|j-lj_V|e1|
zv2!Q@e7>PCTvsDT9K#C=07>!<2
zJRT3v{^4m(e0B`AMuXes=AQD^+;C$tPj22q>4H*zdfz>`#KAid3>9xAeo+*W%jE#P
zv+pgwyLbU*^X6iX@D|vxdJPV{BV^y=rMIzo>FtA}CzL%H7|@3PC-uR0k{o`MEpT&+
zmiCUwd$DjaD&G5mR^R=5Ugy>A
zFL6`pd;osE=`rd~)-ZEc5shchvh}x5aZ~9nJpS;;UjCggyhMFX4IM@k^;K2OnpeX9
zJ+G59W-M>Ndx+<@J`*QB2?^MN1N-(fead7?=HEi6T!B@Box5IR=L;`>Ej{PX
zHuTf??pp_V_K#2V&%f=WuDXUP)2>6K(eP;bS}ruV@b7*5sr;ydIrB8I2tIsDgsYdEB~aA*X6k7?
zxX|2;qp^|Gwe@`Y#d&IupCC)EqUw`l7)GU&uTKu*U$o?QG#U*z%qZYj8`hDRoCLu8
zhbzgOI5DbLyT^;&?d{E@=<{Loc(HlBWQ@7?YwIarxgyB6oH@guS9eiXI-mWozJlq(
z1uEY@fC2%N(MZ*iqs%Lw&3$(-XHs%f#Ci8GF3A_N^~J`q@N(Yec4#`>p8;Rm>`^(w
z^()mX);zY6A1}KTOQ(hBpZ+tI2M_vvC6EgOasg^TuSW9u`2L~=xMTvlF=IdirA&q(
z01}jz+(`M#6-+Id=Jypvl2wZSngV!x>{xvBuA7QRt)c4kYU--0D3~!Fhr>aA^+`_G
z)iHDWG@POs#IMsQgCL+*sYp&si#>KieJ
zAZPaXZl!3>9M-SjNX7dfvh?=bdf)$&1YWO*1jqy#ZFVPakM~lt{ns24pi(Mnce*e+
zoV|U5)IWA0uWtapa=C)>xf3{EU4zZ(WX19y(%RC@hySVMd_x1@*}REPr@KGD1PCBr
zszd|P3jULJU(P|*6JUEpf1ZUYMN@b5y{gO~R0`R^
zzo2^1b1iYS>vBugsL9qPM&yVTyCwWp(Uo=ev@y*W7rS{ZmOePbh#j}_&X%YtxeZa(=9L5<&(e8Bi
z<5wsYm^&^0MKr*8(egMLdIIf9`S}2Jn9Y=xl~T570XoAdF4!DlHH6a}anEJ-cv*VQ
z<;7KRgYq-}Q)5qi@;qcECS38JtLDV#Y+3g(n;(3LUp}&dB%O}ct5)I-xFV2%>k11g
zTUf@C&yKTa*KVdw^(R50loR*{_b2SKCHeZt4jkLpj^;ZlKOe6sQZ!>aT9uM(b0*;N
zdYL_=0IS=B(gj7|CTgIo3w=s5DLNgUE;lDl
z=6*ck(9~r1FRqNt5);TzP2p%4ylH~wfExv!+`pk8s}?!j(i+mgrP)GJVGd2L
zrifxR3OQ=I9MLCX4Ray;#3LJ#2{HtkfT^vG#S0hk#JUIhwAC2&WDQrS)2nfk*V=iQ!Y2K(sVlqHpM%x^1{ck;y4Kin5jc`W;@8<8AFx4+YWs
z?QSo2A}4+Q<6F?#y0F{rconfig['twitter']['consumerkey'] = 'your consumer_key here';
+ *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
+ *
+ *     To activate the plugin itself add it to the $a->config['system']['addon']
+ *     setting. After this, your user can configure their Twitter account settings
+ *     from "Settings -> Plugin Settings".
+ *
+ *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
+ */
+
+/*   __TODO__
+ *
+ *   - deletion of the OAuth credentials does not work
+ *   - include short links to the original posting if possible
+ *   - what about multimedia content?
+ *     so far we just strip HTML tags from the message
+ *   - after entering the PIN reload page propperly
+ */
 
 function twitter_install() {
+	//  we need some hooks, for the configuration and for sending tweets
+	register_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
+	register_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
 	register_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
+	logger("installed twitter");
 }
 
 
 function twitter_uninstall() {
+	unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
+	unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
 	unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
 }
 
+function twitter_settings_post ($a,$post) {
+	if(! local_user())
+		return;
+	if (isset($_POST['twitter-disconnect'])) {
+		/***
+		 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
+		 * from the user configuration
+                 * TODO this does not work that way!?
+		 * TODO can we revoke the access tokens at Twitter and do we need to do so?
+		 */
+		del_pconfig( local_user(), 'twitter', 'consumerkey'  );
+		del_pconfig( local_user(), 'twitter', 'consumersecret' );
+		del_pconfig( local_user(), 'twitter', 'post' );
+	} else {
+	if (isset($_POST['twitter-pin'])) {
+		//  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
+		logger('got a Twitter PIN');
+		require_once('addon/twitter/twitteroauth.php');
+		$ckey    = get_config('twitter', 'consumerkey'  );
+		$csecret = get_config('twitter', 'consumersecret' );
+		//  the token and secret for which the PIN was generated were hidden in the settings
+		//  form as token and token2, we need a new connection to Twitter using these token
+		//  and secret to request a Access Token with the PIN
+		$connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
+		$token   = $connection->getAccessToken( $_POST['twitter-pin'] );
+		//  ok, now that we have the Access Token, save them in the user config
+ 		set_pconfig(local_user(),'twitter', 'oauthtoken',  $token['oauth_token']);
+		set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
+                set_pconfig(local_user(),'twitter', 'post', 1);
+                //  reload the Addon Settings page, if we don't do it see Bug #42
+                header('Location: '.$a->get_baseurl().'/settings/addon');
+	} else {
+		//  if no PIN is supplied in the POST variables, the user has changed the setting
+		//  to post a tweet for every new __public__ posting to the wall
+		set_pconfig(local_user(),'twitter','post',intval($_POST['twitter']));
+	}}
+}
+function twitter_settings(&$a,&$s) {
+        if(! local_user())
+                return;
+        $a->page['htmlhead'] .= '' . "\r\n";
+	/***
+	 * 1) Check that we have global consumer key & secret
+	 * 2) If no OAuthtoken & stuff is present, generate button to get some
+	 * 3) Checkbox for "Send public notices (140 chars only)
+	 */
+	$ckey    = get_config('twitter', 'consumerkey' );
+	$csecret = get_config('twitter', 'consumersecret' );
+	$otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
+	$osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
+        $enabled = get_pconfig(local_user(), 'twitter', 'post');
+	$checked = (($enabled) ? ' checked="checked" ' : '');
+	$s .= '

'.t('Twitter Posting Settings').'

'; + if ( (!$ckey) && (!$csecret) ) { + /*** + * no global consumer keys + * display warning and skip personal config + */ + $s .= '

'.t('No consumer key pair for Twitter found. Please contact your site administrator.').'

'; + } else { + /*** + * ok we have a consumer key pair now look into the OAuth stuff + */ + if ( (!$otoken) && (!$osecret) ) { + /*** + * the user has not yet connected the account to twitter... + * get a temporary OAuth key/secret pair and display a button with + * which the user can request a PIN to connect the account to a + * account at Twitter. + */ + require_once('addon/twitter/twitteroauth.php'); + $connection = new TwitterOAuth($ckey, $csecret); + $request_token = $connection->getRequestToken(); + $token = $request_token['oauth_token']; + /*** + * make some nice form + */ + $s .= '

'.t('At this Friendika instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your public posts will be posted to Twitter.').'

'; + $s .= '
'.t('Log in with Twitter').'></a>';
+			$s .= '<div id='; + $s .= ''; + $s .= ''; + $s .= ''; + $s .= ''; + $s .= '
'; + $s .= '
'; + } else { + /*** + * we have an OAuth key / secret pair for the user + * so let's give a chance to disable the postings to Twitter + */ + require_once('addon/twitter/twitteroauth.php'); + $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); + $details = $connection->get('account/verify_credentials'); + $s .= '
'; + $s .= '

'.t('If enabled all your public postings will be posted to the associated Twitter account as well.').'

'; + $s .= '
'; + $s .= ''; + $s .= ''; + $s .= '
'; + $s .= '
'; + $s .= ''; + $s .= ''; + $s .= '
'; + $s .= '
'; + } + } + $s .= '
'; +} function twitter_post_hook(&$a,&$b) { @@ -19,12 +169,14 @@ function twitter_post_hook(&$a,&$b) { * Post to Twitter */ + logger('twitter post invoked'); + if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) { load_pconfig(local_user(), 'twitter'); - $ckey = get_pconfig(local_user(), 'twitter', 'consumerkey' ); - $csecret = get_pconfig(local_user(), 'twitter', 'consumersecret' ); + $ckey = get_config('twitter', 'consumerkey' ); + $csecret = get_config('twitter', 'consumersecret' ); $otoken = get_pconfig(local_user(), 'twitter', 'oauthtoken' ); $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' ); @@ -35,12 +187,33 @@ function twitter_post_hook(&$a,&$b) { if($twitter_post) { require_once('addon/twitter/twitteroauth.php'); require_once('include/bbcode.php'); - $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); - $tweet->post('statuses/update', array('status' => bbcode($b['body']))); + $max_char = 140; // max. length for a tweet + $msg = strip_tags(bbcode($b['body'])); + if ( strlen($msg) > $max_char) { + $shortlink = ""; + require_once('addon/twitter/slinky.php'); + // post url = base url + /display/ + owner + post id + // we construct this from the Owner link and replace + // profile by display - this will cause an error when + // /profile/ is in the owner url twice but I don't + // think this will be very common... + $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id']; + $slinky = new Slinky( $posturl ); + // setup a cascade of shortening services + // try to get a short link from these services + // in the order ur1.ca, trim, id.gd, tinyurl + $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) ); + $shortlink = $slinky->short(); + // the new message will be shortened such that "... $shortlink" + // will fit into the character limit + $msg = substr($msg, 0, $max_char-strlen($shortlink)-4); + $msg .= '... ' . $shortlink; + } + // and now tweet it :-) + $tweet->post('statuses/update', array('status' => $msg)); } } - } + } } - From a175027fc1c9cdc17e19f418d0fe4dfb23b710db Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Sun, 6 Feb 2011 17:37:04 +0100 Subject: [PATCH 03/36] deleted an item from the ToDo list --- addon/twitter/twitter.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index 8faa5e5c..8f4f74f7 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -24,13 +24,14 @@ * setting. After this, your user can configure their Twitter account settings * from "Settings -> Plugin Settings". * + * Requirements: PHP5, curl [Slinky library] + * * Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin */ /* __TODO__ * * - deletion of the OAuth credentials does not work - * - include short links to the original posting if possible * - what about multimedia content? * so far we just strip HTML tags from the message * - after entering the PIN reload page propperly From 695e08495604ce8f6e32a937b4077bfd480feb71 Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Sun, 6 Feb 2011 18:18:54 +0100 Subject: [PATCH 04/36] deleted another item from the Twitter addon ToDo list --- addon/twitter/twitter.php | 1 - 1 file changed, 1 deletion(-) diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index 8f4f74f7..7d4cf151 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -34,7 +34,6 @@ * - deletion of the OAuth credentials does not work * - what about multimedia content? * so far we just strip HTML tags from the message - * - after entering the PIN reload page propperly */ function twitter_install() { From 89a33a651e0708c95aa7cd170750715d625bf031 Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Tue, 8 Feb 2011 14:38:51 +0100 Subject: [PATCH 05/36] deletion of OAuth stuff works now, removed ToDo note --- addon/twitter/twitter.php | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index 7d4cf151..961cca3b 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -31,7 +31,6 @@ /* __TODO__ * - * - deletion of the OAuth credentials does not work * - what about multimedia content? * so far we just strip HTML tags from the message */ @@ -58,7 +57,6 @@ function twitter_settings_post ($a,$post) { /*** * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair * from the user configuration - * TODO this does not work that way!? * TODO can we revoke the access tokens at Twitter and do we need to do so? */ del_pconfig( local_user(), 'twitter', 'consumerkey' ); @@ -85,7 +83,7 @@ function twitter_settings_post ($a,$post) { } else { // if no PIN is supplied in the POST variables, the user has changed the setting // to post a tweet for every new __public__ posting to the wall - set_pconfig(local_user(),'twitter','post',intval($_POST['twitter'])); + set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable'])); }} } function twitter_settings(&$a,&$s) { @@ -130,7 +128,7 @@ function twitter_settings(&$a,&$s) { * make some nice form */ $s .= '

'.t('At this Friendika instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your public posts will be posted to Twitter.').'

'; - $s .= ''.t('Log in with Twitter').'></a>';
+			$s .= '<a href=getAuthorizeURL($token).'" target="_twitter">'.t('Log in with Twitter').''; $s .= '
'; $s .= ''; $s .= ''; @@ -150,7 +148,7 @@ function twitter_settings(&$a,&$s) { $s .= '

'.t('If enabled all your public postings will be posted to the associated Twitter account as well.').'

'; $s .= '
'; $s .= ''; - $s .= ''; + $s .= ''; $s .= '
'; $s .= '
'; $s .= ''; From 2a093c5c8b3532af61a145c2218a922254a8a24a Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Tue, 8 Feb 2011 14:39:59 +0100 Subject: [PATCH 06/36] added link to Redmine of addon author --- addon/piwik/piwik.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/addon/piwik/piwik.php b/addon/piwik/piwik.php index aad2fd83..52bdaeb0 100644 --- a/addon/piwik/piwik.php +++ b/addon/piwik/piwik.php @@ -18,6 +18,8 @@ * installation has. Alter the baseurl to fit your needs, don't care * about http/https but beware to put the trailing / at the end of your * setting. + * + * Documentation see http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Piwik_Plugin */ function piwik_install() { From ca1b8a267da429de1fffa6207e76f0713e1536c7 Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Tue, 8 Feb 2011 15:17:41 +0100 Subject: [PATCH 07/36] post to StatusNet addon for Friendika --- addon/statusnet/OAuth.php | 874 ++++++++++++++++++++++++ addon/statusnet/signinwithstatusnet.png | Bin 0 -> 5808 bytes addon/statusnet/slinky.php | 704 +++++++++++++++++++ addon/statusnet/statusnet.css | 67 ++ addon/statusnet/statusnet.php | 243 +++++++ addon/statusnet/twitteroauth.php | 245 +++++++ 6 files changed, 2133 insertions(+) create mode 100644 addon/statusnet/OAuth.php create mode 100644 addon/statusnet/signinwithstatusnet.png create mode 100644 addon/statusnet/slinky.php create mode 100644 addon/statusnet/statusnet.css create mode 100644 addon/statusnet/statusnet.php create mode 100644 addon/statusnet/twitteroauth.php diff --git a/addon/statusnet/OAuth.php b/addon/statusnet/OAuth.php new file mode 100644 index 00000000..67a94c47 --- /dev/null +++ b/addon/statusnet/OAuth.php @@ -0,0 +1,874 @@ +key = $key; + $this->secret = $secret; + $this->callback_url = $callback_url; + } + + function __toString() { + return "OAuthConsumer[key=$this->key,secret=$this->secret]"; + } +} + +class OAuthToken { + // access tokens and request tokens + public $key; + public $secret; + + /** + * key = the token + * secret = the token secret + */ + function __construct($key, $secret) { + $this->key = $key; + $this->secret = $secret; + } + + /** + * generates the basic string serialization of a token that a server + * would respond to request_token and access_token calls with + */ + function to_string() { + return "oauth_token=" . + OAuthUtil::urlencode_rfc3986($this->key) . + "&oauth_token_secret=" . + OAuthUtil::urlencode_rfc3986($this->secret); + } + + function __toString() { + return $this->to_string(); + } +} + +/** + * A class for implementing a Signature Method + * See section 9 ("Signing Requests") in the spec + */ +abstract class OAuthSignatureMethod { + /** + * Needs to return the name of the Signature Method (ie HMAC-SHA1) + * @return string + */ + abstract public function get_name(); + + /** + * Build up the signature + * NOTE: The output of this function MUST NOT be urlencoded. + * the encoding is handled in OAuthRequest when the final + * request is serialized + * @param OAuthRequest $request + * @param OAuthConsumer $consumer + * @param OAuthToken $token + * @return string + */ + abstract public function build_signature($request, $consumer, $token); + + /** + * Verifies that a given signature is correct + * @param OAuthRequest $request + * @param OAuthConsumer $consumer + * @param OAuthToken $token + * @param string $signature + * @return bool + */ + public function check_signature($request, $consumer, $token, $signature) { + $built = $this->build_signature($request, $consumer, $token); + return $built == $signature; + } +} + +/** + * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] + * where the Signature Base String is the text and the key is the concatenated values (each first + * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&' + * character (ASCII code 38) even if empty. + * - Chapter 9.2 ("HMAC-SHA1") + */ +class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod { + function get_name() { + return "HMAC-SHA1"; + } + + public function build_signature($request, $consumer, $token) { + $base_string = $request->get_signature_base_string(); + $request->base_string = $base_string; + + $key_parts = array( + $consumer->secret, + ($token) ? $token->secret : "" + ); + + $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); + $key = implode('&', $key_parts); + + return base64_encode(hash_hmac('sha1', $base_string, $key, true)); + } +} + +/** + * The PLAINTEXT method does not provide any security protection and SHOULD only be used + * over a secure channel such as HTTPS. It does not use the Signature Base String. + * - Chapter 9.4 ("PLAINTEXT") + */ +class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod { + public function get_name() { + return "PLAINTEXT"; + } + + /** + * oauth_signature is set to the concatenated encoded values of the Consumer Secret and + * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is + * empty. The result MUST be encoded again. + * - Chapter 9.4.1 ("Generating Signatures") + * + * Please note that the second encoding MUST NOT happen in the SignatureMethod, as + * OAuthRequest handles this! + */ + public function build_signature($request, $consumer, $token) { + $key_parts = array( + $consumer->secret, + ($token) ? $token->secret : "" + ); + + $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); + $key = implode('&', $key_parts); + $request->base_string = $key; + + return $key; + } +} + +/** + * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in + * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for + * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a + * verified way to the Service Provider, in a manner which is beyond the scope of this + * specification. + * - Chapter 9.3 ("RSA-SHA1") + */ +abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod { + public function get_name() { + return "RSA-SHA1"; + } + + // Up to the SP to implement this lookup of keys. Possible ideas are: + // (1) do a lookup in a table of trusted certs keyed off of consumer + // (2) fetch via http using a url provided by the requester + // (3) some sort of specific discovery code based on request + // + // Either way should return a string representation of the certificate + protected abstract function fetch_public_cert(&$request); + + // Up to the SP to implement this lookup of keys. Possible ideas are: + // (1) do a lookup in a table of trusted certs keyed off of consumer + // + // Either way should return a string representation of the certificate + protected abstract function fetch_private_cert(&$request); + + public function build_signature($request, $consumer, $token) { + $base_string = $request->get_signature_base_string(); + $request->base_string = $base_string; + + // Fetch the private key cert based on the request + $cert = $this->fetch_private_cert($request); + + // Pull the private key ID from the certificate + $privatekeyid = openssl_get_privatekey($cert); + + // Sign using the key + $ok = openssl_sign($base_string, $signature, $privatekeyid); + + // Release the key resource + openssl_free_key($privatekeyid); + + return base64_encode($signature); + } + + public function check_signature($request, $consumer, $token, $signature) { + $decoded_sig = base64_decode($signature); + + $base_string = $request->get_signature_base_string(); + + // Fetch the public key cert based on the request + $cert = $this->fetch_public_cert($request); + + // Pull the public key ID from the certificate + $publickeyid = openssl_get_publickey($cert); + + // Check the computed signature against the one passed in the query + $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); + + // Release the key resource + openssl_free_key($publickeyid); + + return $ok == 1; + } +} + +class OAuthRequest { + private $parameters; + private $http_method; + private $http_url; + // for debug purposes + public $base_string; + public static $version = '1.0'; + public static $POST_INPUT = 'php://input'; + + function __construct($http_method, $http_url, $parameters=NULL) { + @$parameters or $parameters = array(); + $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters); + $this->parameters = $parameters; + $this->http_method = $http_method; + $this->http_url = $http_url; + } + + + /** + * attempt to build up a request from what was passed to the server + */ + public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { + $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") + ? 'http' + : 'https'; + @$http_url or $http_url = $scheme . + '://' . $_SERVER['HTTP_HOST'] . + ':' . + $_SERVER['SERVER_PORT'] . + $_SERVER['REQUEST_URI']; + @$http_method or $http_method = $_SERVER['REQUEST_METHOD']; + + // We weren't handed any parameters, so let's find the ones relevant to + // this request. + // If you run XML-RPC or similar you should use this to provide your own + // parsed parameter-list + if (!$parameters) { + // Find request headers + $request_headers = OAuthUtil::get_headers(); + + // Parse the query-string to find GET parameters + $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); + + // It's a POST request of the proper content-type, so parse POST + // parameters and add those overriding any duplicates from GET + if ($http_method == "POST" + && @strstr($request_headers["Content-Type"], + "application/x-www-form-urlencoded") + ) { + $post_data = OAuthUtil::parse_parameters( + file_get_contents(self::$POST_INPUT) + ); + $parameters = array_merge($parameters, $post_data); + } + + // We have a Authorization-header with OAuth data. Parse the header + // and add those overriding any duplicates from GET or POST + if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") { + $header_parameters = OAuthUtil::split_header( + $request_headers['Authorization'] + ); + $parameters = array_merge($parameters, $header_parameters); + } + + } + + return new OAuthRequest($http_method, $http_url, $parameters); + } + + /** + * pretty much a helper function to set up the request + */ + public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { + @$parameters or $parameters = array(); + $defaults = array("oauth_version" => OAuthRequest::$version, + "oauth_nonce" => OAuthRequest::generate_nonce(), + "oauth_timestamp" => OAuthRequest::generate_timestamp(), + "oauth_consumer_key" => $consumer->key); + if ($token) + $defaults['oauth_token'] = $token->key; + + $parameters = array_merge($defaults, $parameters); + + return new OAuthRequest($http_method, $http_url, $parameters); + } + + public function set_parameter($name, $value, $allow_duplicates = true) { + if ($allow_duplicates && isset($this->parameters[$name])) { + // We have already added parameter(s) with this name, so add to the list + if (is_scalar($this->parameters[$name])) { + // This is the first duplicate, so transform scalar (string) + // into an array so we can add the duplicates + $this->parameters[$name] = array($this->parameters[$name]); + } + + $this->parameters[$name][] = $value; + } else { + $this->parameters[$name] = $value; + } + } + + public function get_parameter($name) { + return isset($this->parameters[$name]) ? $this->parameters[$name] : null; + } + + public function get_parameters() { + return $this->parameters; + } + + public function unset_parameter($name) { + unset($this->parameters[$name]); + } + + /** + * The request parameters, sorted and concatenated into a normalized string. + * @return string + */ + public function get_signable_parameters() { + // Grab all parameters + $params = $this->parameters; + + // Remove oauth_signature if present + // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") + if (isset($params['oauth_signature'])) { + unset($params['oauth_signature']); + } + + return OAuthUtil::build_http_query($params); + } + + /** + * Returns the base string of this request + * + * The base string defined as the method, the url + * and the parameters (normalized), each urlencoded + * and the concated with &. + */ + public function get_signature_base_string() { + $parts = array( + $this->get_normalized_http_method(), + $this->get_normalized_http_url(), + $this->get_signable_parameters() + ); + + $parts = OAuthUtil::urlencode_rfc3986($parts); + + return implode('&', $parts); + } + + /** + * just uppercases the http method + */ + public function get_normalized_http_method() { + return strtoupper($this->http_method); + } + + /** + * parses the url and rebuilds it to be + * scheme://host/path + */ + public function get_normalized_http_url() { + $parts = parse_url($this->http_url); + + $port = @$parts['port']; + $scheme = $parts['scheme']; + $host = $parts['host']; + $path = @$parts['path']; + + $port or $port = ($scheme == 'https') ? '443' : '80'; + + if (($scheme == 'https' && $port != '443') + || ($scheme == 'http' && $port != '80')) { + $host = "$host:$port"; + } + return "$scheme://$host$path"; + } + + /** + * builds a url usable for a GET request + */ + public function to_url() { + $post_data = $this->to_postdata(); + $out = $this->get_normalized_http_url(); + if ($post_data) { + $out .= '?'.$post_data; + } + return $out; + } + + /** + * builds the data one would send in a POST request + */ + public function to_postdata() { + return OAuthUtil::build_http_query($this->parameters); + } + + /** + * builds the Authorization: header + */ + public function to_header($realm=null) { + $first = true; + if($realm) { + $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"'; + $first = false; + } else + $out = 'Authorization: OAuth'; + + $total = array(); + foreach ($this->parameters as $k => $v) { + if (substr($k, 0, 5) != "oauth") continue; + if (is_array($v)) { + throw new OAuthException('Arrays not supported in headers'); + } + $out .= ($first) ? ' ' : ','; + $out .= OAuthUtil::urlencode_rfc3986($k) . + '="' . + OAuthUtil::urlencode_rfc3986($v) . + '"'; + $first = false; + } + return $out; + } + + public function __toString() { + return $this->to_url(); + } + + + public function sign_request($signature_method, $consumer, $token) { + $this->set_parameter( + "oauth_signature_method", + $signature_method->get_name(), + false + ); + $signature = $this->build_signature($signature_method, $consumer, $token); + $this->set_parameter("oauth_signature", $signature, false); + } + + public function build_signature($signature_method, $consumer, $token) { + $signature = $signature_method->build_signature($this, $consumer, $token); + return $signature; + } + + /** + * util function: current timestamp + */ + private static function generate_timestamp() { + return time(); + } + + /** + * util function: current nonce + */ + private static function generate_nonce() { + $mt = microtime(); + $rand = mt_rand(); + + return md5($mt . $rand); // md5s look nicer than numbers + } +} + +class OAuthServer { + protected $timestamp_threshold = 300; // in seconds, five minutes + protected $version = '1.0'; // hi blaine + protected $signature_methods = array(); + + protected $data_store; + + function __construct($data_store) { + $this->data_store = $data_store; + } + + public function add_signature_method($signature_method) { + $this->signature_methods[$signature_method->get_name()] = + $signature_method; + } + + // high level functions + + /** + * process a request_token request + * returns the request token on success + */ + public function fetch_request_token(&$request) { + $this->get_version($request); + + $consumer = $this->get_consumer($request); + + // no token required for the initial token request + $token = NULL; + + $this->check_signature($request, $consumer, $token); + + // Rev A change + $callback = $request->get_parameter('oauth_callback'); + $new_token = $this->data_store->new_request_token($consumer, $callback); + + return $new_token; + } + + /** + * process an access_token request + * returns the access token on success + */ + public function fetch_access_token(&$request) { + $this->get_version($request); + + $consumer = $this->get_consumer($request); + + // requires authorized request token + $token = $this->get_token($request, $consumer, "request"); + + $this->check_signature($request, $consumer, $token); + + // Rev A change + $verifier = $request->get_parameter('oauth_verifier'); + $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); + + return $new_token; + } + + /** + * verify an api call, checks all the parameters + */ + public function verify_request(&$request) { + $this->get_version($request); + $consumer = $this->get_consumer($request); + $token = $this->get_token($request, $consumer, "access"); + $this->check_signature($request, $consumer, $token); + return array($consumer, $token); + } + + // Internals from here + /** + * version 1 + */ + private function get_version(&$request) { + $version = $request->get_parameter("oauth_version"); + if (!$version) { + // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. + // Chapter 7.0 ("Accessing Protected Ressources") + $version = '1.0'; + } + if ($version !== $this->version) { + throw new OAuthException("OAuth version '$version' not supported"); + } + return $version; + } + + /** + * figure out the signature with some defaults + */ + private function get_signature_method(&$request) { + $signature_method = + @$request->get_parameter("oauth_signature_method"); + + if (!$signature_method) { + // According to chapter 7 ("Accessing Protected Ressources") the signature-method + // parameter is required, and we can't just fallback to PLAINTEXT + throw new OAuthException('No signature method parameter. This parameter is required'); + } + + if (!in_array($signature_method, + array_keys($this->signature_methods))) { + throw new OAuthException( + "Signature method '$signature_method' not supported " . + "try one of the following: " . + implode(", ", array_keys($this->signature_methods)) + ); + } + return $this->signature_methods[$signature_method]; + } + + /** + * try to find the consumer for the provided request's consumer key + */ + private function get_consumer(&$request) { + $consumer_key = @$request->get_parameter("oauth_consumer_key"); + if (!$consumer_key) { + throw new OAuthException("Invalid consumer key"); + } + + $consumer = $this->data_store->lookup_consumer($consumer_key); + if (!$consumer) { + throw new OAuthException("Invalid consumer"); + } + + return $consumer; + } + + /** + * try to find the token for the provided request's token key + */ + private function get_token(&$request, $consumer, $token_type="access") { + $token_field = @$request->get_parameter('oauth_token'); + $token = $this->data_store->lookup_token( + $consumer, $token_type, $token_field + ); + if (!$token) { + throw new OAuthException("Invalid $token_type token: $token_field"); + } + return $token; + } + + /** + * all-in-one function to check the signature on a request + * should guess the signature method appropriately + */ + private function check_signature(&$request, $consumer, $token) { + // this should probably be in a different method + $timestamp = @$request->get_parameter('oauth_timestamp'); + $nonce = @$request->get_parameter('oauth_nonce'); + + $this->check_timestamp($timestamp); + $this->check_nonce($consumer, $token, $nonce, $timestamp); + + $signature_method = $this->get_signature_method($request); + + $signature = $request->get_parameter('oauth_signature'); + $valid_sig = $signature_method->check_signature( + $request, + $consumer, + $token, + $signature + ); + + if (!$valid_sig) { + throw new OAuthException("Invalid signature"); + } + } + + /** + * check that the timestamp is new enough + */ + private function check_timestamp($timestamp) { + if( ! $timestamp ) + throw new OAuthException( + 'Missing timestamp parameter. The parameter is required' + ); + + // verify that timestamp is recentish + $now = time(); + if (abs($now - $timestamp) > $this->timestamp_threshold) { + throw new OAuthException( + "Expired timestamp, yours $timestamp, ours $now" + ); + } + } + + /** + * check that the nonce is not repeated + */ + private function check_nonce($consumer, $token, $nonce, $timestamp) { + if( ! $nonce ) + throw new OAuthException( + 'Missing nonce parameter. The parameter is required' + ); + + // verify that the nonce is uniqueish + $found = $this->data_store->lookup_nonce( + $consumer, + $token, + $nonce, + $timestamp + ); + if ($found) { + throw new OAuthException("Nonce already used: $nonce"); + } + } + +} + +class OAuthDataStore { + function lookup_consumer($consumer_key) { + // implement me + } + + function lookup_token($consumer, $token_type, $token) { + // implement me + } + + function lookup_nonce($consumer, $token, $nonce, $timestamp) { + // implement me + } + + function new_request_token($consumer, $callback = null) { + // return a new token attached to this consumer + } + + function new_access_token($token, $consumer, $verifier = null) { + // return a new access token attached to this consumer + // for the user associated with this token if the request token + // is authorized + // should also invalidate the request token + } + +} + +class OAuthUtil { + public static function urlencode_rfc3986($input) { + if (is_array($input)) { + return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input); + } else if (is_scalar($input)) { + return str_replace( + '+', + ' ', + str_replace('%7E', '~', rawurlencode($input)) + ); + } else { + return ''; + } +} + + + // This decode function isn't taking into consideration the above + // modifications to the encoding process. However, this method doesn't + // seem to be used anywhere so leaving it as is. + public static function urldecode_rfc3986($string) { + return urldecode($string); + } + + // Utility function for turning the Authorization: header into + // parameters, has to do some unescaping + // Can filter out any non-oauth parameters if needed (default behaviour) + public static function split_header($header, $only_allow_oauth_parameters = true) { + $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/'; + $offset = 0; + $params = array(); + while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) { + $match = $matches[0]; + $header_name = $matches[2][0]; + $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0]; + if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) { + $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content); + } + $offset = $match[1] + strlen($match[0]); + } + + if (isset($params['realm'])) { + unset($params['realm']); + } + + return $params; + } + + // helper to try to sort out headers for people who aren't running apache + public static function get_headers() { + if (function_exists('apache_request_headers')) { + // we need this to get the actual Authorization: header + // because apache tends to tell us it doesn't exist + $headers = apache_request_headers(); + + // sanitize the output of apache_request_headers because + // we always want the keys to be Cased-Like-This and arh() + // returns the headers in the same case as they are in the + // request + $out = array(); + foreach( $headers AS $key => $value ) { + $key = str_replace( + " ", + "-", + ucwords(strtolower(str_replace("-", " ", $key))) + ); + $out[$key] = $value; + } + } else { + // otherwise we don't have apache and are just going to have to hope + // that $_SERVER actually contains what we need + $out = array(); + if( isset($_SERVER['CONTENT_TYPE']) ) + $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; + if( isset($_ENV['CONTENT_TYPE']) ) + $out['Content-Type'] = $_ENV['CONTENT_TYPE']; + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) == "HTTP_") { + // this is chaos, basically it is just there to capitalize the first + // letter of every word that is not an initial HTTP and strip HTTP + // code from przemek + $key = str_replace( + " ", + "-", + ucwords(strtolower(str_replace("_", " ", substr($key, 5)))) + ); + $out[$key] = $value; + } + } + } + return $out; + } + + // This function takes a input like a=b&a=c&d=e and returns the parsed + // parameters like this + // array('a' => array('b','c'), 'd' => 'e') + public static function parse_parameters( $input ) { + if (!isset($input) || !$input) return array(); + + $pairs = explode('&', $input); + + $parsed_parameters = array(); + foreach ($pairs as $pair) { + $split = explode('=', $pair, 2); + $parameter = OAuthUtil::urldecode_rfc3986($split[0]); + $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : ''; + + if (isset($parsed_parameters[$parameter])) { + // We have already recieved parameter(s) with this name, so add to the list + // of parameters with this name + + if (is_scalar($parsed_parameters[$parameter])) { + // This is the first duplicate, so transform scalar (string) into an array + // so we can add the duplicates + $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]); + } + + $parsed_parameters[$parameter][] = $value; + } else { + $parsed_parameters[$parameter] = $value; + } + } + return $parsed_parameters; + } + + public static function build_http_query($params) { + if (!$params) return ''; + + // Urlencode both keys and values + $keys = OAuthUtil::urlencode_rfc3986(array_keys($params)); + $values = OAuthUtil::urlencode_rfc3986(array_values($params)); + $params = array_combine($keys, $values); + + // Parameters are sorted by name, using lexicographical byte value ordering. + // Ref: Spec: 9.1.1 (1) + uksort($params, 'strcmp'); + + $pairs = array(); + foreach ($params as $parameter => $value) { + if (is_array($value)) { + // If two or more parameters share the same name, they are sorted by their value + // Ref: Spec: 9.1.1 (1) + natsort($value); + foreach ($value as $duplicate_value) { + $pairs[] = $parameter . '=' . $duplicate_value; + } + } else { + $pairs[] = $parameter . '=' . $value; + } + } + // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61) + // Each name-value pair is separated by an '&' character (ASCII code 38) + return implode('&', $pairs); + } +} + +?> diff --git a/addon/statusnet/signinwithstatusnet.png b/addon/statusnet/signinwithstatusnet.png new file mode 100644 index 0000000000000000000000000000000000000000..a33998d5cf6ddfc7b71a437b7727586f601af976 GIT binary patch literal 5808 zcmV;h7EkGkP)Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01ejw01ejxLMWSf00007bV*G`2ipP& z3Ks+fAo!X902VMwL_t(|+U=Wpbe+d_*nczM^1knFz+12pBtQ@VSCKSHiQ=MNqN93I zB_G$0)JRU_*maY-Ij&WolN`6TW5-DyCuz^IW7SP%Nmd-!wIkNDl*$xEEtE)cktpsf z2#^FxfY_I}eB1Pox8OYx1Swf|{RihCoNwOD+&g#felG;Tp?&)}`e%QkE&Spa)|!dh zH+Ub%k*|M)>*MkvXHrBo7l0JtC6cK;8aynFM*pF;dGXrFlT#TUXYEq9~T zyE-@|1yX<;D7-6dJ^1DSgl1XSU*Y=rP0;>Zg%H1`ulmS+Yt2;ZE)@jVq>)RSdm!iY zt^FgMneh4NtzrJff(Wu=zfua#wjfZ~seOI?ri{CQwc6L8{n^>TafD`?moc^!IznhD zRC%r>7@vQAkbzvl@}$YLJsG4BtWKL{9v4C&G@ZU*Y(W~vb#h-HzX>jnP)a5A;#UQ; zO9JIGI@v?t$UgGU7|qF>h(}ro8MO!$r^Z~)PWn7|ZvzQa^6kT;{O_(wKD{W0i@Lg{ zm?>}&0yWLO62-aqGbSjVr)F^FepRu@m0(VXH`}^vrNd10{Z-!W{i4rIZ*etxy<7Sh z&$wN$dpg3n2)ULYoFtUP0*m zARwgc_!V@U4X>-wce+9;DVl2)rkVD>ABv(Rprv>Bg8)rRT;DIiPzos}QV1N+Lzl9A zx2q|aN<2k{QU{WHnX>`U&#`s?mvFoZK#-0vL6as!6DM)JabA4qi`>5KYqU4q&f0pD zM|TbqHzXM^;J>X;k@aWL@?r|1?cLq{9R=Vg|MKBkAODvX2Bj3P@AGe-{Xg_gOcY=~^e~gI z!|OfWfM8wAJmMj%_%MQxKJ^3uH#9WzAMd&wQ`2U}AyA6LeSQ3|1N%AB-&YoxbU4Co z^XK#62Uej8$(EBR5CRgm&FVSLXxDfzr4+B6?!pZMOikmq`EA!slPl3r2tg18I2G>> z@XdQaL`x#U3&)S~{k?kt`1?;jh!En6%Bduneh_fDzmE&!;{;0a!H&)<#uq|}64Rqg zix=MhcR1cSx@PmwRzF5KlmY~S@_BymXCc?eJKg`2x#1YVJq--{Ie` z-$2H3%X0&nNt)v|v${S?De|7jvqz7x>+D$oHng-7HVm|)@>EJuX8MdXz~K1Nf_9nr zAW^G)DZMYW(C_^yj)82Fh?^@Avd=lksK z?JXm?p=Caeu_&$|u(+;)h-nl8XCyZ?Gyu>Pixmi_6g$rJaP-n87N*lIs;lG22Mz%6 z;EI*REsO8%dJ`c8>2R18jZN%5-;1ef+|$uX%rq}!S}6o88k>k1CLvuXKr!h!{NU}k zkV5dlvSoA)4RQ3+C6?6HbMw3wgs5hIr4%onI>pJMK~Rd%+;lVJPM*Kt_cp0;mZ4z-qzrR(hN?Pd45v*q(PA34P9XS&g)#zz+~sZtmx1_wCO z-%mUg;_i-4Y+bLSuO9@Q9UUR-7MNt+yjD6>DTIKrU6R+rUI=;u_dv~KtjZZ9JLHF&Yj1KrY0uxd3K!Xp>JXW0W`#7teR7xhwBGryewVk=%s!JGa1~# zFVB0vk1D#oUZ8ljyNmNnNG8+X$}a%_xJAM^w3aw-{X6BV;Kf(nwwcYrx_{4 z6w{Ao&LD-3>t|_gxEn=v3RBl?LPi|d&oDC4#r)bPmc|7~AAf=qPd!b3c$n0R<*fO$ zuMuu&tdK;3uM{C|%IAN%>l7bfzJi2pQx}a8(sVQ-Q78`f^_9)KLBh7VWquo5 zPn~32*C`exlZ@qZ?7w({b48ab8MfJf@xoL+qpuIGXudZUO>&7j|NP}`_(6aIdPau% z*Eg@nsCb(~3{>!s6|m*xF`DBy(in|VYuOlDl8oc9z58^Pb=%(4jpKRTzjPU|_w=y! z)Jcq@Wp#=|@}2wcCt{jx@9r+|^_AlFo*sfgv9Yz4cP?Bg)8V&QtV97@Pn`t7Hgp=I zQU3Uae_|}3M-u{FN&=;DgMc6X_Cr;vkIqz@1AP}cGctm&f{HgQ#6=gz$NADfJx9*- zFg1-pDZC)yjZEbC=Zl24Io}Q_P za~(3SQ{f5-KDBx^yUw0v@A+Q#^!768t!8x1R6p zEVu&C9y!ALme#U~ELn@TM5?^!NPj;)Bg19fFOHAXH8cpo+;|O+=U18J4XyKOj@R(S zTYCZc*s>ewOr=SM?W%PG`0PzLv*qLoP7DsPt*eViR&m5&DXYV1)w1s?Nrl7cQlmYY;tLyZL6?$A*X7$g z3f(AAzO{!>-?Wym-o1&hZQF`h^yxppegg^HCKd`+G1-KZuVUh?<8pR%l(Bq)zV|Iz zN_(o{HcvWv#`F0KX9&WkNkcTsjx#+p#$r{Dm+J>Sv3EB)&!a7o;KPfSka1le-@BWa zPj}IgO7SOm-o+2z-plcU0RaAB-8vF>nEFU`ie9B7V|FvTw9sXUx4Qm2N(BfcAkd`A z>Ao%G+z~Wsl8!B*ck5RAcf84*O`G`et1q+hvA^ZcAO8bL$vfZt7Mg9BeJw-Nm|IiB z!>iZuz|v(bNG7SZEXEy&6N3Z%_4e0reZQ(8><0mtCML@SU0UBjYfUXn>g%V-5U8p> zmZ38z9;Y^Jm**xOm*6r#^70s=vWC{4O41aMm%oRzSsdT5@*g!JNZ1x_iGp%CK5&Vn z{g+tN+)UPW>6;j*rx>tzrqYBAy$WX14pSeEmcJXLQ5L4tG{xdr6>DoOi>7#tXedRH#TN=52YQXh@-u^X22;EI(jt*<9x+vI$Y-mx*hz2go1AfP@r1<%wqI#Ov`6A5CW z5M#M4n-3r6Td%!ZW_W;;gF~27qahY8TU#jv?a34ik|}B|8$qSp2Nepss9Y4$VjXCE zPd9tconthYWl_2g%P^|;hjpEs=e4k>_gs}iQz){o!-0#1tm5h6VZOcd4IbaSyS(P; zrAs93FqS?QYqTa3w5L;~BH?mUM6bm5&gI|W7yJH*;fYf`xA!wFYk7!}9^+{5GxU$_ zM<5C5aS)QBLx<2Ui-o`Y2=4eeN-5&)3uwCIc6$DCGhQZBW_&3G2|LW9v_@kj%8I5r z^o@_P<>X0D4Gq#YJjA5yRB2xYxPezT*%8B}#%q08HpXb%?(@Z!Hqq!_` z%dWDDh9)tj#z=O8@9o}2&huE=*hpI<$>t-6r(glPsCE%eT_dDvRW3;B-SWYd=9f}X zAC2Z=`@BWsyYKqO(!I^vTLf8n$q-v@=3>+(Ao4+ydcX&_5yDl`3trk_!Ig@ z_LZx#B^O8)0}H>xEf7*8*WZs3k5Q=b7Am=35b*syyLs-&VZ0!qJ(;9El}3uGw58+u zmt{JmW(c#0?4I6pxSr3>b7!uc4=)nAO7qOJ_DVxat?G>ONvb+qVCg#T$rMrudWH+G zO_e@xMw))>j=$aw`uZLX;yU15RBDMtxm!<@2=zCzOqbP88g z^DmB%v-jM&sv8(mBVrod*0z9;EMCImy1IfD85(5Laf<4sDCAOOPApDSELL_GOZ8JJ z1dED$$8uQ~B$KRbX=O!I6H*8|QfUlL!_xH%*VV<)^m5$?n9}s6bk5p^U!W;*BfC!g zS3EykhFD^PtTV)=(StOu-^j_Qp60Eu{3*9T`2?D2aOTO?i!RtpU8i`d>(piU-O$=f+zO#f$;Q_CyxM)5 zbEBjD?oWTrJsq8F>gb>;7URPBIL{wDM#D6wFKNzO=g;To$BvTsJU+Aerz}V&`O{4w zWO2H#y!J0&dxe|l&8rfafy^X-^ZNG7g#Om~^NX1qQNa&_xMguydq-8aNeY2&7;Nh3 z7^9+r{7GHOsLE{z`K(Aj_B=H*{x#h3mA`~S-~dEwp6P3W4$)HF09tL`L#mYP~VyLK)8;}c{&4=?bE7$$S#aXQm!l6JUItm*8e zE)rodlR*l}()xO8EQ?20t>&GJ7cn(SOKpO~{r%)Um&RzUkjB&`x3;wr4TZ`Dw)wRQ zlv1?R*7Aqz)^qIAB~p zD8GAqDn-OFSz2GuT?^XDxGt8iV`@4P)1)I^$LBX}EHl0?B&kT4Md>>7zK^Br+|by_ zr*FK8?%`p)z^BHtnaJnMagjK7?3nU08KsBA*Hm6pN?~X=y@PMkkX*&#@BA%YKP&{W zx@B?akA6rfl`NEyLm~D*`Xva3$ht0*jziw}@Qdj+U6Vu%lZa`eNlDi87|vwyf`A&! zB5WA^=NGqdLqh|JaG2pthMyKK#iDeY&)vM9`e>A~T#l^g5j9QXp%59@Wi*#Vmy%>S zjIHa)qNy*rTO-*l<3&cRwJf|KU^tsa0kxJzNY@$7X32OS5yK#1+l7ammaBJtpP_7q zoa+${g@}bhxTUj#fLhxoYMKR@xf~OYgRSc%Y#U8VCLD+Hd>+^LF*S`^+eQk(Xf{jU z_lcS&u~4YI&eSv#wq39uMO=a)An$ohI8MRJ6w{l!6xfDI%rr4{9h4&Dx{T%X*KvFg$McDpCJEa{*EDj)y;;{qp@^9wYVAU{Y20zh6a`k7lB`=u z8`oGNEW;%0I%HiJ*AI|FU>Q2GP>7JGlk+@=itk=)S;Rsia-PRoSHcf&c zAmh4Bx(<2QLx@7$6EQ;tJ`#ew=P{noGwHenL4a+VB#Lh;gis}>M-PYJb%Ri$lTzd8 zW8dTG|M)v@{k!jxT(NwrOS8!I(z42xNi~C+F2xH$@v&6VEy;NvFL#|{Yu8Cm4-TP8 zNmD$|lDax>n%ly{bef1ch47xXWBdczNPn= zj=!1#ujw?HzFy7nj??cds@n{zXiWvZi@y!(S50MHp|oEnjOWpE-$xiaaDe&^>+vQg zs@(uJMKosVZBfPMqRKg4N>K}Rm3N*7=$h{|{qJl_>PlzHLdkhr>~nd_OGyPTYIf%z1Mrp z_WOIG*L#Im{1?LCmv8_4XS;b7IdBR9 literal 0 HcmV?d00001 diff --git a/addon/statusnet/slinky.php b/addon/statusnet/slinky.php new file mode 100644 index 00000000..51432c3f --- /dev/null +++ b/addon/statusnet/slinky.php @@ -0,0 +1,704 @@ +url_get() and ->url_post() +define( 'SLINKY_BODY', 1 ); // Default +define( 'SLINKY_HEADERS', 2 ); // Not implemented yet +define( 'SLINKY_FINAL_URL', 3 ); // Default for lengthening URLs + +// So that services may decide what to do with us +define( 'SLINKY_USER_AGENT', 'Slinky v1.0 +http://dentedreality.com.au/projects/slinky/' ); + +// How many seconds until remote requests should be cut? +define( 'SLINKY_TIMEOUT', 10 ); + +/** + * Slinky allows you to go back and forth between "long" and shortened URLs + * using popular URL shortening services. + * + * Slinky assumes you have cURL installed and working, and requires the JSON + * extension installed if you're working with a service that uses JSON. + * + * Slinky will ONLY work with PHP5+ + * + * It supports some of the more popular services, with easy extensibility for + * adding your own relatively easily. It defaults to using TinyURL + * for shortening URLs. If you want to use some of the other services, you need + * to set some configuration options before actually shortening/lengthening + * URLs. I'd strongly suggest that you cache results using memcached, a local + * DB or whatever to avoid having to hit APIs etc every time you encounter a + * URL. + * + * Slinky supports shortening, and auto-detection (for lengthening URLs) + * using these services: + * - Bit.ly + * - Tr.im + * - TinyURL + * - Is.Gd + * - Fon.gs + * - Micurl.com + * - ur1.ca + * - Ptiturl + * - Tighturl + * - 2tu.us + * - Snipr / Snipurl / Snurl.com / Sn.im + * + * + * To use Slinky: + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * - Creates a new Slinky instance, will default to using TinyURL for ->short(); + * + * $slinky = new Slinky( 'http://dentedreality.com.au', new Slinky_Bitly() ); + * - Creates new Slinky, forces use of Bit.ly for ->short(); + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * echo $slinky->short(); + * - echos the short version of http://dentedreality.com.au/ (default to TinyURL) + * + * $slinky = new Slinky( 'http://tinyurl.com/jw5sh' ); + * echo $slinky->long(); + * - echos out the long version of http://tinyurl.com/jw5sh (which should be http://dentedreality.com.au/) + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * echo $slinky->long(); + * - Attempts to lengthen the URL, but will not auto-detect which service it is + * so it will just output the original URL. Useful for always attempting to + * lengthen any URL you come across (fails gracefully) + * + * $slinky = new Slinky( 'http://dentedreality.com.au/' ); + * $slinky->set_cascade( array( new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) ); + * echo $slinky->short(); + * - Uses the powerful cascade mode to make sure that we get a short URL from + * Tr.im, Is.Gd or TinyURL (in that order). + * + * See specific service class definitions below for examples of how to use them, + * as some services allow (or require) additional properties before you can use + * them (for authentication etc). + * + * To use a different service with Slinky, just create your own class and + * extend Slinky_Service(). Make sure you implement url_is_short(), url_is_long(), + * make_short() and make_long(). If you need to GET or POST a URL, you can use + * ->url_get() and ->url_post(), which your class will have inherited. +**/ +class Slinky { + var $url = false; + var $service = false; + var $cascade = false; + + function __construct( $url = false, $service = false ) { + $this->url = $url; + $this->service = $service; + } + + /** + * Specify which URL Service to use + * + * @param Slinky_Service $service Packaged or custom Service object + * @return void + */ + public function set_service( $service = false ) { + if ( is_object( $service ) ) { + $this->service = $service; + } + } + + /** + * If you pass an array of Slinky_Service objects to this method, they will + * be used in order to try to get a short URL, so if one fails, it will + * try the next and so on, until it gets a valid short URL, or it runs + * out of options. + * + * @param array $services List of Slinky_Service objects as an array + **/ + public function set_cascade( $services = false ) { + if ( !$services || !is_array( $services ) ) + return false; + + $this->cascade = $services; + } + + /** + * Guess the URL service to use from known domains of short URLs + * + * @param string $url + */ + public function set_service_from_url( $url = false ) { + if ( !$url ) + $url = $this->url; + + $host = parse_url( $url, PHP_URL_HOST ); + switch ( str_replace( 'www.', '', $host ) ) { + case 'bit.ly': + if ( class_exists( 'Slinky_Bitly' ) ) { + $this->service = new Slinky_Bitly(); + break; + } + case 'tr.im': + if ( class_exists( 'Slinky_Trim' ) ) { + $this->service = new Slinky_Trim(); + break; + } + case 'tinyurl.com': + if ( class_exists( 'Slinky_TinyURL' ) ) { + $this->service = new Slinky_TinyURL(); + break; + } + case 'is.gd': + if ( class_exists( 'Slinky_IsGd' ) ) { + $this->service = new Slinky_IsGd(); + break; + } + case 'fon.gs': + if ( class_exists( 'Slinky_Fongs' ) ) { + $this->service = new Slinky_Fongs(); + break; + } + case 'micurl.com': + if ( class_exists( 'Slinky_Micurl' ) ) { + $this->service = new Slinky_Micurl(); + break; + } + case 'ur1.ca': + if ( class_exists( 'Slinky_Ur1ca' ) ) { + $this->service = new Slinky_Ur1ca(); + break; + } + case 'ptiturl.com': + if ( class_exists( 'Slinky_PtitURL' ) ) { + $this->service = new Slinky_PtitURL(); + break; + } + case 'tighturl.com': + case '2tu.us': + if ( class_exists( 'Slinky_TightURL' ) ) { + $this->service = new Slinky_TightURL(); + break; + } + case 'snipr.com': + case 'snipurl.com': + case 'snurl.com': + case 'sn.im': + if ( class_exists( 'Slinky_Snipr' ) ) { + $this->service = new Slinky_Snipr(); + break; + } + default: + $this->service = new Slinky_Default(); + break; + } + } + + /** + * Take a long URL and make it short. Will avoid "re-shortening" a URL if it + * already seems to be short. + * + * @param string $url Optional URL to shorten, otherwise use $this->url + * @return The short version of the URL + */ + public function short( $url = false ) { + if ( $url ) + $this->url = $url; + + if ( !$this->service ) + $this->set_service( new Slinky_TinyURL() ); // Defaults to tinyurl because it doesn't require any configuration + + if ( !$this->cascade ) + $this->cascade = array( $this->service ); // Use a single service in cascade mode + + foreach ( $this->cascade as $service ) { + if ( $service->url_is_short( $this->url ) ) + return trim( $this->url ); // Identified as already short, using this service + + $response = trim( $service->make_short( $this->url ) ); + if ( $response && $this->url != $response ) + return trim( $response ); + } + + return $this->url; // If all else fails, just send back the URL we already know about + } + + /** + * Take a short URL and make it long ("resolve" it). + * + * @param string $url The short URL + * @return A long URL + */ + public function long( $url = false ) { + if ( $url ) + $this->url = $url; + + if ( !$this->service ) + $this->set_service_from_url(); + + if ( $this->service->url_is_long( $this->url ) ) + return trim( $this->url ); + + return trim( $this->service->make_long( $this->url ) ); + } +} + +/** + * Use this class to create a Service implementation for your own URL + * shortening service. Extend the class and customize methods to suit your + * service. Note that it is an "abstract" class, so there are certain methods + * which you *must* define. +**/ +abstract class Slinky_Service { + + /** + * Determine, based on the input URL, if it's already a short URL, from + * this particular service. e.g. a Bit.ly URL contains "bit.ly/" + **/ + abstract function url_is_short( $url ); + + /** + * Determine if this is a "long" URL (just means it hasn't been shortened) + * already. e.g. a no-Bit.ly URL would NOT contain "bit.ly/" + **/ + abstract function url_is_long( $url ); + + /** + * Handle taking the $url and converting it to a short URL via whatever + * means is provided at the remote service. + **/ + abstract function make_short( $url ); + + /** + * Return the long/expanded version of a URL via any API means available + * from this service. As a fallback, you might + * consider just following the URL and using SLINKY_FINAL_URL as the + * return method from a $this->url_get() call to find out. + * + * This one is optional for Services extending this class, if they don't + * then the following implementation will work on most services anyway. + **/ + public function make_long( $url ) { + return $this->url_get( $url, SLINKY_FINAL_URL ); + } + + /** + * Method for getting properties that you might need during the process + * of shortening/lengthening a URL (e.g. auth credentials) + **/ + public function get( $prop ) { + if ( empty( $this->$prop ) ) + return null; + + return $this->$prop; + } + + /** + * Method for setting properties that you might need during the process + * of shortening/lengthening a URL (e.g. auth credentials) + **/ + public function set( $prop, $val ) { + $this->$prop = $val; + } + + /** + * Internal helper for performing a GET request on a remote URL. + * + * @param string $url The URL to GET + * @param const $return The return method [ SLINKY_BODY | SLINKY_FINAL_URL | SLINKY_HEADERS ] + * @return Mixed, based on the $return var passed in. + **/ + protected function url_get( $url, $return = SLINKY_BODY ) { + $ch = curl_init( $url ); + curl_setopt( $ch, CURLOPT_USERAGENT, SLINKY_USER_AGENT ); + curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // Don't stress about SSL validity + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // Return the response, don't output it + curl_setopt( $ch, CURLOPT_TIMEOUT, SLINKY_TIMEOUT ); // Limit how long we'll wait for a response + curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); // Allow following of redirections + $r = curl_exec( $ch ); + if ( curl_errno( $ch ) ) { + return false; + } + + // Return whatever we were asked for + if ( SLINKY_FINAL_URL == $return ) + return curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL ); + else if ( SLINKY_BODY == $return ) + return $r; + + return false; + } + + /** + * Internal helper for performing a POST request on a remote URL. + * + * @param string $url The URL to POST to + * @param array $payload Array containing name/value pairs of the parameters to POST + * @param const $return The return method [ SLINKY_BODY | SLINKY_FINAL_URL | SLINKY_HEADERS ] + * @return Mixed, based on the $return var passed in. + **/ + protected function url_post( $url, $payload = array(), $return = SLINKY_BODY ) { + $ch = curl_init( $url ); + curl_setopt( $ch, CURLOPT_POST, true ); + curl_setopt( $ch, CURLOPT_POSTFIELDS, (array) $payload ); + curl_setopt( $ch, CURLOPT_USERAGENT, SLINKY_USER_AGENT ); + curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // Don't stress about SSL validity + curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // Return the response, don't output it + curl_setopt( $ch, CURLOPT_TIMEOUT, SLINKY_TIMEOUT ); // Limit how long we'll wait for a response + curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); // Allow following of redirections + $r = curl_exec( $ch ); + if ( curl_errno( $ch ) ) { + return false; + } + + // Return whatever we were asked for + if ( SLINKY_FINAL_URL == $return ) + return curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL ); + else if ( SLINKY_BODY == $return ) + return $r; + + return false; + } +} + +// This default service is used in cases when you try to do something based +// on auto-detection, but we can't detect anything. It will also resolve URLs +// to their "long" version by following all redirects. +class Slinky_Default extends Slinky_Service { + function url_is_short( $url ) { + return false; + } + + function url_is_long( $url ) { + return false; + } + + function make_short( $url ) { + return $url; + } +} + +// Implementation of TinyURL as a Slinky Service +class Slinky_TinyURL extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'tinyurl.com/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'tinyurl.com/' ); + } + + function make_short( $url ) { + return $this->url_get( 'http://tinyurl.com/api-create.php?url=' . urlencode( $url ) ); + } + + function make_long( $url ) { + $bits = parse_url( $url ); + $result = $this->url_get( 'http://tinyurl.com/preview.php?num=' . substr( $bits['path'], 1 ) ); + if ( preg_match('//is', $result, $matches ) ) + return $matches[1]; + else + return $url; + } +} + +// Implementation of Bit.ly as a Slinky Service +/* +To use Bit.ly, you MUST set your login and apiKey for the service first, e.g. + +$bitly = new Slinky_Bitly(); +$bitly->set( 'login', 'bitly_login' ); +$bitly->set( 'apiKey', 'bitly_apiKey' ); + +$slinky = new Slinky( $url, $bitly ); +echo $slinky->short(); + +You could also do this if the URL was already a bit.ly URL and you +were going to make it longer, since Bitly is supported for auto-detection: + +$slinky = new Slinky( $url ); +$slinky->set_service_from_url(); +$slinky->service->set( 'login', 'bitly_login' ); +$slinky->service->set( 'apiKey', 'bitly_apiKey' ); +echo $slinky->long(); + +*/ +class Slinky_Bitly extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'bit.ly/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'bit.ly/' ); + } + + function make_short( $url ) { + // Can't do anything unless these 2 properties are set first + if ( !$this->get( 'login' ) || !$this->get( 'apiKey' ) ) + return $url; + + $result = $this->url_post( 'http://api.bit.ly/shorten?version=2.0.1&format=json&login=' . $this->get( 'login' ) . '&apiKey=' . $this->get( 'apiKey' ) . '&longUrl=' . urlencode( $url ) ); + $result = json_decode( $result ); + if ( !$result->errorCode ) { + foreach ( $result->results as $detail ) { + return $detail->shortUrl; + } + } else { + return false; + } + } + + function make_long( $url ) { + // Can't do anything unless these 2 properties are set first + if ( !$this->get( 'login' ) || !$this->get( 'apiKey' ) ) + return $url; + + $result = $this->url_post( 'http://api.bit.ly/expand?version=2.0.1&format=json&login=' . $this->get( 'login' ) . '&apiKey=' . $this->get( 'apiKey' ) . '&shortUrl=' . urlencode( $url ) ); + $result = json_decode( $result ); + if ( !$result->errorCode ) { + foreach ( $result->results as $detail ) { + return $detail->longUrl; + } + } else { + return false; + } + } +} + +// Implementation of Tr.im as a Slinky Service +/* +When using Tr.im, you MAY optionally set your username and password to tie +URLs to your account, e.g. + +$trim = new Slinky_Trim(); +$trim->set( 'username', 'trim_username' ); +$trim->set( 'password', 'trim_password' ); + +$slinky = new Slinky( $url, $trim ); +echo $slinky->short(); + +You could also do this if the URL was already a tr.im URL and you +were going to make it longer, since Tr.im is supported for auto-detection: + +$slinky = new Slinky( $url ); +$slinky->set_service_from_url(); +echo $slinky->long(); + +*/ +class Slinky_Trim extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'tr.im/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'tr.im/' ); + } + + function make_short( $url ) { + $url = 'http://api.tr.im/api/trim_simple?url=' . urlencode( $url ); + + if ( $this->get( 'username' ) && $this->get( 'password' ) ) + $url .= '&username=' . urlencode( $this->get( 'username' ) ) . '&password=' . urlencode( $this->get( 'password' ) ); + + return $this->url_get( $url ); + } + + function make_long( $url ) { + $bits = parse_url( $url ); + $result = $this->url_get( 'http://api.tr.im/api/trim_destination.json?trimpath=' . substr( $bits['path'], 1 ) ); + $result = json_decode($result); + if ( 'OK' == $result->status->result ) + return $result->destination; + else + return $url; + } +} + +// Implementation of Is.Gd as a Slinky Service +class Slinky_IsGd extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'is.gd/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'is.gd/' ); + } + + function make_short( $url ) { + $response = $this->url_get( 'http://is.gd/api.php?longurl=' . urlencode( $url ) ); + if ( 'error' == substr( strtolower( $response ), 0, 5 ) ) + return false; + else + return $response; + } +} + +// Fon.gs +class Slinky_Fongs extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'fon.gs/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'fon.gs/' ); + } + + function make_short( $url ) { + $response = $this->url_get( 'http://fon.gs/create.php?url=' . urlencode( $url ) ); + if ( 'OK:' == substr( $response, 0, 3 ) ) + return str_replace( 'OK: ', '', $response ); + else + return $url; + } +} + +// Micu.rl +class Slinky_Micurl extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'micurl.com/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'micurl.com/' ); + } + + function make_short( $url ) { + $result = $this->url_get( 'http://micurl.com/api.php?url=' . urlencode( $url ) ); + if ( 1 != $result && 2 != $result ) + return 'http://micurl.com/' . $result; + else + return $url; + } +} + +// ur1.ca +class Slinky_Ur1ca extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'ur1.ca/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'ur1.ca/' ); + } + + function make_short( $url ) { + $result = $this->url_post( 'http://ur1.ca/', array( 'longurl' => $url ) ); + if ( preg_match( '/

Your ur1 is: /', $result, $matches ) ) + return $matches[1]; + else + return $url; + } +} + +// PtitURL.com +class Slinky_PtitURL extends Slinky_Service { + function url_is_short( $url ) { + return stristr( $url, 'ptiturl.com/' ); + } + + function url_is_long( $url ) { + return !stristr( $url, 'ptiturl.com/' ); + } + + function make_short( $url ) { + $result = $this->url_get( 'http://ptiturl.com/index.php?creer=oui&url=' . urlencode( $url ) ); + if ( preg_match( '/

]+)\'?>/', $result, $matches ) )
+			return $matches[1];
+		else
+			return $url;
+	}
+}
+
+// Tighturl.com
+class Slinky_TightURL extends Slinky_Service {
+	function url_is_short( $url ) {
+		return stristr( $url, 'tighturl.com/' )
+				|| stristr( $url, '2tu.us/' );
+	}
+	
+	function url_is_long( $url ) {
+		return !stristr( $url, 'tighturl.com/' )
+				&& !stristr( $url, '2tu.us/' );
+	}
+	
+	function make_short( $url ) {
+		$response = $this->url_get( 'http://tighturl.com/?save=y&url=' . urlencode( $url ) );
+		if ( preg_match( '/Your tight URL is: /', $response, $matches ) ) {
+			return $matches[1];
+		} else {
+			return $url;
+		}
+	}
+}
+
+// Snipr for Slinky
+/*
+To use Snipr, you MUST set your user_id and API (key) for the service first, e.g.
+
+$snipr = new Slinky_Snipr();
+$snipr->set( 'user_id', 'Snipr User ID' );
+$snipr->set( 'API', 'Snipr API Key' );
+
+$slinky = new Slinky( $url, $snipr );
+echo $slinky->short();
+
+NOTE: Snipr requires the SimpleXML extension to be installed for lengthening URLs
+*/
+class Slinky_Snipr extends Slinky_Service {
+	// Snipurl, Snurl, Snipr, Sn.im
+	function url_is_short( $url ) {
+		return stristr( $url, 'snipr.com/' ) || stristr( $url, 'snipurl.com/' ) || stristr( $url, 'snurl.com/' ) || stristr( $url, 'sn.im/' );
+	}
+	
+	function url_is_long( $url ) {
+		return !stristr( $url, 'snipr.com/' ) || !stristr( $url, 'snipurl.com/' ) || !stristr( $url, 'snurl.com/' ) || !stristr( $url, 'sn.im/' );
+	}
+	
+	function make_short( $url ) {
+		if ( !$this->get( 'user_id' ) || !$this->get( 'API' ) )
+			return $url;
+		
+		$response = $this->url_post( 'http://snipr.com/site/getsnip', array( 'sniplink' => urlencode( $url ), 'snipuser' => $this->get( 'user_id'), 'snipapi' => $this->get( 'API' ), 'snipformat' => 'simple' ) );
+		if ( 'ERROR' != substr( $response, 0, 5 ) )
+			return $response;
+		else
+			return $url;
+	}
+}
+
+// If you're testing things out, http://dentedreality.com.au/ should convert to:
+// - http://tinyurl.com/jw5sh
+// - http://bit.ly/hEkAD
+// - http://tr.im/sk1H
+// - http://is.gd/1yJ81
+// - http://fon.gs/tc1p8c
+// - http://micurl.com/qen3uub
+// - http://ur1.ca/7dcd
+// - http://ptiturl.com/?id=bac8fb
+// - http://tighturl.com/kgd
+// - http://snipr.com/nbbw3
+// 
+// $slinky = new Slinky( 'http://dentedreality.com.au/' );
+// echo $slinky->short();
diff --git a/addon/statusnet/statusnet.css b/addon/statusnet/statusnet.css
new file mode 100644
index 00000000..4e27b093
--- /dev/null
+++ b/addon/statusnet/statusnet.css
@@ -0,0 +1,67 @@
+
+
+#statusnet-avatar {
+	float: left;
+	width: 48px;
+	height: 48px;
+	padding: 2px;
+}
+#statusnet-info-block {
+	height: 52px;
+	vertical-align: middle;
+}
+#statusnet-disconnect-label {
+	float: left;
+	width: 200px;
+	margin-bottom: 25px;
+}
+
+#statusnet-disconnect {
+	float: left;
+}
+#statusnet-enable-label {
+	float: left;
+	width: 200px;
+	margin-bottom: 5px;
+}
+
+#statusnet-checkbox {
+	float: left;
+}
+#statusnet-pin-label {
+	float: left;
+	width: 200px;
+	margin-bottom: 25px;
+}
+#statusnet-pin {
+	float: left;
+}
+
+
+#statusnet-consumerkey-label {
+	float: left;
+	width: 200px;
+	margin-bottom: 8px;
+}
+#statusnet-consumerkey {
+	float: left;
+	margin-bottom: 8px;
+}
+#statusnet-consumersecret-label {
+	float: left;
+	width: 200px;
+	margin-bottom: 8px;
+}
+#statusnet-consumersecret {
+	float: left;
+	margin-bottom: 8px;
+}
+#statusnet-baseapi-label {
+	float: left;
+	width: 200px;
+	margin-bottom: 25px;
+}
+#statusnet-baseapi {
+	float: left;
+	margin-bottom: 8px;
+}
diff --git a/addon/statusnet/statusnet.php b/addon/statusnet/statusnet.php
new file mode 100644
index 00000000..b1d33054
--- /dev/null
+++ b/addon/statusnet/statusnet.php
@@ -0,0 +1,243 @@
+config['system']['addon']
+ *     setting. After this, your user can configure their Twitter account settings
+ *     from "Settings -> Plugin Settings".
+ *
+ *     Requirements: PHP5, curl [Slinky library]
+ *
+ *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
+ */
+
+/*   __TODO__
+ *
+ *   - what about multimedia content?
+ *     so far we just strip HTML tags from the message
+ */
+
+
+/***
+ * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
+ * installation abroad. Basically it's only make the API path variable and be happy.
+ *
+ * Thank you guys for the Twitter compatible API!
+ */
+require_once('addon/twitter/twitteroauth.php');
+class StatusNetOAuth extends TwitterOAuth {
+    function get_maxlength() {
+        $config = $this->get($this->host . 'statusnet/config.json');
+        return $config->site->textlimit;
+    }
+    function accessTokenURL()  { return $this->host.'oauth/access_token'; }
+    function authenticateURL() { return $this->host.'oauth/authenticate'; } 
+    function authorizeURL() { return $this->host.'oauth/authorize'; }
+    function requestTokenURL() { return $this->host.'oauth/request_token'; }
+    function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
+        parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
+        $this->host = $apipath;
+    }
+}
+
+function statusnet_install() {
+	//  we need some hooks, for the configuration and for sending tweets
+	register_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
+	register_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
+	register_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
+	logger("installed statusnet");
+}
+
+
+function statusnet_uninstall() {
+	unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
+	unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
+	unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
+}
+
+function statusnet_settings_post ($a,$post) {
+	if(! local_user())
+	    return;
+	if (isset($_POST['statusnet-disconnect'])) {
+	    /***
+	     * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
+	     * TODO can we revoke the access tokens at Twitter and do we need to do so?
+	     */
+            del_pconfig( local_user(), 'statusnet', 'consumerkey'  );
+	    del_pconfig( local_user(), 'statusnet', 'consumersecret' );
+	    del_pconfig( local_user(), 'statusnet', 'post' );
+            del_pconfig( local_user(), 'statusnet', 'oauthtoken' );
+            del_pconfig( local_user(), 'statusnet', 'oauthsecret' );
+            del_pconfig( local_user(), 'statusnet', 'baseapi' );
+	} else {
+        if (isset($_POST['statusnet-consumersecret'])) {
+            set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
+            set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
+            set_pconfig(local_user(), 'statusnet', 'baseapi', $_POST['statusnet-baseapi']);
+            header('Location: '.$a->get_baseurl().'/settings/addon');
+        } else {
+	if (isset($_POST['statusnet-pin'])) {
+	    //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
+	    logger('got a StatusNet security code');
+            $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
+	    $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
+	    $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
+	    //  the token and secret for which the PIN was generated were hidden in the settings
+	    //  form as token and token2, we need a new connection to Twitter using these token
+	    //  and secret to request a Access Token with the PIN
+	    $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
+	    $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
+	    //  ok, now that we have the Access Token, save them in the user config
+ 	    set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
+	    set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
+            set_pconfig(local_user(),'statusnet', 'post', 1);
+            //  reload the Addon Settings page, if we don't do it see Bug #42
+            header('Location: '.$a->get_baseurl().'/settings/addon');
+	} else {
+	    //  if no PIN is supplied in the POST variables, the user has changed the setting
+	    //  to post a tweet for every new __public__ posting to the wall
+	    set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
+	}}}
+}
+function statusnet_settings(&$a,&$s) {
+        if(! local_user())
+                return;
+        $a->page['htmlhead'] .= '' . "\r\n";
+	/***
+	 * 1) Check that we have a base api url and a consumer key & secret
+	 * 2) If no OAuthtoken & stuff is present, generate button to get some
+	 * 3) Checkbox for "Send public notices (respect size limitation)
+	 */
+        $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
+	$ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
+	$csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
+	$otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
+	$osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
+        $enabled = get_pconfig(local_user(), 'statusnet', 'post');
+	$checked = (($enabled) ? ' checked="checked" ' : '');
+	$s .= '

'.t('StatusNet Posting Settings').'

'; + + if ( (!$ckey) && (!$csecret) ) { + /*** + * no consumer keys + */ + $s .= '

'.t('No consumer key pair for StatusNet found. Register your Friendika Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.
Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendika installation at your favorited StatusNet installation.').'

'; + $s .= '
'; + $s .= ''; + $s .= '
'; + $s .= ''; + $s .= '
'; + $s .= ''; + $s .= '
'; + $s .= '
'; + $s .= '
'; + } else { + /*** + * ok we have a consumer key pair now look into the OAuth stuff + */ + if ( (!$otoken) && (!$osecret) ) { + /*** + * the user has not yet connected the account to statusnet + * get a temporary OAuth key/secret pair and display a button with + * which the user can request a PIN to connect the account to a + * account at statusnet + */ + $connection = new StatusNetOAuth($api, $ckey, $csecret); + $request_token = $connection->getRequestToken('oob'); + $token = $request_token['oauth_token']; + /*** + * make some nice form + */ + $s .= '

'.t('To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your public posts will be posted to StatusNet.').'

'; + $s .= '
'.t('Log in with StatusNet').''; + $s .= '
'; + $s .= ''; + $s .= ''; + $s .= ''; + $s .= ''; + $s .= '
'; + $s .= '
'; + } else { + /*** + * we have an OAuth key / secret pair for the user + * so let's give a chance to disable the postings to statusnet + */ + $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret); + $details = $connection->get('account/verify_credentials'); + $s .= '

'.t('Currently connected to: ').''.$details->screen_name.'
'.$details->description.'

'; + $s .= '

'.t('If enabled all your public postings will be posted to the associated StatusNet account as well.').'

'; + $s .= '
'; + $s .= ''; + $s .= ''; + $s .= '
'; + $s .= '
'; + $s .= ''; + $s .= ''; + $s .= '
'; + $s .= '
'; + } + } + $s .= '
'; +} + + +function statusnet_post_hook(&$a,&$b) { + + /** + * Post to statusnet + */ + + logger('StatusNet post invoked'); + + if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) { + + load_pconfig(local_user(), 'statusnet'); + + $api = get_pconfig(local_user(), 'statusnet', 'baseapi'); + $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' ); + $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' ); + $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' ); + $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' ); + + if($ckey && $csecret && $otoken && $osecret) { + + $statusnet_post = get_pconfig(local_user(),'statusnet','post'); + + if($statusnet_post) { + require_once('include/bbcode.php'); + $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret); + $max_char = $dent->get_maxlength(); // max. length for a dent + $msg = strip_tags(bbcode($b['body'])); + if ( strlen($msg) > $max_char) { + $shortlink = ""; + require_once('addon/statusnet/slinky.php'); + // post url = base url + /display/ + owner + post id + // we construct this from the Owner link and replace + // profile by display - this will cause an error when + // /profile/ is in the owner url twice but I don't + // think this will be very common... + $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id']; + $slinky = new Slinky( $posturl ); + // setup a cascade of shortening services + // try to get a short link from these services + // in the order ur1.ca, trim, id.gd, tinyurl + $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) ); + $shortlink = $slinky->short(); + // the new message will be shortened such that "... $shortlink" + // will fit into the character limit + $msg = substr($msg, 0, $max_char-strlen($shortlink)-4); + $msg .= '... ' . $shortlink; + } + // and now tweet it :-) + $dent->post('statuses/update', array('status' => $msg)); + } + } + } +} + diff --git a/addon/statusnet/twitteroauth.php b/addon/statusnet/twitteroauth.php new file mode 100644 index 00000000..cc771391 --- /dev/null +++ b/addon/statusnet/twitteroauth.php @@ -0,0 +1,245 @@ +http_status; } + function lastAPICall() { return $this->last_api_call; } + + /** + * construct TwitterOAuth object + */ + function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) { + $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); + $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); + if (!empty($oauth_token) && !empty($oauth_token_secret)) { + $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret); + } else { + $this->token = NULL; + } + } + + + /** + * Get a request_token from Twitter + * + * @returns a key/value array containing oauth_token and oauth_token_secret + */ + function getRequestToken($oauth_callback = NULL) { + $parameters = array(); + if (!empty($oauth_callback)) { + $parameters['oauth_callback'] = $oauth_callback; + } + $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters); + $token = OAuthUtil::parse_parameters($request); + $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); + return $token; + } + + /** + * Get the authorize URL + * + * @returns a string + */ + function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) { + if (is_array($token)) { + $token = $token['oauth_token']; + } + if (empty($sign_in_with_twitter)) { + return $this->authorizeURL() . "?oauth_token={$token}"; + } else { + return $this->authenticateURL() . "?oauth_token={$token}"; + } + } + + /** + * Exchange request token and secret for an access token and + * secret, to sign API calls. + * + * @returns array("oauth_token" => "the-access-token", + * "oauth_token_secret" => "the-access-secret", + * "user_id" => "9436992", + * "screen_name" => "abraham") + */ + function getAccessToken($oauth_verifier = FALSE) { + $parameters = array(); + if (!empty($oauth_verifier)) { + $parameters['oauth_verifier'] = $oauth_verifier; + } + $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters); + $token = OAuthUtil::parse_parameters($request); + $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); + return $token; + } + + /** + * One time exchange of username and password for access token and secret. + * + * @returns array("oauth_token" => "the-access-token", + * "oauth_token_secret" => "the-access-secret", + * "user_id" => "9436992", + * "screen_name" => "abraham", + * "x_auth_expires" => "0") + */ + function getXAuthToken($username, $password) { + $parameters = array(); + $parameters['x_auth_username'] = $username; + $parameters['x_auth_password'] = $password; + $parameters['x_auth_mode'] = 'client_auth'; + $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters); + $token = OAuthUtil::parse_parameters($request); + $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']); + return $token; + } + + /** + * GET wrapper for oAuthRequest. + */ + function get($url, $parameters = array()) { + $response = $this->oAuthRequest($url, 'GET', $parameters); + if ($this->format === 'json' && $this->decode_json) { + return json_decode($response); + } + return $response; + } + + /** + * POST wrapper for oAuthRequest. + */ + function post($url, $parameters = array()) { + $response = $this->oAuthRequest($url, 'POST', $parameters); + if ($this->format === 'json' && $this->decode_json) { + return json_decode($response); + } + return $response; + } + + /** + * DELETE wrapper for oAuthReqeust. + */ + function delete($url, $parameters = array()) { + $response = $this->oAuthRequest($url, 'DELETE', $parameters); + if ($this->format === 'json' && $this->decode_json) { + return json_decode($response); + } + return $response; + } + + /** + * Format and sign an OAuth / API request + */ + function oAuthRequest($url, $method, $parameters) { + if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) { + $url = "{$this->host}{$url}.{$this->format}"; + } + $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters); + $request->sign_request($this->sha1_method, $this->consumer, $this->token); + switch ($method) { + case 'GET': + return $this->http($request->to_url(), 'GET'); + default: + return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata()); + } + } + + /** + * Make an HTTP request + * + * @return API results + */ + function http($url, $method, $postfields = NULL) { + $this->http_info = array(); + $ci = curl_init(); + /* Curl settings */ + curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); + curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); + curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); + curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); + curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); + curl_setopt($ci, CURLOPT_HEADER, FALSE); + + switch ($method) { + case 'POST': + curl_setopt($ci, CURLOPT_POST, TRUE); + if (!empty($postfields)) { + curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); + } + break; + case 'DELETE': + curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); + if (!empty($postfields)) { + $url = "{$url}?{$postfields}"; + } + } + + curl_setopt($ci, CURLOPT_URL, $url); + $response = curl_exec($ci); + $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); + $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); + $this->url = $url; + curl_close ($ci); + return $response; + } + + /** + * Get the header info to store. + */ + function getHeader($ch, $header) { + $i = strpos($header, ':'); + if (!empty($i)) { + $key = str_replace('-', '_', strtolower(substr($header, 0, $i))); + $value = trim(substr($header, $i + 2)); + $this->http_header[$key] = $value; + } + return strlen($header); + } +} From b8629a03182410abc0463865d29774e42e41810d Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Tue, 8 Feb 2011 19:04:39 +0100 Subject: [PATCH 08/36] added README files for the piwik, twitter and statusnet addon --- addon/piwik/README | 43 +++++++++++++++++++++++ addon/statusnet/README | 75 ++++++++++++++++++++++++++++++++++++++++ addon/twitter/README | 77 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 195 insertions(+) create mode 100644 addon/piwik/README create mode 100644 addon/statusnet/README create mode 100644 addon/twitter/README diff --git a/addon/piwik/README b/addon/piwik/README new file mode 100644 index 00000000..20b78b51 --- /dev/null +++ b/addon/piwik/README @@ -0,0 +1,43 @@ +____ Piwik Plugin ____ +by Tobias Diekershoff + tobias.diekershoff(at)gmx.net + +This addon allows you to embed the code necessary for the FLOSS webanalytics +tool piwik into the Friendika pages. + +Online version of this Document: http://ur1.ca/35m2x + +___ Requirements ___ + +To use this plugin you need a "piwik":http://piwik.org installation. + +___ Where to find ___ + +In the Friendika git repository @/addon/piwik/piwik.php@ and a CSS file for +styling the opt-out notice. + +___ Configuration ___ + +Open the .htconfig.php file and add "piwik" to the list of activated addons. + $a->config['system']['addon'] = "piwik, ..." +You have to add 3 more configuration variables for the addon: + +$a->config['piwik']['baseurl'] = 'example.com/piwik/'; +$a->config['piwik']['sideid'] = '1'; +$a->config['piwik']['optout'] = true; + +The *baseurl* points to your piwik installation. Use the absolute path, +remember trailing slashes but ignore the protocol (http/s) part of the URL. +Change the *sideid* parameter to whatever ID you want to use for tracking your +Friendika installation. The *optout* parameter (true|false) defines whether or +not a short notice about the utilization of piwik will be displayed on every +page of your Friendika site (at the bottom of the page with some spacing to the +other content). Part of the note is a link that allows the visitor to set an +_opt-out_ cookie which will prevent visits from that user be tracked by piwik. + +Currently the optional notice states the following: + + This website is tracked using the Piwik analytics tool. If you do not want + that your visits are logged this way you can set a cookie to prevent Piwik + from tracking further visits of the site (opt-out). + diff --git a/addon/statusnet/README b/addon/statusnet/README new file mode 100644 index 00000000..8d5e2729 --- /dev/null +++ b/addon/statusnet/README @@ -0,0 +1,75 @@ +____ StatusNet Plugin ____ +by Tobias Diekershoff + tobias.diekershoff(at)gmx.net + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +!! This addon is currently in under development. If you have any problem !! +!! with it, please contact the Author. !! +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +With this addon to Friendika you can give your user the possibility to post +their public messages to any StatusNet instance like identi.ca for example. The +messages will be strapped their rich context and shortened to to the character +limit of the StatusNet instance in question if necessary. If shortening of the +message was performed a link will be added to the notice pointing to the +original message on your server. + +There is a similar plugin to forward public messages to Twitter Twitter Plugin. + +Online version of this document: http://ur1.ca/35mpb + +___ Requirements ___ + +Due to the distributed nature of the StatusNet network, each user who wishes to +forward public messages to a StatusNet account has get the OAuth credentials +for themselves, which makes this addon a little bit more user unfriendly then +the Twitter Plugin is. Nothing to geeky though! + +The inclusion of a shorturl for the original posting in cases when the message +was longer then the maximal allowed notice length requires it, that you have +PHP5+ and curl on your server. +Where to find + +In the Friendika git repository /addon/statusnet/, this directory contains all +required PHP files (including the Twitter OAuth library [1] by Abraham Williams, +MIT licensed and the Slinky library [2] by Beau Lebens, BSD license), a CSS file +for styling of the user configuration and an image to Sign in with StatusNet. + +[1] https://github.com/abraham/twitteroauth +[2] http://dentedreality.com.au/projects/slinky + +___ Configuration ___ + +__ Global Configuration __ + +To activate this addon add statusnet to the list of active addons in your +.htconfig.php file + $a->config['system']['addon'] = "statusnet, ...". + +__ User Configuration __ + +When the addon is activated the user has to aquire three things in order to +connect to the StatusNet account of choice. + * the base URL for the StatusNet API, for identi.ca this is + https://identi.ca/api/ + * OAuth Consumer key & secret + +To get the OAuth Consumer key pair the user has to (a) ask her Friendika admin +if a pair already exists or (b) has to register the Friendika server as a +client application on the StatusNet server. This can be done from the account +settings under "Connect -> Connections -> Register an OAuth client application +-> Register new application". + +During the registration of the OAuth client remember the following: + * there is no callback url + * register a desktop client + * with read & write access + * the Source URL should be the URL of your Friendika server + +After the required credentials for the application are stored in the +configuration you have to actually connect your Friendika account with +StatusNet. To do so follow the Sign in with StatusNet button, allow the access +and copy the security code into the addon configuration. Friendika will then +try to acquire the final OAuth credentials from the API, if successful the +addon settings will allow you to select to post your public messages to your +StatusNet account. diff --git a/addon/twitter/README b/addon/twitter/README new file mode 100644 index 00000000..a49fa5cd --- /dev/null +++ b/addon/twitter/README @@ -0,0 +1,77 @@ +____ Twitter Plugin ____ +By Tobias Diekershoff + tobias.diekershoff(at)gmx.net + +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +!! This addon is currently in under development. If you have any problem !! +!! with it, please contact the Author. !! +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +With this addon to Friendika you can give your user the possibility to post +their *public* messages to Twitter. The messages will be strapped their rich +context and shortened to 140 characters length if necessary. If shortening of +the message was performed a link will be added to the Tweet pointing to the +original message on your server. + +There is a similar addon for forwarding public messages to +"StatusNet":http://status.net [[StatusNet Plugin]]. + +Online version of this document: http://ur1.ca/35mml + +___ Requirements ___ + +To use this plugin you have to register your Friendika instance as an +_client application_ for Twitter with _read and write_ access, we do not intend +to use Twitter for login. The registration can be done at twitter.com/apps +and you need to have a Twitter account to do so. + +After you registered the application you get an OAuth consumer key / secret +pair that identifies your app, you will need them for configuration. + +The inclusion of a shorturl for the original posting in cases when the +message was longer then 140 characters requires it, that you have *PHP5+* and +*curl* on your server. + +___ Where to find ___ + +In the Friendika git repository /addon/twitter/, this directory contains +all required PHP files (including the Twitter OAuth library [1] by Abraham +Williams, MIT licensed and the Slinky library [2] by Beau Lebens, BSD license), +a CSS file for styling of the user configuration and an image to _Sign in with +Twitter_. + +[1] https://github.com/abraham/twitteroauth +[2] http://dentedreality.com.au/projects/slinky/ + +___ Configuration ___ + +__ Global Configuration __ + +To activate this addon add @twitter@ to the list of active addons in your +.htconfig.php file + $a->config['system']['addon'] = "twitter, ..." +Afterwards you need to add your OAuth consumer key / secret pair to it by +adding the following to lines + +$a->config['twitter']['consumerkey'] = 'your consumer KEY here'; +$a->config['twitter']['consumersecret'] = 'your consumer SECRET here'; + +When this is done your user can now configure their Twitter connection at +"Settings -> Addon Settings" and enable the forwarding of their *public* +messages to Twitter. + +__ User Configuration __ + +When the OAuth consumer informations are correctly placed into the +configuration file and a user visits the "Addon Settings" page they can now +connect to Twitter. To do so one has to follow the _Sign in with Twitter_ +button (the page will be opened in a new browser window/tab) and get a PIN from +Twitter. This PIN has to be entered on the settings page. After submitting the +PIN the plugin will get OAuth credentials identifying this user from the +Friendika account. + +If this first step was successful the Twitter configuration will be changed +on the "Addon Settings" page displaying two check boxes. One to enable/disable +the forwarding of *all public* postings to Twitter and one to clear the +personal configuration from the Twitter credentials. + From 766c4778cb0a678ef7f55e56cbd11497a73ae6cb Mon Sep 17 00:00:00 2001 From: Friendika Date: Tue, 8 Feb 2011 15:08:07 -0800 Subject: [PATCH 09/36] modify tag handling and replies to stnet --- mod/item.php | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/mod/item.php b/mod/item.php index 38ef580a..2264ea5b 100644 --- a/mod/item.php +++ b/mod/item.php @@ -25,6 +25,7 @@ function item_post(&$a) { $parent = ((x($_POST,'parent')) ? intval($_POST['parent']) : 0); $parent_item = null; + $parent_contact = null; if($parent) { $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", @@ -35,6 +36,14 @@ function item_post(&$a) { goaway($a->get_baseurl() . "/" . $_POST['return'] ); } $parent_item = $r[0]; + if($parent_item['contact-id'] && $uid) { + $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", + intval($parent_item['contact-id']), + intval($uid) + ); + if(count($r)) + $parent_contact = $r[0]; + } } $profile_uid = ((x($_POST,'profile_uid')) ? intval($_POST['profile_uid']) : 0); @@ -185,8 +194,13 @@ function item_post(&$a) { $str_tags = ''; $inform = ''; + $tags = get_tags($body); + if(($parent_contact) && ($parent_contact['network'] === 'stat') && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) { + $body = '@' . $parent_contact['nick'] . ' ' . $body; + $tags[] = '@' . $parent_contact['nick']; + } if(count($tags)) { foreach($tags as $tag) { @@ -199,6 +213,7 @@ function item_post(&$a) { continue; } if(strpos($tag,'@') === 0) { + $stat = false; $name = substr($tag,1); if((strpos($name,'@')) || (strpos($name,'http://'))) { $newname = $name; @@ -231,6 +246,8 @@ function item_post(&$a) { ); } if(count($r)) { + if($r[0]['network'] === 'stat') + $stat = true; $profile = $r[0]['url']; $newname = $r[0]['name']; if(strlen($inform)) @@ -239,7 +256,8 @@ function item_post(&$a) { } } if($profile) { - $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname . '[/url]', $body); + if(! $stat) + $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname . '[/url]', $body); $profile = str_replace(',','%2c',$profile); if(strlen($str_tags)) $str_tags .= ','; @@ -249,6 +267,8 @@ function item_post(&$a) { } } + + $wall = 0; if($post_type === 'wall' || $post_type === 'wall-comment') $wall = 1; From f70a0b028288fa13c64f1ffaa310765a95347dac Mon Sep 17 00:00:00 2001 From: Friendika Date: Tue, 8 Feb 2011 18:44:30 -0800 Subject: [PATCH 10/36] more graceful handling of some statusnet followups --- boot.php | 24 +++++++++++++++++++++--- database.sql | 2 +- include/items.php | 6 ++++-- mod/follow.php | 27 ++++++++++++++++++++++++--- mod/item.php | 12 +++++++----- mod/salmon.php | 2 +- update.php | 7 +++++++ 7 files changed, 65 insertions(+), 15 deletions(-) diff --git a/boot.php b/boot.php index 7fbd2a6f..8492b8be 100644 --- a/boot.php +++ b/boot.php @@ -2,7 +2,7 @@ set_time_limit(0); -define ( 'BUILD_ID', 1037 ); +define ( 'BUILD_ID', 1038 ); define ( 'FRIENDIKA_VERSION', '2.10.0905' ); define ( 'DFRN_PROTOCOL_VERSION', '2.1' ); @@ -1378,10 +1378,12 @@ function webfinger($s) { logger('webfinger: lrdd template: ' . $tpl); if(strlen($tpl)) { $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl); + logger('webfinger: pxrd: ' . $pxrd); $links = fetch_xrd_links($pxrd); if(! count($links)) { // try with double slashes $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl); + logger('webfinger: pxrd: ' . $pxrd); $links = fetch_xrd_links($pxrd); } return $links; @@ -1453,6 +1455,7 @@ function fetch_lrdd_template($host) { $tpl = ''; $url = 'http://' . $host . '/.well-known/host-meta' ; $links = fetch_xrd_links($url); +logger('template: ' . print_r($links,true)); if(count($links)) { foreach($links as $link) if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd') @@ -1479,15 +1482,30 @@ function fetch_xrd_links($url) { $h = simplexml_load_string($xml); $arr = convert_xml_element_to_array($h); + $links = array(); + if(isset($arr['xrd']['link'])) { $link = $arr['xrd']['link']; if(! isset($link[0])) $links = array($link); else $links = $link; - return $links; } - return array(); + if(isset($arr['xrd']['alias'])) { + $alias = $arr['xrd']['alias']; + if(! isset($alias[0])) + $aliases = array($alias); + else + $aliases = $alias; + foreach($aliases as $alias) { + $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias); + } + } + + logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA); + + return $links; + }} // Convert an ACL array to a storable string diff --git a/database.sql b/database.sql index 83e0e4b6..34b80797 100644 --- a/database.sql +++ b/database.sql @@ -64,7 +64,7 @@ CREATE TABLE IF NOT EXISTS `contact` ( `issued-id` char(255) NOT NULL, `dfrn-id` char(255) NOT NULL, `url` char(255) NOT NULL, - `lrdd` char(255) NOT NULL, + `alias` char(255) NOT NULL, `pubkey` text NOT NULL, `prvkey` text NOT NULL, `request` text NOT NULL, diff --git a/include/items.php b/include/items.php index cffd13a0..b5bdd783 100644 --- a/include/items.php +++ b/include/items.php @@ -1128,15 +1128,16 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) { } if(($is_reply) && is_array($contact)) { - + // Have we seen it? If not, import it. $item_id = $item->get_id(); - + $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($item_id), intval($importer['uid']) ); + // FIXME update content if 'updated' changes if(count($r)) { $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow'); @@ -1155,6 +1156,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) { } continue; } + $datarray = get_atom_elements($feed,$item); $force_parent = false; if($contact['network'] === 'stat') { diff --git a/mod/follow.php b/mod/follow.php index 8c1dc348..eaee7d5a 100644 --- a/mod/follow.php +++ b/mod/follow.php @@ -15,7 +15,7 @@ function follow_post(&$a) { $email_conversant = false; if($url) { - $links = lrdd($url); + $links = @lrdd($url); if(count($links)) { foreach($links as $link) { if($link['@attributes']['rel'] === NAMESPACE_DFRN) @@ -30,6 +30,26 @@ function follow_post(&$a) { $profile = $link['@attributes']['href']; } + + // Status.Net can have more than one profile URL. We need to match the profile URL + // to a contact on incoming messages to prevent spam, and we won't know which one + // to match. So in case of two, one of them is stored as an alias. Only store URL's + // and not webfinger user@host aliases. If they've got more than two non-email style + // aliases, let's hope we're lucky and get one that matches the feed author-uri because + // otherwise we're screwed. + + foreach($links as $link) { + if($link['@attributes']['rel'] === 'alias') { + if(strpos($link['@attributes']['href'],'@') === false) { + if(isset($profile)) { + if($link['@attributes']['href'] !== $profile) + $alias = $link['@attributes']['href']; + } + else + $profile = $link['@attributes']['href']; + } + } + } } else { if((strpos($orig_url,'@')) && validate_email($orig_url)) { @@ -165,12 +185,13 @@ function follow_post(&$a) { } else { // create contact record - $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `notify`, `poll`, `name`, `nick`, `photo`, `network`, `rel`, `priority`, + $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `alias`, `notify`, `poll`, `name`, `nick`, `photo`, `network`, `rel`, `priority`, `blocked`, `readonly`, `pending` ) - VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 0, 0, 0 ) ", + VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, 0, 0, 0 ) ", intval(local_user()), dbesc(datetime_convert()), dbesc($profile), + dbesc($alias), dbesc($notify), dbesc($poll), dbesc($vcard['fn']), diff --git a/mod/item.php b/mod/item.php index 2264ea5b..737fe834 100644 --- a/mod/item.php +++ b/mod/item.php @@ -246,18 +246,20 @@ function item_post(&$a) { ); } if(count($r)) { - if($r[0]['network'] === 'stat') - $stat = true; $profile = $r[0]['url']; - $newname = $r[0]['name']; + if($r[0]['network'] === 'stat') { + $newname = $r[0]['nick']; + $stat = true; + } + else + $newname = $r[0]['name']; if(strlen($inform)) $inform .= ','; $inform .= 'cid:' . $r[0]['id']; } } if($profile) { - if(! $stat) - $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname . '[/url]', $body); + $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname . '[/url]', $body); $profile = str_replace(',','%2c',$profile); if(strlen($str_tags)) $str_tags .= ','; diff --git a/mod/salmon.php b/mod/salmon.php index 8c7d921c..885ba470 100644 --- a/mod/salmon.php +++ b/mod/salmon.php @@ -177,7 +177,7 @@ function salmon_post(&$a) { * */ - $r = q("SELECT * FROM `contact` WHERE `network` = 'stat' AND ( `url` = '%s' OR `lrdd` = '%s') + $r = q("SELECT * FROM `contact` WHERE `network` = 'stat' AND ( `url` = '%s' OR `alias` = '%s') AND `uid` = %d LIMIT 1", dbesc($author_link), dbesc($author_link), diff --git a/update.php b/update.php index e51e8ac3..84eaebe1 100644 --- a/update.php +++ b/update.php @@ -363,3 +363,10 @@ function update_1036() { } } } + +function update_1037() { + + q("ALTER TABLE `contact` CHANGE `lrdd` `alias` CHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL "); + +} + From 6b8bbef6c795fcf73c7c7271decf0f0bfed158c7 Mon Sep 17 00:00:00 2001 From: Friendika Date: Tue, 8 Feb 2011 20:55:34 -0800 Subject: [PATCH 11/36] suppress parse warnings --- boot.php | 2 +- include/oembed.php | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/boot.php b/boot.php index 8492b8be..3edd4597 100644 --- a/boot.php +++ b/boot.php @@ -3,7 +3,7 @@ set_time_limit(0); define ( 'BUILD_ID', 1038 ); -define ( 'FRIENDIKA_VERSION', '2.10.0905' ); +define ( 'FRIENDIKA_VERSION', '2.10.0906' ); define ( 'DFRN_PROTOCOL_VERSION', '2.1' ); define ( 'EOL', "
\r\n" ); diff --git a/include/oembed.php b/include/oembed.php index 37923a87..4d6b0af1 100644 --- a/include/oembed.php +++ b/include/oembed.php @@ -79,7 +79,10 @@ function oe_get_inner_html( $node ) { * and replace it with [embed]url[/embed] */ function oembed_html2bbcode($text) { - $dom = DOMDocument::loadHTML($text); + // If it doesn't parse at all, just return the text. + $dom = @DOMDocument::loadHTML($text); + if(! $dom) + return $text; $xpath = new DOMXPath($dom); $attr = "oembed"; From 5899ae9017c351b9987868871605f3f2324c62c0 Mon Sep 17 00:00:00 2001 From: Friendika Date: Tue, 8 Feb 2011 21:26:28 -0800 Subject: [PATCH 12/36] Support bbcode size tag - I may regret this... --- boot.php | 4 ++-- include/bbcode.php | 4 ++-- include/html2bbcode.php | 2 ++ tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/boot.php b/boot.php index 3edd4597..9d41abec 100644 --- a/boot.php +++ b/boot.php @@ -305,9 +305,9 @@ class App { $this->scheme = $parsed['scheme']; $this->hostname = $parsed['host']; - if($parsed['port']) + if(x($parsed,'port')) $this->hostname .= ':' . $parsed['port']; - if($parsed['path']) + if(x($parsed,'path')) $this->path = trim($parsed['path'],'\\/'); } diff --git a/include/bbcode.php b/include/bbcode.php index eb0806dc..f39ebd5b 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -49,10 +49,10 @@ function bbcode($Text) { $Text = preg_replace("(\[o\](.+?)\[\/o\])is",'$1',$Text); // Check for colored text - $Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","$2",$Text); + $Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","$2",$Text); // Check for sized text - $Text = preg_replace("(\[size=(.+?)\](.+?)\[\/size\])is","$2",$Text); + $Text = preg_replace("(\[size=(.+?)\](.+?)\[\/size\])is","$2",$Text); // Check for list text $Text = preg_replace("/\[list\](.+?)\[\/list\]/is", '
    $1
' ,$Text); diff --git a/include/html2bbcode.php b/include/html2bbcode.php index 6af8df82..bde761f2 100644 --- a/include/html2bbcode.php +++ b/include/html2bbcode.php @@ -26,6 +26,7 @@ function html2bbcode($s) { '/\(.*?)\<\/a\>/is', '/\(.*?)\<\/code\>/is', '/\(.*?)\<\/span\>/is', + '/\(.*?)\<\/span\>/is', '/\(.*?)\<\/blockquote\>/is', '/\(.*?)\<\/video\>/is', '/\(.*?)\<\/audio\>/is', @@ -51,6 +52,7 @@ function html2bbcode($s) { '[url=$2]$4[/url]', '[code]$1[/code]', '[color="$1"]$2[/color]', + '[size=$1]$2[/size]', '[quote]$1[/quote]', '[video]$1[/video]', '[audio]$1[/audio]', diff --git a/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js b/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js index ebccfb31..aad83280 100644 --- a/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js +++ b/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js @@ -103,7 +103,7 @@ rep(/\[img=(.*?)x(.*?)\](.*?)\[\/img\]/gi,""); rep(/\[img\](.*?)\[\/img\]/gi,""); rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"$2"); -// rep(/\[\/code\]\s*\[code\]/gi,"
"); // fold multiline code + rep(/\[size=(.*?)\](.*?)\[\/size\]/gi,"$2"); rep(/\[code\](.*?)\[\/code\]/gi,"$1"); rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"
$1
"); From ca826c7ff2eafe215cc4c405738f46172bb62cd0 Mon Sep 17 00:00:00 2001 From: Friendika Date: Tue, 8 Feb 2011 23:24:19 -0800 Subject: [PATCH 13/36] images were left behind in theme rename --- view/theme/duepuntozero/ff-16.jpg | Bin 0 -> 644 bytes view/theme/duepuntozero/lock.cur | Bin 0 -> 4286 bytes view/theme/duepuntozero/login-bg.gif | Bin 0 -> 237 bytes view/theme/duepuntozero/style.css | 6 +++--- 4 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 view/theme/duepuntozero/ff-16.jpg create mode 100755 view/theme/duepuntozero/lock.cur create mode 100644 view/theme/duepuntozero/login-bg.gif diff --git a/view/theme/duepuntozero/ff-16.jpg b/view/theme/duepuntozero/ff-16.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3621f59148398ca78a670fd3134cf6739a346cde GIT binary patch literal 644 zcmex=O1eh6>7?=bZ znFSgDA7Kz-U}QiA96(Vy0R~1^u#GS|Rz_wPHg+ZsArVoayeLo(CIg|_LE2OV85mg@ znb?@&a!g=ttRftofimxJ#@AiifwGDncT6PBEX~+9-4*kc)Yu}|R&RLV;{NEiYL$;|B1MOl^sl}6(k*IS zxlQ=Ur&TVeCAu{?E_j{GzV(nGPg!{Enhk4Zi>()|I$g3fp)objfK9UN%lmbzCnv1m z)ypKed3oBtg3ne#r9Qd-k%`Yrg1HKQ?3PYA^0_nm?dEh3E~(EUGmk9uy>z6-@9C7x zj&oC9Pgl0pOg39|H#>fX?9z9~-bj6ms|$vz@7jA literal 0 HcmV?d00001 diff --git a/view/theme/duepuntozero/lock.cur b/view/theme/duepuntozero/lock.cur new file mode 100755 index 0000000000000000000000000000000000000000..892c5e851eedc16e9844061b199e24194cfbc370 GIT binary patch literal 4286 zcmd^C$KVDWfom`T#)dc~R#4I^Rs~r4O)`b{bmUKcqz}))c5uC(7v?)v4a2P)ZNa- z@$&T2)z|&~{r~^}A^8LV00000EC2ui01yBW000GQ;3tk`X`bk)Wk@<6#nZYULKH{p zEx|?+kif!I0vIL|#ZMubBmjWH2OtmxIFVa~6JQ7!1CK!f5W#StOTv&C3=E8h2vI1s n+#cd5;2fT3B_0kF0v!+!GARoV78n&7dMN`JIW(4+BOw4gP{MS* literal 0 HcmV?d00001 diff --git a/view/theme/duepuntozero/style.css b/view/theme/duepuntozero/style.css index 50745ac1..0c56c423 100644 --- a/view/theme/duepuntozero/style.css +++ b/view/theme/duepuntozero/style.css @@ -28,7 +28,7 @@ input { img { border :0px; } .openid { - background: url(../default/login-bg.gif) no-repeat; + background: url(login-bg.gif) no-repeat; background-position: 0 50%; padding-left: 18px; } @@ -319,7 +319,7 @@ div.wall-item-content-wrapper.shiny { input#dfrn-url { float: left; - background: url(../default/ff-16.jpg) no-repeat; + background: url(ff-16.jpg) no-repeat; background-position: 2px center; font-size: 17px; padding-left: 21px; @@ -1781,7 +1781,7 @@ a.mail-list-link { } .sparkle { - cursor: url('../default/lock.cur'), pointer; + cursor: url('lock.cur'), pointer; /* cursor: pointer !important; */ } From 89da23c30e132fa1f0c118e32e386cbd9c3c88af Mon Sep 17 00:00:00 2001 From: Tobias Diekershoff Date: Wed, 9 Feb 2011 09:40:56 +0100 Subject: [PATCH 14/36] spaces for the string extractor, check no parent --- addon/statusnet/statusnet.php | 24 ++++++++++++------------ addon/twitter/twitter.php | 18 +++++++++--------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/addon/statusnet/statusnet.php b/addon/statusnet/statusnet.php index b1d33054..cd562cd1 100644 --- a/addon/statusnet/statusnet.php +++ b/addon/statusnet/statusnet.php @@ -127,13 +127,13 @@ function statusnet_settings(&$a,&$s) { /*** * no consumer keys */ - $s .= '

'.t('No consumer key pair for StatusNet found. Register your Friendika Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.
Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendika installation at your favorited StatusNet installation.').'

'; + $s .= '

'. t('No consumer key pair for StatusNet found. Register your Friendika Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.
Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendika installation at your favorited StatusNet installation.') .'

'; $s .= '
'; - $s .= ''; + $s .= ''; $s .= '
'; - $s .= ''; + $s .= ''; $s .= '
'; - $s .= ''; + $s .= ''; $s .= '
'; $s .= '
'; $s .= '
'; @@ -154,10 +154,10 @@ function statusnet_settings(&$a,&$s) { /*** * make some nice form */ - $s .= '

'.t('To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your public posts will be posted to StatusNet.').'

'; - $s .= '
'.t('Log in with StatusNet').''; + $s .= '

'. t('To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your public posts will be posted to StatusNet.') .'

'; + $s .= ''. t('Log in with StatusNet') .''; $s .= '
'; - $s .= ''; + $s .= ''; $s .= ''; $s .= ''; $s .= ''; @@ -170,14 +170,14 @@ function statusnet_settings(&$a,&$s) { */ $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret); $details = $connection->get('account/verify_credentials'); - $s .= '

'.t('Currently connected to: ').''.$details->screen_name.'
'.$details->description.'

'; - $s .= '

'.t('If enabled all your public postings will be posted to the associated StatusNet account as well.').'

'; + $s .= '

'. t('Currently connected to: ') .''.$details->screen_name.'
'.$details->description.'

'; + $s .= '

'. t('If enabled all your public postings will be posted to the associated StatusNet account as well.') .'

'; $s .= '
'; - $s .= ''; + $s .= ''; $s .= ''; $s .= '
'; $s .= '
'; - $s .= ''; + $s .= ''; $s .= ''; $s .= '
'; $s .= '
'; @@ -195,7 +195,7 @@ function statusnet_post_hook(&$a,&$b) { logger('StatusNet post invoked'); - if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) { + if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (!$b['parent']) ) { load_pconfig(local_user(), 'statusnet'); diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index 961cca3b..1cd6ee7e 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -101,14 +101,14 @@ function twitter_settings(&$a,&$s) { $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' ); $enabled = get_pconfig(local_user(), 'twitter', 'post'); $checked = (($enabled) ? ' checked="checked" ' : ''); - $s .= '

'.t('Twitter Posting Settings').'

'; + $s .= '

'. t('Twitter Posting Settings') .'

'; if ( (!$ckey) && (!$csecret) ) { /*** * no global consumer keys * display warning and skip personal config */ - $s .= '

'.t('No consumer key pair for Twitter found. Please contact your site administrator.').'

'; + $s .= '

'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'

'; } else { /*** * ok we have a consumer key pair now look into the OAuth stuff @@ -127,10 +127,10 @@ function twitter_settings(&$a,&$s) { /*** * make some nice form */ - $s .= '

'.t('At this Friendika instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your public posts will be posted to Twitter.').'

'; + $s .= '

'. t('At this Friendika instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your public posts will be posted to Twitter.') .'

'; $s .= ''.t('Log in with Twitter').''; $s .= '
'; - $s .= ''; + $s .= ''; $s .= ''; $s .= ''; $s .= ''; @@ -144,14 +144,14 @@ function twitter_settings(&$a,&$s) { require_once('addon/twitter/twitteroauth.php'); $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); $details = $connection->get('account/verify_credentials'); - $s .= '

'.t('Currently connected to: ').''.$details->screen_name.'
'.$details->description.'

'; - $s .= '

'.t('If enabled all your public postings will be posted to the associated Twitter account as well.').'

'; + $s .= '

'. t('Currently connected to: ') .''.$details->screen_name.'
'.$details->description.'

'; + $s .= '

'. t('If enabled all your public postings will be posted to the associated Twitter account as well.') .'

'; $s .= '
'; - $s .= ''; + $s .= ''; $s .= ''; $s .= '
'; $s .= '
'; - $s .= ''; + $s .= ''; $s .= ''; $s .= '
'; $s .= '
'; @@ -169,7 +169,7 @@ function twitter_post_hook(&$a,&$b) { logger('twitter post invoked'); - if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) { + if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) { load_pconfig(local_user(), 'twitter'); From 1d12a2be699df4b5170901a63180beab52c464f7 Mon Sep 17 00:00:00 2001 From: Friendika Date: Wed, 9 Feb 2011 00:53:51 -0800 Subject: [PATCH 15/36] string update --- util/strings.php | 44 ++++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/util/strings.php b/util/strings.php index 762c68d2..b6360e97 100644 --- a/util/strings.php +++ b/util/strings.php @@ -57,6 +57,18 @@ $a->strings['December'] = 'December'; $a->strings['Birthdays this week:'] = 'Birthdays this week:'; $a->strings["\x28Adjusted for local time\x29"] = "\x28Adjusted for local time\x29"; $a->strings['[today]'] = '[today]'; +$a->strings['Unable to locate original post.'] = 'Unable to locate original post.'; +$a->strings['Empty post discarded.'] = 'Empty post discarded.'; +$a->strings['Wall Photos'] = 'Wall Photos'; +$a->strings[" commented on your item at "] = " commented on your item at "; +$a->strings[" posted on your profile wall at "] = " posted on your profile wall at "; +$a->strings['System error. Post not saved.'] = 'System error. Post not saved.'; +$a->strings['This message was sent to you by '] = 'This message was sent to you by '; +$a->strings[', a member of the Friendika social network.'] = ', a member of the Friendika social network.'; +$a->strings['You may visit them online at'] = 'You may visit them online at'; +$a->strings['Please contact the sender by replying to this post if you do not wish to receive these messages.'] = 'Please contact the sender by replying to this post if you do not wish to receive these messages.'; +$a->strings['posted an update.'] = 'posted an update.'; +$a->strings['Item not found.'] = 'Item not found.'; $a->strings["Invite Friends"] = "Invite Friends"; $a->strings['Connect/Follow [profile address]'] = 'Connect/Follow [profile address]'; $a->strings['Example: bob@example.com, http://example.com/barbara'] = 'Example: bob@example.com, http://example.com/barbara'; @@ -76,6 +88,9 @@ $a->strings['Contact not found.'] = 'Contact not found.'; $a->strings['Mutual Friendship'] = 'Mutual Friendship'; $a->strings['is a fan of yours'] = 'is a fan of yours'; $a->strings['you are a fan of'] = 'you are a fan of'; +$a->strings['Never'] = 'Never'; +$a->strings["\x28Update was successful\x29"] = "\x28Update was successful\x29"; +$a->strings["\x28Update was not successful\x29"] = "\x28Update was not successful\x29"; $a->strings['Contact Editor'] = 'Contact Editor'; $a->strings['Visit $name\'s profile'] = 'Visit $name\'s profile'; $a->strings['Block/Unblock contact'] = 'Block/Unblock contact'; @@ -83,7 +98,6 @@ $a->strings['Ignore contact'] = 'Ignore contact'; $a->strings['Delete contact'] = 'Delete contact'; $a->strings['Last updated: '] = 'Last updated: '; $a->strings['Update public posts: '] = 'Update public posts: '; -$a->strings['Never'] = 'Never'; $a->strings['Update now'] = 'Update now'; $a->strings['Unblock this contact'] = 'Unblock this contact'; $a->strings['Block this contact'] = 'Block this contact'; @@ -159,7 +173,6 @@ $a->strings['Your profile address:'] = 'Your profile address:'; $a->strings['Submit Request'] = 'Submit Request'; $a->strings['Cancel'] = 'Cancel'; $a->strings['Global Directory'] = 'Global Directory'; -$a->strings['Item not found.'] = 'Item not found.'; $a->strings['Private Message'] = 'Private Message'; $a->strings['This is you'] = 'This is you'; $a->strings['View $name\'s profile'] = 'View $name\'s profile'; @@ -215,16 +228,6 @@ $a->strings['Your message:'] = 'Your message:'; $a->strings['Please join my social network on '] = 'Please join my social network on '; $a->strings['To accept this invitation, please visit:'] = 'To accept this invitation, please visit:'; $a->strings['Once you have registered, please connect with me via my profile page at:'] = 'Once you have registered, please connect with me via my profile page at:'; -$a->strings['Unable to locate original post.'] = 'Unable to locate original post.'; -$a->strings['Empty post discarded.'] = 'Empty post discarded.'; -$a->strings['Wall Photos'] = 'Wall Photos'; -$a->strings[" commented on your item at "] = " commented on your item at "; -$a->strings[" posted on your profile wall at "] = " posted on your profile wall at "; -$a->strings['This message was sent to you by '] = 'This message was sent to you by '; -$a->strings[', a member of the Friendika social network.'] = ', a member of the Friendika social network.'; -$a->strings['You may visit them online at'] = 'You may visit them online at'; -$a->strings['Please contact the sender by replying to this post if you do not wish to receive these messages.'] = 'Please contact the sender by replying to this post if you do not wish to receive these messages.'; -$a->strings['posted an update.'] = 'posted an update.'; $a->strings['photo'] = 'photo'; $a->strings['status'] = 'status'; $a->strings['likes'] = 'likes'; @@ -490,6 +493,23 @@ $a->strings['File has an invalid extension, it should be one of '] = 'File has a $a->strings['Upload was cancelled, or server error encountered'] = 'Upload was cancelled, or server error encountered'; $a->strings['Randplace Settings'] = 'Randplace Settings'; $a->strings['Enable Randplace Plugin'] = 'Enable Randplace Plugin'; +$a->strings['No consumer key pair for StatusNet found. Register your Friendika Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.
Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendika installation at your favorited StatusNet installation.'] = 'No consumer key pair for StatusNet found. Register your Friendika Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.
Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendika installation at your favorited StatusNet installation.'; +$a->strings['OAuth Consumer Key'] = 'OAuth Consumer Key'; +$a->strings['OAuth Consumer Secret'] = 'OAuth Consumer Secret'; +$a->strings['Base API Path (remember the trailing /] = 'Base API Path (remember the trailing /; +$a->strings['To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your public posts will be posted to StatusNet.'] = 'To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your public posts will be posted to StatusNet.'; +$a->strings['Log in with StatusNet'] = 'Log in with StatusNet'; +$a->strings['Copy the security code from StatusNet here'] = 'Copy the security code from StatusNet here'; +$a->strings['Currently connected to: '] = 'Currently connected to: '; +$a->strings['If enabled all your public postings will be posted to the associated StatusNet account as well.'] = 'If enabled all your public postings will be posted to the associated StatusNet account as well.'; +$a->strings['Send public postings to StatusNet'] = 'Send public postings to StatusNet'; +$a->strings['Clear OAuth configuration'] = 'Clear OAuth configuration'; +$a->strings['Twitter Posting Settings'] = 'Twitter Posting Settings'; +$a->strings['No consumer key pair for Twitter found. Please contact your site administrator.'] = 'No consumer key pair for Twitter found. Please contact your site administrator.'; +$a->strings['At this Friendika instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your public posts will be posted to Twitter.'] = 'At this Friendika instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your public posts will be posted to Twitter.'; +$a->strings['Copy the PIN from Twitter here'] = 'Copy the PIN from Twitter here'; +$a->strings['If enabled all your public postings will be posted to the associated Twitter account as well.'] = 'If enabled all your public postings will be posted to the associated Twitter account as well.'; +$a->strings['Send public postings to Twitter'] = 'Send public postings to Twitter'; $a->strings['Africa/Abidjan'] = 'Africa/Abidjan'; $a->strings['Africa/Accra'] = 'Africa/Accra'; $a->strings['Africa/Addis_Ababa'] = 'Africa/Addis_Ababa'; From 971b16ea4aadf8a24427907619e482e4cafe6faa Mon Sep 17 00:00:00 2001 From: Friendika Date: Wed, 9 Feb 2011 16:55:31 -0800 Subject: [PATCH 16/36] Accept pretty much bloody anything inside a [url] tag as a legal URL. --- include/bbcode.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/bbcode.php b/include/bbcode.php index f39ebd5b..c55ebab0 100644 --- a/include/bbcode.php +++ b/include/bbcode.php @@ -15,14 +15,14 @@ function bbcode($Text) { $Text = nl2br($Text); // Set up the parameters for a URL search string - $URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\%"; + $URLSearchString = "^\[\]"; // Set up the parameters for a MAIL search string - $MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@"; + $MAILSearchString = $URLSearchString; // Perform URL Search - $Text = preg_replace("/([^\]\=]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\%]+)/", ' $2', $Text); + $Text = preg_replace("/([^\]\=]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\%\$\!]+)/", ' $2', $Text); $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/", '$1', $Text); $Text = preg_replace("(\[url\=([$URLSearchString]*)\](.+?)\[/url\])", '$2', $Text); From 05c52ae81da6ce3c3b57672c2560072e1ce2705c Mon Sep 17 00:00:00 2001 From: Friendika Date: Wed, 9 Feb 2011 17:51:05 -0800 Subject: [PATCH 17/36] preserve newlines inside
 tags when importing
 feeds

---
 include/html2bbcode.php | 51 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 49 insertions(+), 2 deletions(-)

diff --git a/include/html2bbcode.php b/include/html2bbcode.php
index bde761f2..734282d9 100644
--- a/include/html2bbcode.php
+++ b/include/html2bbcode.php
@@ -7,10 +7,15 @@
 
 function html2bbcode($s) {
 
+
+	// only keep newlines from source that are within pre tags
+
+	$s = stripnl_exceptinpre($s);
+
+
 	// Tags to Find
 
 	$htmltags = array(
-		'/\n/is',
 		'/\(.*?)\<\/pre\>/is',
 		'/\/is',
 		'/\<\/p\>/is',
@@ -36,7 +41,6 @@ function html2bbcode($s) {
 	// Replace with
 
 	$bbtags = array(
-		'',
 		'[code]$1[/code]',
 		'',
 		"\n",
@@ -66,5 +70,48 @@ function html2bbcode($s) {
 	// Strip all other HTML tags
 	$text = strip_tags($text);
 	return $text;
+
+}
+
+function stripnl_exceptinpre($string)
+{
+    // First, check for 
 tag
+    if(strpos($string, '
') === false)
+    {
+        return str_replace("\n","", $string);
+    }
+
+    // If there is a 
, we have to split by line
+    // and manually replace the linebreaks
+
+    $strArr=explode("\n", $string);
+
+    $output="";
+    $preFound=false;
+
+    // Loop over each line
+    foreach($strArr as $line)
+    {    // See if the line has a 
. If it does, set $preFound to true
+        if(strpos($line, "
") !== false)
+        {
+            $preFound=true;
+        }
+        elseif(strpos($line, "
") !== false) + { + $preFound=false; + } + + // If we are in a pre tag, add line and also add \n, else add the line without \n + if($preFound) + { + $output .= $line . "\n"; + } + else + { + $output .= $line ; + } + } + + return $output; } From de2c9531db2332f0c0e944add6f9d85e88476dff Mon Sep 17 00:00:00 2001 From: Friendika Date: Wed, 9 Feb 2011 19:39:49 -0800 Subject: [PATCH 18/36] post permission hooks --- include/acl_selectors.php | 22 ++++++++++++++++++++++ mod/item.php | 2 ++ 2 files changed, 24 insertions(+) diff --git a/include/acl_selectors.php b/include/acl_selectors.php index 269dc3e3..953243a4 100644 --- a/include/acl_selectors.php +++ b/include/acl_selectors.php @@ -3,6 +3,8 @@ function group_select($selname,$selclass,$preselected = false,$size = 4) { + $a = get_app(); + $o = ''; $o .= "\r\n"; + call_hooks($a->module . '_post_' . $selname, $o); + return $o; } @@ -60,6 +71,15 @@ function contact_select($selname, $selclass, $preselected = false, $size = 4, $p intval(local_user()) ); + + $arr = array('contact' => $r, 'entry' => $o); + + // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow' + + call_hooks($a->module . '_pre_' . $selname, $arr); + + + if(count($r)) { foreach($r as $rr) { if((is_array($preselected)) && in_array($rr['id'], $preselected)) @@ -73,8 +93,10 @@ function contact_select($selname, $selclass, $preselected = false, $size = 4, $p } } + $o .= "\r\n"; + call_hooks($a->module . '_post_' . $selname, $o); return $o; } diff --git a/mod/item.php b/mod/item.php index 737fe834..a83373f5 100644 --- a/mod/item.php +++ b/mod/item.php @@ -22,6 +22,8 @@ function item_post(&$a) { $uid = local_user(); + call_hooks('post_local_start', $_POST); + $parent = ((x($_POST,'parent')) ? intval($_POST['parent']) : 0); $parent_item = null; From 40777b132b86cb832c0ce18b9a65a137a085a41b Mon Sep 17 00:00:00 2001 From: Friendika Date: Wed, 9 Feb 2011 19:56:40 -0800 Subject: [PATCH 19/36] log ignored pubsub deliveries --- mod/pubsub.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mod/pubsub.php b/mod/pubsub.php index 4f4ed2f1..df27c6bc 100644 --- a/mod/pubsub.php +++ b/mod/pubsub.php @@ -105,8 +105,10 @@ function pubsub_post(&$a) { intval($contact_id), intval($importer['uid']) ); - if(! count($r)) + if(! count($r)) { + logger('pubsub: no contact record - ignored'); hub_post_return(); + } $contact = $r[0]; From 2e78ed00f6b247c90b1bc78ff4801e337e6d8d86 Mon Sep 17 00:00:00 2001 From: Friendika Date: Thu, 10 Feb 2011 00:32:09 -0800 Subject: [PATCH 20/36] general purpose callback landing page - e.g. for facebook plugin --- mod/cb.php | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 mod/cb.php diff --git a/mod/cb.php b/mod/cb.php new file mode 100644 index 00000000..6375d239 --- /dev/null +++ b/mod/cb.php @@ -0,0 +1,24 @@ + Date: Thu, 10 Feb 2011 03:51:42 -0800 Subject: [PATCH 21/36] entirely possible media/links were the only thing posted - don't forward empty message to twitter/SN --- addon/statusnet/statusnet.php | 3 ++- addon/twitter/twitter.php | 35 ++++++++++++++++++----------------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/addon/statusnet/statusnet.php b/addon/statusnet/statusnet.php index cd562cd1..bc47242f 100644 --- a/addon/statusnet/statusnet.php +++ b/addon/statusnet/statusnet.php @@ -235,7 +235,8 @@ function statusnet_post_hook(&$a,&$b) { $msg .= '... ' . $shortlink; } // and now tweet it :-) - $dent->post('statuses/update', array('status' => $msg)); + if(strlen($msg)) + $dent->post('statuses/update', array('status' => $msg)); } } } diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index 1cd6ee7e..a0c6db93 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -188,30 +188,31 @@ function twitter_post_hook(&$a,&$b) { $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); $max_char = 140; // max. length for a tweet $msg = strip_tags(bbcode($b['body'])); - if ( strlen($msg) > $max_char) { - $shortlink = ""; - require_once('addon/twitter/slinky.php'); - // post url = base url + /display/ + owner + post id - // we construct this from the Owner link and replace - // profile by display - this will cause an error when - // /profile/ is in the owner url twice but I don't - // think this will be very common... + if ( strlen($msg) > $max_char) { + $shortlink = ""; + require_once('addon/twitter/slinky.php'); + // post url = base url + /display/ + owner + post id + // we construct this from the Owner link and replace + // profile by display - this will cause an error when + // /profile/ is in the owner url twice but I don't + // think this will be very common... $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id']; $slinky = new Slinky( $posturl ); // setup a cascade of shortening services // try to get a short link from these services // in the order ur1.ca, trim, id.gd, tinyurl $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) ); - $shortlink = $slinky->short(); - // the new message will be shortened such that "... $shortlink" - // will fit into the character limit - $msg = substr($msg, 0, $max_char-strlen($shortlink)-4); - $msg .= '... ' . $shortlink; - } - // and now tweet it :-) - $tweet->post('statuses/update', array('status' => $msg)); + $shortlink = $slinky->short(); + // the new message will be shortened such that "... $shortlink" + // will fit into the character limit + $msg = substr($msg, 0, $max_char-strlen($shortlink)-4); + $msg .= '... ' . $shortlink; + } + // and now tweet it :-) + if(strlen($msg)) + $tweet->post('statuses/update', array('status' => $msg)); } } - } + } } From 6da603fbb5ad5ff405ddcdf77a2ce587515d6e94 Mon Sep 17 00:00:00 2001 From: Friendika Date: Thu, 10 Feb 2011 13:21:17 -0800 Subject: [PATCH 22/36] typo in schema --- database.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database.sql b/database.sql index 34b80797..55671db8 100644 --- a/database.sql +++ b/database.sql @@ -472,7 +472,7 @@ CREATE TABLE IF NOT EXISTS `event` ( `deny_gid` MEDIUMTEXT NOT NULL ) ENGINE = MYISAM DEFAULT CHARSET=utf8; -CREATE TABLE IF NOT EXISTS 'cache' ( +CREATE TABLE IF NOT EXISTS `cache` ( `k` CHAR( 255 ) NOT NULL PRIMARY KEY , `v` TEXT NOT NULL, `updated` DATETIME NOT NULL From f217a557b84129a9f2ad692069d40e7fe341cdc6 Mon Sep 17 00:00:00 2001 From: Friendika Date: Thu, 10 Feb 2011 16:17:21 -0800 Subject: [PATCH 23/36] allow plugins to become cmd modules --- boot.php | 4 +++- index.php | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/boot.php b/boot.php index 9d41abec..f1edf798 100644 --- a/boot.php +++ b/boot.php @@ -195,7 +195,7 @@ class App { public $hooks; public $timezone; public $interactive = true; - + public $plugins; private $scheme; private $hostname; @@ -478,6 +478,8 @@ function check_config(&$a) { if($plugins) $plugins_arr = explode(',',str_replace(' ', '',$plugins)); + $a->plugins = $plugins_arr; + $installed_arr = array(); if(count($installed)) { diff --git a/index.php b/index.php index 5f128ebb..d0de1b9d 100644 --- a/index.php +++ b/index.php @@ -134,7 +134,12 @@ else if(strlen($a->module)) { - if(file_exists("mod/{$a->module}.php")) { + if(is_array($a->plugins) && in_array($a->module,$a->plugins) && file_exists("addon/{$a->module}/{$a->module}.php")) { + include("addon/{$a->module}/{$a->module}.php"); + if(function_exists($a->module . '_module')) + $a->module_loaded = true; + } + if((! $a->module_loaded) && (file_exists("mod/{$a->module}.php"))) { include("mod/{$a->module}.php"); $a->module_loaded = true; } From bd4e7249a347b012c34d23a739b56cb6aea63240 Mon Sep 17 00:00:00 2001 From: Friendika Date: Thu, 10 Feb 2011 18:01:38 -0800 Subject: [PATCH 24/36] more work on facebook addon --- addon/facebook/LICENSE | 662 ------------------------------------ addon/facebook/facebook.php | 95 +++++- util/typo.php | 2 +- 3 files changed, 89 insertions(+), 670 deletions(-) delete mode 100644 addon/facebook/LICENSE diff --git a/addon/facebook/LICENSE b/addon/facebook/LICENSE deleted file mode 100644 index 5193fb41..00000000 --- a/addon/facebook/LICENSE +++ /dev/null @@ -1,662 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a wok means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. - diff --git a/addon/facebook/facebook.php b/addon/facebook/facebook.php index acf37fcd..7a7c3428 100644 --- a/addon/facebook/facebook.php +++ b/addon/facebook/facebook.php @@ -10,6 +10,58 @@ * */ +define('FACEBOOK_MAXPOSTLEN', 420); + +/* declare the facebook_module function so that /facebook url requests will land here */ + +function facebook_module() {} + + + +/* Callback from Facebook oauth requests. */ + +function facebook_init(&$a) { + + if($a->argc != 2) + return; + $nick = $a->argv[1]; + if(strlen($nick)) + $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", + dbesc($nick) + ); + if(! count($r)) + return; + + $uid = $r[0]['uid']; + $auth_code = (($_GET['code']) ? $_GET['code'] : ''); + $error = (($_GET['error_description']) ? $_GET['error_description'] : ''); + + + if($auth_code && $uid) { + + $appid = get_config('facebook','appid'); + $appsecret = get_config('facebook', 'appsecret'); + + $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' + . $appid . '&client_secret=' . $appsecret . '&redirect_uri=' + . urlencode($a->get_baseurl() . '/facebook/' . $nick) + . '&code=' . $auth_code); + if(strpos($x,'access_token=') !== false) { + $token = str_replace('access_token=', '', $x); + if(strpos($token,'&') !== false) + $token = substr('$token,0,strpos($token,'&')); + set_pconfig($uid,'facebook','access_token',$token); + } + + // todo: is this a browser session or a server session? where do we go? + } + +} + +function facebook_content(&$a) { + $o = "facebook module loaded"; + return $o; +} function facebook_install() { register_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook'); @@ -21,27 +73,56 @@ function facebook_uninstall() { } - - function facebook_post_hook(&$a,&$b) { /** * Post to Facebook stream */ - if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) { + if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent'])) { - $appid = get_config('system', 'facebook_appid' ); - $secret = get_config('system', 'facebook_secret' ); + $appid = get_config('facebook', 'appid' ); + $secret = get_config('facebook', 'appsecret' ); if($appid && $secret) { - $fb_post = get_pconfig(local_user(),'facebook','post'); + $fb_post = get_pconfig(local_user(),'facebook','post'); + $fb_token = get_pconfig(local_user(),'facebook','access_token'); - if($fb_post) { + if($fb_post && $fb_token) { require_once('library/facebook.php'); require_once('include/bbcode.php'); + + // make links readable before we strip the code + + $msg = preg_replace('\[url\=(.?*)\](.?*)\[\/url\]/is','$2 ($1)',$msg); + + $msg = preg_replace('\[img\](.?*)\[\/img\]/is', t('Image: ') . '$1',$msg); + + $msg = trim(strip_tags(bbcode($b['body']))); + if (strlen($msg) > FACEBOOK_MAXPOSTLEN) { + $shortlink = ""; + require_once('addon/twitter/slinky.php'); + + $display_url = $a->get_baseurl() . '/display/' . $a->user['nickname'] . '/' . $b['id']; + $slinky = new Slinky( $posturl ); + // setup a cascade of shortening services + // try to get a short link from these services + // in the order ur1.ca, trim, id.gd, tinyurl + $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) ); + $shortlink = $slinky->short(); + // the new message will be shortened such that "... $shortlink" + // will fit into the character limit + $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4); + $msg .= '... ' . $shortlink; + } + if(! strlen($msg)) + return; + + + + $facebook = new Facebook(array( 'appId' => $appid, 'secret' => $secret, diff --git a/util/typo.php b/util/typo.php index be5307ab..d0ecf0c8 100644 --- a/util/typo.php +++ b/util/typo.php @@ -21,6 +21,6 @@ foreach($files as $file) include_once($file); - $files = glob('addon/*.php'); + $files = glob('addon/*/*.php'); foreach($files as $file) include_once($file); From fc5a3cac14d40286f0daf909b0243725a8ef76e3 Mon Sep 17 00:00:00 2001 From: Friendika Date: Thu, 10 Feb 2011 21:25:24 -0800 Subject: [PATCH 25/36] post to FB is working --- addon/facebook/facebook.php | 69 ++++++++++++++++++++++++++++--------- index.php | 2 +- 2 files changed, 53 insertions(+), 18 deletions(-) diff --git a/addon/facebook/facebook.php b/addon/facebook/facebook.php index 7a7c3428..c1f3c5a3 100644 --- a/addon/facebook/facebook.php +++ b/addon/facebook/facebook.php @@ -18,7 +18,7 @@ function facebook_module() {} -/* Callback from Facebook oauth requests. */ +/* If a->argv[1] is a nickname, this is a callback from Facebook oauth requests. */ function facebook_init(&$a) { @@ -37,6 +37,9 @@ function facebook_init(&$a) { $error = (($_GET['error_description']) ? $_GET['error_description'] : ''); + if($error) + logger('facebook_init: Error: ' . $error); + if($auth_code && $uid) { $appid = get_config('facebook','appid'); @@ -46,11 +49,15 @@ function facebook_init(&$a) { . $appid . '&client_secret=' . $appsecret . '&redirect_uri=' . urlencode($a->get_baseurl() . '/facebook/' . $nick) . '&code=' . $auth_code); + + logger('facebook_init: returned access token: ' . $x, LOGGER_DATA); + if(strpos($x,'access_token=') !== false) { $token = str_replace('access_token=', '', $x); if(strpos($token,'&') !== false) - $token = substr('$token,0,strpos($token,'&')); + $token = substr($token,0,strpos($token,'&')); set_pconfig($uid,'facebook','access_token',$token); + set_pconfig($uid,'facebook','post','true'); } // todo: is this a browser session or a server session? where do we go? @@ -59,7 +66,34 @@ function facebook_init(&$a) { } function facebook_content(&$a) { - $o = "facebook module loaded"; + + if(! local_user()) { + notice( t('Permission denied.') . EOL); + return ''; + } + + if($a->argc > 1 && $a->argv[1] === 'remove') { + del_pconfig(local_user(),'facebook','post'); + notice( t('Facebook disabled') . EOL); + } + + $appid = get_config('facebook','appid'); + + if(! $appid) { + notify( t('Facebook API key is missing.') . EOL); + return ''; + } + + $o .= '

' . t('Facebook Connect') . '

'; + + $o .= '
'; + + $o .= '' . t('Install Facebook posting') . '
'; + + $o .= '' . t('Remove Facebook posting') . '
'; + + return $o; } @@ -79,8 +113,11 @@ function facebook_post_hook(&$a,&$b) { * Post to Facebook stream */ + logger('Facebook post'); + if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent'])) { + $appid = get_config('facebook', 'appid' ); $secret = get_config('facebook', 'appsecret' ); @@ -93,14 +130,18 @@ function facebook_post_hook(&$a,&$b) { require_once('library/facebook.php'); require_once('include/bbcode.php'); + $msg = $b['body']; + + logger('Facebook post2: msg=' . $msg, LOGGER_DATA); // make links readable before we strip the code - $msg = preg_replace('\[url\=(.?*)\](.?*)\[\/url\]/is','$2 ($1)',$msg); + $msg = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is",'$2 ($1)',$msg); - $msg = preg_replace('\[img\](.?*)\[\/img\]/is', t('Image: ') . '$1',$msg); + $msg = preg_replace("/\[img\](.+?)\[\/img\]/is", t('Image: ') . '$1',$msg); + + $msg = trim(strip_tags(bbcode($msg))); - $msg = trim(strip_tags(bbcode($b['body']))); if (strlen($msg) > FACEBOOK_MAXPOSTLEN) { $shortlink = ""; require_once('addon/twitter/slinky.php'); @@ -120,20 +161,14 @@ function facebook_post_hook(&$a,&$b) { if(! strlen($msg)) return; + logger('Facebook post: msg=' . $msg, LOGGER_DATA); + $postvars = array('access_token' => $fb_token, 'message' => $msg); + $x = post_url('https://graph.facebook.com/me/feed', $postvars); + + logger('Facebook post returns: ' . $x, LOGGER_DEBUG); - $facebook = new Facebook(array( - 'appId' => $appid, - 'secret' => $secret, - 'cookie' => true - )); - try { - $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> bbcode($b['body']), 'cb' => '')); - } - catch (FacebookApiException $e) { - notice( t('Facebook status update failed.') . EOL); - } } } } diff --git a/index.php b/index.php index d0de1b9d..661676bf 100644 --- a/index.php +++ b/index.php @@ -143,7 +143,7 @@ if(strlen($a->module)) { include("mod/{$a->module}.php"); $a->module_loaded = true; } - else { + if(! $a->module_loaded) { if((x($_SERVER,'QUERY_STRING')) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) { logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']); goaway($a->get_baseurl() . $_SERVER['REQUEST_URI']); From 40574589e27d9135a434dcc4f9dfa899fe5f8ec6 Mon Sep 17 00:00:00 2001 From: Friendika Date: Thu, 10 Feb 2011 23:10:50 -0800 Subject: [PATCH 26/36] fb connecter - document installation --- addon/facebook/facebook.php | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/addon/facebook/facebook.php b/addon/facebook/facebook.php index c1f3c5a3..a41344a3 100644 --- a/addon/facebook/facebook.php +++ b/addon/facebook/facebook.php @@ -1,12 +1,32 @@ config['facebook']['appid'] = 'xxxxxxxxxxx'; + * $a->config['facebook']['appsecret'] = 'xxxxxxxxxxxxxxx'; + * Replace with the settings Facebook gives you. + * 2. Enable the facebook plugin by including it in .htconfig.php - e.g. + * $a->config['system']['addon'] = 'plugin1,plugin2,facebook'; + * 3. Visit your site url + '/facebook' (e.g. http://example.com/facebook) + * and click 'Install Facebook posting'. + * 4. This will ask you to login to Facebook and grant permission to the + * plugin to do its stuff. Allow it to do so. + * 5. You're done. To turn it off visit your site's /facebook page again and + * 'Remove Facebook posting'. + * + * Turn logging on (see the github Friendika wiki page 'Settings') and + * repeat these steps if you have trouble. + * Vidoes and embeds will not be posted if there is no other content. Links + * and images will be converted to text and long posts truncated - with a link + * to view the full post. Posts with permission settings and comments will + * not be posted to Facebook. * */ From c16e86add81d9f2867a0da024954b5cbc14a9f4b Mon Sep 17 00:00:00 2001 From: Friendika Date: Fri, 11 Feb 2011 02:35:19 -0800 Subject: [PATCH 27/36] toggles "post to facebook, post to twitter", etc. --- addon/facebook/facebook.php | 45 ++++++++++++++++++++++++++----- addon/twitter/twitter.php | 36 ++++++++++++++++++++++++- boot.php | 2 ++ mod/network.php | 5 +++- mod/profile.php | 6 ++++- view/de/jot.tpl | 6 ++++- view/en/jot.tpl | 6 ++++- view/fr/jot.tpl | 7 +++-- view/it/jot.tpl | 7 +++-- view/theme/duepuntozero/style.css | 11 ++++++++ view/theme/loozah/style.css | 11 ++++++++ 11 files changed, 127 insertions(+), 15 deletions(-) diff --git a/addon/facebook/facebook.php b/addon/facebook/facebook.php index a41344a3..2a5715b2 100644 --- a/addon/facebook/facebook.php +++ b/addon/facebook/facebook.php @@ -3,6 +3,9 @@ /** * This module still needs a lot of work, but is functional today. * Please review this section if you upgrade because things will change. + * If you have issues upgrading, remove facebook from the addon list, + * view a page on your site, then add it back to the list. This will reset + * all of the plugin 'hooks'. * * 1. register an API key from developer.facebook.com * a. We'd be very happy if you include "Friendika" in the application name @@ -77,7 +80,7 @@ function facebook_init(&$a) { if(strpos($token,'&') !== false) $token = substr($token,0,strpos($token,'&')); set_pconfig($uid,'facebook','access_token',$token); - set_pconfig($uid,'facebook','post','true'); + set_pconfig($uid,'facebook','post','1'); } // todo: is this a browser session or a server session? where do we go? @@ -118,12 +121,41 @@ function facebook_content(&$a) { } function facebook_install() { - register_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook'); + register_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook'); + register_hook('jot_networks', 'addon/facebook/facebook.php', 'facebook_jot_nets'); + register_hook('post_local_start','addon/facebook/facebook.php', 'facebook_post_local'); + } function facebook_uninstall() { - unregister_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook'); + unregister_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook'); + unregister_hook('jot_networks', 'addon/facebook/facebook.php', 'facebook_jot_nets'); + unregister_hook('post_local_start','addon/facebook/facebook.php', 'facebook_post_local'); +} + + +function facebook_jot_nets(&$a,&$b) { + if(! local_user()) + return; + + $fb_post = get_pconfig(local_user(),'facebook','post'); + if(intval($fb_post) == 1) { + $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default'); + $selected = ((intval($fb_defpost == 1)) ? ' selected="selected" ' : ''); + $b .= '
' + . t('Post to Facebook') . '
'; + } +} + +function facebook_post_local(&$a,&$b) { + if(! local_user()) + return; + + if((x($b,'facebook_enable')) && (intval($b['facebook_enable']))) + set_pconfig(local_user(),'facebook','enable','1'); + else + del_pconfig(local_user(),'facebook','enable'); } @@ -143,10 +175,11 @@ function facebook_post_hook(&$a,&$b) { if($appid && $secret) { - $fb_post = get_pconfig(local_user(),'facebook','post'); - $fb_token = get_pconfig(local_user(),'facebook','access_token'); + $fb_post = intval(get_pconfig(local_user(),'facebook','post')); + $fb_enable = intval(get_pconfig(local_user(),'facebook','enable')); + $fb_token = get_pconfig(local_user(),'facebook','access_token'); - if($fb_post && $fb_token) { + if($fb_post && $fb_token && $fb_enable) { require_once('library/facebook.php'); require_once('include/bbcode.php'); diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index a0c6db93..6a0365e0 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -40,6 +40,8 @@ function twitter_install() { register_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); register_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post'); register_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook'); + register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets'); + register_hook('post_local_start', 'addon/twitter/twitter.php', 'twitter_post_start'); logger("installed twitter"); } @@ -48,8 +50,39 @@ function twitter_uninstall() { unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post'); unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook'); + unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets'); + unregister_hook('post_local_start', 'addon/twitter/twitter.php', 'twitter_post_start'); + } +function twitter_jot_nets(&$a,&$b) { + if(! local_user()) + return; + + $tw_post = get_pconfig(local_user(),'twitter','post'); + if(intval($tw_post) == 1) { + $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default'); + $selected = ((intval($tw_defpost == 1)) ? ' selected="selected" ' : ''); + $b .= '
' + . t('Post to Twitter') . '
'; + } + + +} + +function twitter_post_start(&$a,&$b) { + if(! local_user()) + return; + + if((x($b,'twitter_enable')) && (intval($b['twitter_enable']))) + set_pconfig(local_user(),'twitter','enable','1'); + else + del_pconfig(local_user(),'twitter','enable'); + + +} + + function twitter_settings_post ($a,$post) { if(! local_user()) return; @@ -181,8 +214,9 @@ function twitter_post_hook(&$a,&$b) { if($ckey && $csecret && $otoken && $osecret) { $twitter_post = get_pconfig(local_user(),'twitter','post'); + $twitter_enable = intval(get_pconfig(local_user(),'twitter','enable')); - if($twitter_post) { + if($twitter_post && $twitter_enable) { require_once('addon/twitter/twitteroauth.php'); require_once('include/bbcode.php'); $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); diff --git a/boot.php b/boot.php index f1edf798..9c871275 100644 --- a/boot.php +++ b/boot.php @@ -516,6 +516,7 @@ function check_config(&$a) { } } } + load_hooks(); return; }} @@ -2189,6 +2190,7 @@ function unregister_hook($hook,$file,$function) { if(! function_exists('load_hooks')) { function load_hooks() { $a = get_app(); + $a->hooks = array(); $r = q("SELECT * FROM `hook` WHERE 1"); if(count($r)) { foreach($r as $rr) { diff --git a/mod/network.php b/mod/network.php index b0196f92..f11db45a 100644 --- a/mod/network.php +++ b/mod/network.php @@ -79,8 +79,10 @@ function network_content(&$a, $update = 0) { $celeb = ((($a->user['page-flags'] == PAGE_SOAPBOX) || ($a->user['page-flags'] == PAGE_COMMUNITY)) ? true : false); - $jotplugins = ""; + $jotplugins = ''; + $jotnets = ''; call_hooks('jot_tool', $jotplugins); + call_hooks('jot_networks', $jotnets); $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins)); @@ -90,6 +92,7 @@ function network_content(&$a, $update = 0) { '$defloc' => $a->user['default-location'], '$visitor' => 'block', '$emailcc' => t('CC: email addresses'), + '$jotnets' => $jotnets, '$emtitle' => t('Example: bob@example.com, mary@example.com'), '$lockstate' => $lockstate, '$acl' => populate_acl((($group) ? $group_acl : $a->user), $celeb), diff --git a/mod/profile.php b/mod/profile.php index 3b4616a3..8ec29d38 100644 --- a/mod/profile.php +++ b/mod/profile.php @@ -135,9 +135,12 @@ function profile_content(&$a, $update = 0) { else $lockstate = 'unlock'; - $jotplugins = ""; + $jotplugins = ''; + $jotnets = ''; call_hooks('jot_tool', $jotplugins); + call_hooks('jot_networks', $jotnets); + $tpl = replace_macros($tpl,array('$jotplugins' => $jotplugins)); $o .= replace_macros($tpl,array( @@ -147,6 +150,7 @@ function profile_content(&$a, $update = 0) { '$visitor' => (($is_owner || $commvisitor) ? 'block' : 'none'), '$lockstate' => $lockstate, '$emailcc' => t('CC: email addresses'), + '$jotnets' => $jotnets, '$emtitle' => t('Example: bob@example.com, mary@example.com'), '$bang' => '', '$acl' => (($is_owner) ? populate_acl($a->user, $celeb) : ''), diff --git a/view/de/jot.tpl b/view/de/jot.tpl index 545bbdad..db73b17a 100644 --- a/view/de/jot.tpl +++ b/view/de/jot.tpl @@ -42,12 +42,16 @@
-
Berechtigungseinstellungen$bang
+
Berechtigungseinstellungen$bang
+ +
diff --git a/view/en/jot.tpl b/view/en/jot.tpl index 5f993577..7c6a857e 100644 --- a/view/en/jot.tpl +++ b/view/en/jot.tpl @@ -40,12 +40,16 @@
-
Permission Settings$bang
+
Permission Settings$bang
+ +
diff --git a/view/fr/jot.tpl b/view/fr/jot.tpl index 720cb0d1..d64632da 100644 --- a/view/fr/jot.tpl +++ b/view/fr/jot.tpl @@ -42,13 +42,16 @@
-
Permission Settings$bang
+
Permission Settings$bang
- + +
diff --git a/view/it/jot.tpl b/view/it/jot.tpl index eae3ecba..c4b63eb0 100644 --- a/view/it/jot.tpl +++ b/view/it/jot.tpl @@ -41,13 +41,16 @@
-
Impostazione permessi$bang
+
Impostazione permessi$bang
- + +
diff --git a/view/theme/duepuntozero/style.css b/view/theme/duepuntozero/style.css index 0c56c423..45e5efb6 100644 --- a/view/theme/duepuntozero/style.css +++ b/view/theme/duepuntozero/style.css @@ -960,6 +960,17 @@ input#dfrn-url { #profile-jot-plugin-end{ clear: both; } +.profile-jot-net { + float: left; + margin-right: 10px; + margin-top: 5px; + margin-bottom: 5px; +} + +#profile-jot-networks-end { + clear: both; +} + #profile-jot-end { /*clear: both;*/ margin-bottom: 30px; diff --git a/view/theme/loozah/style.css b/view/theme/loozah/style.css index d7d735d6..2a037bf9 100644 --- a/view/theme/loozah/style.css +++ b/view/theme/loozah/style.css @@ -1085,6 +1085,17 @@ input#dfrn-url { #profile-jot-plugin-end { clear:both; } +.profile-jot-net { + float: left; + margin-right: 10px; + margin-top: 5px; + margin-bottom: 5px; +} + +#profile-jot-networks-end { + clear: both; +} + #profile-jot-end { clear: both; margin-bottom: 30px; From 0bfe63e7d887f484c5cc0aea37ead0c283967fee Mon Sep 17 00:00:00 2001 From: Friendika Date: Fri, 11 Feb 2011 03:17:16 -0800 Subject: [PATCH 28/36] reinstate send slaps but only at the top level (and followup) --- include/notifier.php | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/include/notifier.php b/include/notifier.php index b6c4ca57..648a0706 100644 --- a/include/notifier.php +++ b/include/notifier.php @@ -40,6 +40,7 @@ function notifier_run($argv, $argc){ break; } + $top_level = false; $recipients = array(); $url_recipients = array(); @@ -79,12 +80,16 @@ function notifier_run($argv, $argc){ return; } + // avoid race condition with deleting entries if($items[0]['deleted']) { foreach($items as $item) $item['deleted'] = 1; } + + if(count($items) == 1 && $items[0]['uri'] === $items[0]['parent-uri']) + $top_level = true; } $r = q("SELECT `contact`.*, `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, `user`.`page-flags` @@ -167,9 +172,6 @@ function notifier_run($argv, $argc){ $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0"); -// if( ! count($r)){ -// return; -// } if(count($r)) $contacts = $r; @@ -242,12 +244,8 @@ function notifier_run($argv, $argc){ $atom .= atom_entry($item,'text',$contact,$owner,true); - // There's a problem here - we *were* going to use salmon to provide semi-authenticated - // communication to OStatus, but unless we're the item author they won't verify. - // commented out for now, though we'll still send local replies (and any mentions - // that they contain) upstream. Rethinking the problem space. - -// $slaps[] = atom_entry($item,'html',$contact,$owner,true); + if(($top_level) && ($notify_hub) && ($item['author-link'] === $item['owner-link'])) + $slaps[] = atom_entry($item,'html',$contact,$owner,true); } } } @@ -255,7 +253,7 @@ function notifier_run($argv, $argc){ logger('notifier: ' . $atom, LOGGER_DATA); -// logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA); + logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA); if($followup) $recip_str = $parent['contact-id']; From 5e02519a1311cb62d7aaa2f8dc947fd0affd454c Mon Sep 17 00:00:00 2001 From: Friendika Date: Fri, 11 Feb 2011 04:32:38 -0800 Subject: [PATCH 29/36] disable network toggles when ACL's are entered --- addon/facebook/facebook.php | 2 +- addon/twitter/twitter.php | 2 +- view/de/jot-header.tpl | 6 ++++-- view/en/jot-header.tpl | 6 ++++-- view/fr/jot-header.tpl | 7 ++++--- view/it/jot-header.tpl | 6 ++++-- 6 files changed, 18 insertions(+), 11 deletions(-) diff --git a/addon/facebook/facebook.php b/addon/facebook/facebook.php index 2a5715b2..93e7962c 100644 --- a/addon/facebook/facebook.php +++ b/addon/facebook/facebook.php @@ -143,7 +143,7 @@ function facebook_jot_nets(&$a,&$b) { if(intval($fb_post) == 1) { $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default'); $selected = ((intval($fb_defpost == 1)) ? ' selected="selected" ' : ''); - $b .= '
' + $b .= '
' . t('Post to Facebook') . '
'; } } diff --git a/addon/twitter/twitter.php b/addon/twitter/twitter.php index 6a0365e0..0b706f9b 100644 --- a/addon/twitter/twitter.php +++ b/addon/twitter/twitter.php @@ -63,7 +63,7 @@ function twitter_jot_nets(&$a,&$b) { if(intval($tw_post) == 1) { $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default'); $selected = ((intval($tw_defpost == 1)) ? ' selected="selected" ' : ''); - $b .= '
' + $b .= '
' . t('Post to Twitter') . '
'; } diff --git a/view/de/jot-header.tpl b/view/de/jot-header.tpl index 41abdf0f..58403f1b 100644 --- a/view/de/jot-header.tpl +++ b/view/de/jot-header.tpl @@ -75,10 +75,12 @@ tinyMCE.init({ $('#contact_allow option:selected, #contact_deny option:selected, #group_allow option:selected, #group_deny option:selected').each( function() { selstr = $(this).text(); $('#profile-jot-perms img').attr('src', 'images/lock_icon.gif'); - + $('.profile-jot-net input').attr('disabled', 'disabled'); }); - if(selstr == null) + if(selstr == null) { $('#profile-jot-perms img').attr('src', 'images/unlock_icon.gif'); + $('.profile-jot-net input').attr('disabled', false); + } }).trigger('change'); diff --git a/view/en/jot-header.tpl b/view/en/jot-header.tpl index d0c956a0..fe818410 100644 --- a/view/en/jot-header.tpl +++ b/view/en/jot-header.tpl @@ -75,10 +75,12 @@ tinyMCE.init({ $('#contact_allow option:selected, #contact_deny option:selected, #group_allow option:selected, #group_deny option:selected').each( function() { selstr = $(this).text(); $('#profile-jot-perms img').attr('src', 'images/lock_icon.gif'); - + $('.profile-jot-net input').attr('disabled', 'disabled'); }); - if(selstr == null) + if(selstr == null) { $('#profile-jot-perms img').attr('src', 'images/unlock_icon.gif'); + $('.profile-jot-net input').attr('disabled', false); + } }).trigger('change'); diff --git a/view/fr/jot-header.tpl b/view/fr/jot-header.tpl index d0c956a0..ff7e543a 100644 --- a/view/fr/jot-header.tpl +++ b/view/fr/jot-header.tpl @@ -75,11 +75,12 @@ tinyMCE.init({ $('#contact_allow option:selected, #contact_deny option:selected, #group_allow option:selected, #group_deny option:selected').each( function() { selstr = $(this).text(); $('#profile-jot-perms img').attr('src', 'images/lock_icon.gif'); - + $('.profile-jot-net input').attr('disabled', 'disabled'); }); - if(selstr == null) + if(selstr == null) { $('#profile-jot-perms img').attr('src', 'images/unlock_icon.gif'); - + $('.profile-jot-net input').attr('disabled', false); + } }).trigger('change'); }); diff --git a/view/it/jot-header.tpl b/view/it/jot-header.tpl index e55a357e..117cd165 100644 --- a/view/it/jot-header.tpl +++ b/view/it/jot-header.tpl @@ -75,10 +75,12 @@ tinyMCE.init({ $('#contact_allow option:selected, #contact_deny option:selected, #group_allow option:selected, #group_deny option:selected').each( function() { selstr = $(this).text(); $('#profile-jot-perms img').attr('src', 'images/lock_icon.gif'); - + $('.profile-jot-net input').attr('disabled', 'disabled'); }); - if(selstr == null) + if(selstr == null) { $('#profile-jot-perms img').attr('src', 'images/unlock_icon.gif'); + $('.profile-jot-net input').attr('disabled', false); + } }).trigger('change'); From 6745f0781796c0064c3f1b223ae194017bd26c0c Mon Sep 17 00:00:00 2001 From: Chris Case Date: Fri, 11 Feb 2011 18:26:07 -0800 Subject: [PATCH 30/36] set size of contact images to improve rendering --- view/theme/duepuntozero/style.css | 4 ++++ view/theme/loozah/style.css | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/view/theme/duepuntozero/style.css b/view/theme/duepuntozero/style.css index 45e5efb6..b0273254 100644 --- a/view/theme/duepuntozero/style.css +++ b/view/theme/duepuntozero/style.css @@ -1807,6 +1807,10 @@ a.mail-list-link { .contact-block-link { float: left; } +.contact-block-img { + width:48px; + height:48px; +} #tag-remove { margin-bottom: 15px; diff --git a/view/theme/loozah/style.css b/view/theme/loozah/style.css index 2a037bf9..0dcddd26 100644 --- a/view/theme/loozah/style.css +++ b/view/theme/loozah/style.css @@ -1933,6 +1933,10 @@ a.mail-list-link { .contact-block-link { float: left; } +.contact-block-img { + width:48px; + height:48px; +} #tag-remove { margin-bottom: 15px; From b98b5645e6572a2ee4b00a1d7960b93160f1de7f Mon Sep 17 00:00:00 2001 From: Chris Case Date: Fri, 11 Feb 2011 18:46:54 -0800 Subject: [PATCH 31/36] fixed a typo in the profile photo wrapper div id --- boot.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/boot.php b/boot.php index 9c871275..2cbc48cd 100644 --- a/boot.php +++ b/boot.php @@ -2100,7 +2100,7 @@ function profile_sidebar($profile) { $tabs = ''; - $photo = '
' . $profile['name'] . '
'; + $photo = '
' . $profile['name'] . '
'; $connect = (($profile['uid'] != local_user()) ? '
  • ' . t('Connect') . '
  • ' : ''); From 8937ba86a211ff5822a0198087f94847f67e5d24 Mon Sep 17 00:00:00 2001 From: Chris Case Date: Fri, 11 Feb 2011 18:52:30 -0800 Subject: [PATCH 32/36] set default size for profile photo to improve render appearance/speed --- view/theme/duepuntozero/style.css | 4 ++++ view/theme/loozah/style.css | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/view/theme/duepuntozero/style.css b/view/theme/duepuntozero/style.css index b0273254..74898220 100644 --- a/view/theme/duepuntozero/style.css +++ b/view/theme/duepuntozero/style.css @@ -605,6 +605,10 @@ input#dfrn-url { #profile-photo-link-select-wrapper { margin-top: 2em; } +#profile-photo-wrapper img { + width:175px; + height:175px; +} #profile-edit-profile-name-label, #profile-edit-name-label, diff --git a/view/theme/loozah/style.css b/view/theme/loozah/style.css index 0dcddd26..a8725201 100644 --- a/view/theme/loozah/style.css +++ b/view/theme/loozah/style.css @@ -737,6 +737,10 @@ input#dfrn-url { #profile-photo-link-select-wrapper { margin-top: 2em; } +#profile-photo-wrapper img { + width:175px; + height:175px; +} #profile-edit-profile-name-label, #profile-edit-name-label, From f79c21529328c9d062d63ccba98ae90480c32225 Mon Sep 17 00:00:00 2001 From: Friendika Date: Sat, 12 Feb 2011 01:37:21 -0800 Subject: [PATCH 33/36] give all comment input form elements id's --- view/comment_item.tpl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/view/comment_item.tpl b/view/comment_item.tpl index 1b1f3a49..6f63e39b 100644 --- a/view/comment_item.tpl +++ b/view/comment_item.tpl @@ -1,9 +1,9 @@
    - - - - + + + +
    $mytitle From 7d0de6dfb77d97b1d4dc10f30565ac8d3622d5a3 Mon Sep 17 00:00:00 2001 From: Friendika Date: Sat, 12 Feb 2011 01:51:29 -0800 Subject: [PATCH 34/36] trim excessive space around message body (though we still need 20px padding to accomodate scrollbars) --- view/theme/duepuntozero/style.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/view/theme/duepuntozero/style.css b/view/theme/duepuntozero/style.css index 74898220..3611e455 100644 --- a/view/theme/duepuntozero/style.css +++ b/view/theme/duepuntozero/style.css @@ -818,7 +818,7 @@ input#dfrn-url { .wall-item-wrapper { float: left; margin-right: 5px; - width: 150px; + width: 250px; } .wall-item-lock { height: 20px; @@ -863,7 +863,7 @@ input#dfrn-url { float: left; /*width: 450px;*/ margin-left: 10px; - margin-bottom: 20px; +/* margin-bottom: 20px;*/ padding: 20px; max-height: 400px; overflow: auto; @@ -878,7 +878,7 @@ input#dfrn-url { .wall-item-body { float: left; width: 450px; - margin-top: 30px; + margin-top: 10px; } .comment-edit-wrapper { From 4081ebe6c5f4e36f7b4ef288005995d959633fce Mon Sep 17 00:00:00 2001 From: Friendika Date: Sat, 12 Feb 2011 02:07:16 -0800 Subject: [PATCH 35/36] correct color and indent on wall-wall comments --- view/theme/duepuntozero/style.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/view/theme/duepuntozero/style.css b/view/theme/duepuntozero/style.css index 3611e455..ac3562d1 100644 --- a/view/theme/duepuntozero/style.css +++ b/view/theme/duepuntozero/style.css @@ -889,8 +889,8 @@ input#dfrn-url { .comment-wwedit-wrapper { margin-top: 15px; - background: #CCCCCC; - margin-left: 250px; + background: #f3f3f3; + margin-left: 50px; } .comment-edit-photo { From 89cbd17c721dae57b18686fd7f3e5f8c74a279d9 Mon Sep 17 00:00:00 2001 From: Friendika Date: Sat, 12 Feb 2011 05:07:24 -0800 Subject: [PATCH 36/36] more fb debug msgs --- addon/facebook/facebook.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/addon/facebook/facebook.php b/addon/facebook/facebook.php index 93e7962c..7bebb3b4 100644 --- a/addon/facebook/facebook.php +++ b/addon/facebook/facebook.php @@ -149,6 +149,7 @@ function facebook_jot_nets(&$a,&$b) { } function facebook_post_local(&$a,&$b) { + if(! local_user()) return; @@ -175,17 +176,20 @@ function facebook_post_hook(&$a,&$b) { if($appid && $secret) { + logger('facebook: have appid+secret'); + $fb_post = intval(get_pconfig(local_user(),'facebook','post')); $fb_enable = intval(get_pconfig(local_user(),'facebook','enable')); $fb_token = get_pconfig(local_user(),'facebook','access_token'); if($fb_post && $fb_token && $fb_enable) { + logger('facebook: able to post'); require_once('library/facebook.php'); require_once('include/bbcode.php'); $msg = $b['body']; - logger('Facebook post2: msg=' . $msg, LOGGER_DATA); + logger('Facebook post: original msg=' . $msg, LOGGER_DATA); // make links readable before we strip the code