diff --git a/.gitignore b/.gitignore
index b300f579e..5b7e09b50 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,7 +12,7 @@ addon
*~
robots.txt
-#ignore documentation, it should be newly built
+#ignore documentation, it should be newly built
doc/html
#ignore reports, should be generted with every build
@@ -23,7 +23,7 @@ report/
.buildpath
.externalToolBuilders
.settings
-#ignore OSX .DS_Store files
+#ignore OSX .DS_Store files
.DS_Store
/nbproject/private/
diff --git a/boot.php b/boot.php
index 4ef30eada..58b4bc098 100644
--- a/boot.php
+++ b/boot.php
@@ -6,17 +6,19 @@
/**
* Friendica
- *
+ *
* Friendica is a communications platform for integrated social communications
* utilising decentralised communications and linkage to several indie social
* projects - as well as popular mainstream providers.
- *
+ *
* Our mission is to free our friends and families from the clutches of
* data-harvesting corporations, and pave the way to a future where social
* communications are free and open and flow between alternate providers as
* easily as email does today.
*/
+require_once('include/autoloader.php');
+
require_once('include/config.php');
require_once('include/network.php');
require_once('include/plugin.php');
@@ -28,7 +30,7 @@ require_once('include/cache.php');
require_once('library/Mobile_Detect/Mobile_Detect.php');
require_once('include/features.php');
require_once('include/identity.php');
-
+require_once('include/pidfile.php');
require_once('update.php');
require_once('include/dbstructure.php');
@@ -463,11 +465,12 @@ class App {
public $plugins;
public $apps = array();
public $identities;
- public $is_mobile;
- public $is_tablet;
+ public $is_mobile = false;
+ public $is_tablet = false;
public $is_friendica_app;
public $performance = array();
public $callstack = array();
+ public $theme_info = array();
public $nav_sel;
@@ -588,15 +591,6 @@ class App {
if(x($_SERVER,'SERVER_NAME')) {
$this->hostname = $_SERVER['SERVER_NAME'];
- // See bug 437 - this didn't work so disabling it
- //if(stristr($this->hostname,'xn--')) {
- // PHP or webserver may have converted idn to punycode, so
- // convert punycode back to utf-8
- // require_once('library/simplepie/idn/idna_convert.class.php');
- // $x = new idna_convert();
- // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
- //}
-
if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
$this->hostname .= ':' . $_SERVER['SERVER_PORT'];
/*
@@ -862,11 +856,11 @@ class App {
$shortcut_icon = get_config("system", "shortcut_icon");
if ($shortcut_icon == "")
- $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
+ $shortcut_icon = "images/friendica-32.png";
$touch_icon = get_config("system", "touch_icon");
if ($touch_icon == "")
- $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
+ $touch_icon = "images/friendica-128.png";
$tpl = get_markup_template('head.tpl');
$this->page['htmlhead'] = replace_macros($tpl,array(
@@ -945,6 +939,25 @@ class App {
}
+ /**
+ * @brief Removes the baseurl from an url. This avoids some mixed content problems.
+ *
+ * @param string $url
+ *
+ * @return string The cleaned url
+ */
+ function remove_baseurl($url){
+
+ // Is the function called statically?
+ if (!is_object($this))
+ return(self::$a->remove_baseurl($url));
+
+ $url = normalise_link($url);
+ $base = normalise_link($this->get_baseurl());
+ $url = str_replace($base."/", "", $url);
+ return $url;
+ }
+
/**
* @brief Register template engine class
*
@@ -1034,22 +1047,42 @@ class App {
function save_timestamp($stamp, $value) {
$duration = (float)(microtime(true)-$stamp);
+ if (!isset($this->performance[$value])) {
+ // Prevent ugly E_NOTICE
+ $this->performance[$value] = 0;
+ }
+
$this->performance[$value] += (float)$duration;
$this->performance["marktime"] += (float)$duration;
- // Trace the different functions with their timestamps
- $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
+ $callstack = $this->callstack();
+ if (!isset($this->callstack[$value][$callstack])) {
+ // Prevent ugly E_NOTICE
+ $this->callstack[$value][$callstack] = 0;
+ }
+
+ $this->callstack[$value][$callstack] += (float)$duration;
+
+ }
+
+ /**
+ * @brief Returns a string with a callstack. Can be used for logging.
+ *
+ * @return string
+ */
+ function callstack() {
+ $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
+
+ // We remove the first two items from the list since they contain data that we don't need.
+ array_shift($trace);
array_shift($trace);
- $function = array();
+ $callstack = array();
foreach ($trace AS $func)
- $function[] = $func["function"];
-
- $function = implode(", ", $function);
-
- $this->callstack[$value][$function] += (float)$duration;
+ $callstack[] = $func["function"];
+ return implode(", ", $callstack);
}
function mark_timestamp($mark) {
@@ -1065,6 +1098,55 @@ class App {
return($this->is_friendica_app);
}
+ /**
+ * @brief Checks if the maximum load is reached
+ *
+ * @return bool Is the load reached?
+ */
+ function maxload_reached() {
+
+ $maxsysload = intval(get_config('system', 'maxloadavg'));
+ if ($maxsysload < 1)
+ $maxsysload = 50;
+
+ $load = current_load();
+ if ($load) {
+ if (intval($load) > $maxsysload) {
+ logger('system: load '.$load.' too high.');
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @brief Checks if the process is already running
+ *
+ * @param string $taskname The name of the task that will be used for the name of the lockfile
+ * @param string $task The path and name of the php script
+ * @param int $timeout The timeout after which a task should be killed
+ *
+ * @return bool Is the process running?
+ */
+ function is_already_running($taskname, $task = "", $timeout = 540) {
+
+ $lockpath = get_lockpath();
+ if ($lockpath != '') {
+ $pidfile = new pidfile($lockpath, $taskname);
+ if ($pidfile->is_already_running()) {
+ logger("Already running");
+ if ($pidfile->running_time() > $timeout) {
+ $pidfile->kill();
+ logger("killed stale process");
+ // Calling a new instance
+ if ($task != "")
+ proc_run('php', $task);
+ }
+ return true;
+ }
+ }
+ return false;
+ }
}
/**
@@ -1416,7 +1498,7 @@ function login($register = false, $hiddens=false) {
$noid = get_config('system','no_openid');
- $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
+ $dest_url = $a->query_string;
if(local_user()) {
$tpl = get_markup_template("logout.tpl");
@@ -1476,6 +1558,9 @@ function killme() {
* @brief Redirect to another URL and terminate this process.
*/
function goaway($s) {
+ if (!strstr(normalise_link($s), "http://"))
+ $s = App::get_baseurl()."/".$s;
+
header("Location: $s");
killme();
}
@@ -1735,9 +1820,9 @@ function current_theme_url() {
$opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
if (file_exists('view/theme/' . $t . '/style.php'))
- return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
+ return('view/theme/'.$t.'/style.pcss'.$opts);
- return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
+ return('view/theme/'.$t.'/style.css');
}
function feed_birthday($uid,$tz) {
diff --git a/database.sql b/database.sql
index 70b315ea2..89b821e23 100644
--- a/database.sql
+++ b/database.sql
@@ -1,6 +1,6 @@
-- ------------------------------------------
-- Friendica 3.5-dev (Asparagus)
--- DB_UPDATE_VERSION 1193
+-- DB_UPDATE_VERSION 1194
-- ------------------------------------------
@@ -119,6 +119,7 @@ CREATE TABLE IF NOT EXISTS `contact` (
`keywords` text NOT NULL,
`gender` varchar(32) NOT NULL DEFAULT '',
`attag` varchar(255) NOT NULL DEFAULT '',
+ `avatar` varchar(255) NOT NULL DEFAULT '',
`photo` text NOT NULL,
`thumb` text NOT NULL,
`micro` text NOT NULL,
@@ -200,17 +201,6 @@ CREATE TABLE IF NOT EXISTS `deliverq` (
PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
---
--- TABLE dsprphotoq
---
-CREATE TABLE IF NOT EXISTS `dsprphotoq` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `uid` int(11) NOT NULL DEFAULT 0,
- `msg` mediumtext NOT NULL,
- `attempt` tinyint(4) NOT NULL DEFAULT 0,
- PRIMARY KEY(`id`)
-) DEFAULT CHARSET=utf8;
-
--
-- TABLE event
--
@@ -411,21 +401,6 @@ CREATE TABLE IF NOT EXISTS `gserver` (
INDEX `nurl` (`nurl`)
) DEFAULT CHARSET=utf8;
---
--- TABLE guid
---
-CREATE TABLE IF NOT EXISTS `guid` (
- `id` int(10) unsigned NOT NULL auto_increment,
- `guid` varchar(255) NOT NULL DEFAULT '',
- `plink` varchar(255) NOT NULL DEFAULT '',
- `uri` varchar(255) NOT NULL DEFAULT '',
- `network` varchar(32) NOT NULL DEFAULT '',
- PRIMARY KEY(`id`),
- INDEX `guid` (`guid`),
- INDEX `plink` (`plink`),
- INDEX `uri` (`uri`)
-) DEFAULT CHARSET=utf8;
-
--
-- TABLE hook
--
@@ -926,13 +901,11 @@ CREATE TABLE IF NOT EXISTS `session` (
CREATE TABLE IF NOT EXISTS `sign` (
`id` int(10) unsigned NOT NULL auto_increment,
`iid` int(10) unsigned NOT NULL DEFAULT 0,
- `retract_iid` int(10) unsigned NOT NULL DEFAULT 0,
`signed_text` mediumtext NOT NULL,
`signature` text NOT NULL,
`signer` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY(`id`),
- INDEX `iid` (`iid`),
- INDEX `retract_iid` (`retract_iid`)
+ INDEX `iid` (`iid`)
) DEFAULT CHARSET=utf8;
--
diff --git a/doc/Accesskeys.md b/doc/Accesskeys.md
index c49e79c0a..4f16ba253 100644
--- a/doc/Accesskeys.md
+++ b/doc/Accesskeys.md
@@ -37,10 +37,7 @@ General
* o: Profile
* t: Contacts
* d: Common friends
-* b: Toggle Blocked status
-* i: Toggle Ignored status
-* v: Toggle Archive status
-* r: Repair
+* r: Advanced
/message
--------
diff --git a/doc/BBCode.md b/doc/BBCode.md
index fe7c1481f..186b1cda9 100644
--- a/doc/BBCode.md
+++ b/doc/BBCode.md
@@ -143,6 +143,56 @@ Map
You can embed maps from coordinates or addresses.
This require "openstreetmap" addon version 1.3 or newer.
+-----------------------------------------------------------
+
+Abstract for longer posts
+-------------------------
+
+If you want to spread your post to several third party networks you can have the problem that these networks have (for example) a length limitation.
+(Like on Twitter)
+
+Friendica is using a semi intelligent mechanism to generate a fitting abstract.
+But it can be interesting to define an own abstract that will only be displayed on the external network.
+This is done with the [abstract]-element.
+Example:
+
+
[abstract]Totally interesting! A must-see! Please click the link![/abstract]
+I want to tell you a really boring story that you really never wanted
+to hear.
+
+Twitter would display the text "Totally interesting! A must-see! Please click the link!".
+On Friendica you would only see the text after "I want to tell you a really ..."
+
+It is even possible to define abstracts for separate networks:
+
+
+[abstract]Hi friends Here are my newest pictures![abstract]
+[abstract=twit]Hi my dear Twitter followers. Do you want to see my new
+pictures?[abstract]
+[abstract=apdn]Helly my dear followers on ADN. I made sone new pictures
+that I wanted to share with you.[abstract]
+Today I was in the woods and took some real cool pictures ...
+
+
+For Twitter and App.net the system will use the defined abstracts.
+For other networks (e.g. when you are using the "statusnet" connector that is used to post to GNU Social) the general abstract element will be used.
+
+If you use (for example) the "buffer" connector to post to Facebook or Google+ you can use this element to define an abstract for a longer blogpost that you don't want to post completely to these networks.
+
+Networks like Facebook or Google+ aren't length limited.
+For this reason the [abstract] element isn't used.
+Instead you have to name the explicit network:
+
+
+[abstract]These days I had a strange encounter ...[abstract]
+[abstract=goog]Helly my dear Google+ followers. You have to read my
+newest blog post![abstract]
+[abstract=face]Hello my Facebook friends. These days happened something
+really cool.[abstract]
+While taking pictures in the woods I had a really strange encounter ...
+
+The [abstract] element isn't working with the native OStatus connection or with connectors where we post the HTML.
+(Like Tumblr, Wordpress or Pump.io)
Special
-------
@@ -150,5 +200,3 @@ Special
If you need to put literal bbcode in a message, [noparse], [nobb] or [pre] are used to escape bbcode:
[noparse][b]bold[/b][/noparse]
: [b]bold[/b]
-
-
diff --git a/doc/Bugs-and-Issues.md b/doc/Bugs-and-Issues.md
index 366b2ed66..0ece265a2 100644
--- a/doc/Bugs-and-Issues.md
+++ b/doc/Bugs-and-Issues.md
@@ -6,6 +6,8 @@ Bugs and Issues
If your server has a support page, you should report any bugs/issues you encounter there first.
Reporting to your support page before reporting to the developers makes their job easier, as they don't have to deal with bug reports that might not have anything to do with them.
This helps us get new features faster.
+You can also contact the [friendica support forum](https://helpers.pyxis.uberspace.de/profile/helpers) and report your problem there.
+Maybe someone from another node encountered the problem as well and can help you.
If you're a technical user, or your site doesn't have a support page, you'll need to use the [Bug Tracker](http://bugs.friendica.com/).
Please perform a search to see if there's already an open bug that matches yours before submitting anything.
diff --git a/doc/Connectors.md b/doc/Connectors.md
index cd4b643f1..148352c55 100644
--- a/doc/Connectors.md
+++ b/doc/Connectors.md
@@ -57,13 +57,15 @@ All that the pages need to have is a discoverable feed using either the RSS or A
Twitter
---
-To follow a Twitter member, put the URL of the Twitter member's main page into the Connect box on your [Contacts](contacts) page.
+To follow a Twitter member, the Twitter-Connector (Addon) needs to be configured on your node.
+If this is the case put the URL of the Twitter member's main page into the Connect box on your [Contacts](contacts) page.
To reply, you must have the Twitter connector installed, and reply using your own status editor.
Begin the message with @twitterperson replacing with the Twitter username.
Email
---
+If the php module for IMAP support is available on your server, Friendica can connect to email contacts as well.
Configure the email connector from your [Settings](settings) page.
Once this has been done, you may enter an email address to connect with using the Connect box on your [Contacts](contacts) page.
They must be the sender of a message which is currently in your INBOX for the connection to succeed.
diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md
index 10bbd5632..8e3cd03b1 100644
--- a/doc/Developers-Intro.md
+++ b/doc/Developers-Intro.md
@@ -83,11 +83,11 @@ Ask us to find out whom to talk to about their experiences.
Do not worry about cross-posting.
###Client software
-There are free software clients that do somehow work with Friendica but most of them need love and maintenance.
-Also, they were mostly made for other platforms using the GNU Social API.
-This means they lack the features that are really specific to Friendica.
-Popular clients you might want to have a look at are:
+As Friendica is using a [Twitter/GNU Social compatible API](help/api) any of the clients for those platforms should work with Friendica as well.
+Furthermore there are several client projects, especially for use with Friendica.
+If you are interested in improving those clients, please contact the developers of the clients directly.
-* [Hotot (Linux)](http://hotot.org/) - abandoned
-* [Friendica for Android](https://github.com/max-weller/friendica-for-android) - abandoned
-* You can find more working client software in [Wikipedia](https://en.wikipedia.org/wiki/Friendica).
+* Android / CynogenMod: **Friendica for Android** [src](https://github.com/max-weller/friendica-for-android), [homepage](http://friendica.android.max-weller.de/) - abandoned
+* iOS: *currently no client*
+* SailfishOS: **Friendiy** [src](https://kirgroup.com/projects/fabrixxm/harbour-friendly) - developed by [Fabio](https://kirgroup.com/profile/fabrixxm/?tab=profile)
+* Windows: **Friendica Mobile** for Windows versions [before 8.1](http://windowsphone.com/s?appid=e3257730-c9cf-4935-9620-5261e3505c67) and [Windows 10](https://www.microsoft.com/store/apps/9nblggh0fhmn) - developed by [Gerhard Seeber](http://mozartweg.dyndns.org/friendica/profile/gerhard/?tab=profile)
diff --git a/doc/Home.md b/doc/Home.md
index 3b6442867..1f9b0cfab 100644
--- a/doc/Home.md
+++ b/doc/Home.md
@@ -47,8 +47,10 @@ Friendica Documentation and Resources
* [Theme Development](help/themes)
* [Smarty 3 Templates](help/smarty3-templates)
* [Database schema documantation](help/database)
+* [Class Autoloading](help/autoloader)
* [Code - Reference(Doxygen generated - sets cookies)](doc/html/)
+
**External Resources**
* [Main Website](http://friendica.com)
diff --git a/doc/Plugins.md b/doc/Plugins.md
index 24d403e1f..a30a3f4a7 100644
--- a/doc/Plugins.md
+++ b/doc/Plugins.md
@@ -1,5 +1,7 @@
Friendica Addon/Plugin development
-==========================
+==============
+
+* [Home](help)
Please see the sample addon 'randplace' for a working example of using some of these features.
Addons work by intercepting event hooks - which must be registered.
@@ -16,12 +18,12 @@ Future extensions may provide for "setup" amd "remove".
Plugins should contain a comment block with the four following parameters:
- /*
- * Name: My Great Plugin
- * Description: This is what my plugin does. It's really cool
- * Version: 1.0
- * Author: John Q. Public
- */
+ /*
+ * Name: My Great Plugin
+ * Description: This is what my plugin does. It's really cool.
+ * Version: 1.0
+ * Author: John Q. Public
+ */
Register your plugin hooks during installation.
@@ -45,7 +47,7 @@ Your hook callback functions will be called with at least one and possibly two a
If you wish to make changes to the calling data, you must declare them as reference variables (with '&') during function declaration.
-###$a
+#### $a
$a is the Friendica 'App' class.
It contains a wealth of information about the current state of Friendica:
@@ -56,13 +58,13 @@ It contains a wealth of information about the current state of Friendica:
It is recommeded you call this '$a' to match its usage elsewhere.
-###$b
+#### $b
$b can be called anything you like.
This is information specific to the hook currently being processed, and generally contains information that is being immediately processed or acted on that you can use, display, or alter.
Remember to declare it with '&' if you wish to alter it.
Modules
---------
+---
Plugins/addons may also act as "modules" and intercept all page requests for a given URL path.
In order for a plugin to act as a module it needs to define a function "plugin_name_module()" which takes no arguments and needs not do anything.
@@ -72,15 +74,15 @@ These are parsed into an array $a->argv, with a corresponding $a->argc indicatin
So http://my.web.site/plugin/arg1/arg2 would look for a module named "plugin" and pass its module functions the $a App structure (which is available to many components).
This will include:
- $a->argc = 3
- $a->argv = array(0 => 'plugin', 1 => 'arg1', 2 => 'arg2');
+ $a->argc = 3
+ $a->argv = array(0 => 'plugin', 1 => 'arg1', 2 => 'arg2');
Your module functions will often contain the function plugin_name_content(&$a), which defines and returns the page body content.
They may also contain plugin_name_post(&$a) which is called before the _content function and typically handles the results of POST forms.
You may also have plugin_name_init(&$a) which is called very early on and often does module initialisation.
Templates
-----------
+---
If your plugin needs some template, you can use the Friendica template system.
Friendica uses [smarty3](http://www.smarty.net/) as a template engine.
@@ -104,140 +106,140 @@ See also the wiki page [Quick Template Guide](https://github.com/friendica/frien
Current hooks
-------------
-###'authenticate'
+### 'authenticate'
'authenticate' is called when a user attempts to login.
$b is an array containing:
- 'username' => the supplied username
- 'password' => the supplied password
+ 'username' => the supplied username
+ 'password' => the supplied password
'authenticated' => set this to non-zero to authenticate the user.
'user_record' => successful authentication must also return a valid user record from the database
-###'logged_in'
+### 'logged_in'
'logged_in' is called after a user has successfully logged in.
$b contains the $a->user array.
-###'display_item'
+### 'display_item'
'display_item' is called when formatting a post for display.
$b is an array:
'item' => The item (array) details pulled from the database
'output' => the (string) HTML representation of this item prior to adding it to the page
-###'post_local'
+### 'post_local'
* called when a status post or comment is entered on the local system
* $b is the item array of the information to be stored in the database
* Please note: body contents are bbcode - not HTML
-###'post_local_end'
+### 'post_local_end'
* called when a local status post or comment has been stored on the local system
* $b is the item array of the information which has just been stored in the database
* Please note: body contents are bbcode - not HTML
-###'post_remote'
+### 'post_remote'
* called when receiving a post from another source. This may also be used to post local activity or system generated messages.
* $b is the item array of information to be stored in the database and the item body is bbcode.
-###'settings_form'
+### 'settings_form'
* called when generating the HTML for the user Settings page
* $b is the (string) HTML of the settings page before the final '' tag.
-###'settings_post'
+### 'settings_post'
* called when the Settings pages are submitted
* $b is the $_POST array
-###'plugin_settings'
+### 'plugin_settings'
* called when generating the HTML for the addon settings page
* $b is the (string) HTML of the addon settings page before the final '' tag.
-###'plugin_settings_post'
+### 'plugin_settings_post'
* called when the Addon Settings pages are submitted
* $b is the $_POST array
-###'profile_post'
+### 'profile_post'
* called when posting a profile page
* $b is the $_POST array
-###'profile_edit'
+### 'profile_edit'
'profile_edit' is called prior to output of profile edit page.
$b is an array containing:
'profile' => profile (array) record from the database
'entry' => the (string) HTML of the generated entry
-###'profile_advanced'
+### 'profile_advanced'
* called when the HTML is generated for the 'Advanced profile', corresponding to the 'Profile' tab within a person's profile page
* $b is the (string) HTML representation of the generated profile
* The profile array details are in $a->profile.
-###'directory_item'
+### 'directory_item'
'directory_item' is called from the Directory page when formatting an item for display.
$b is an array:
'contact' => contact (array) record for the person from the database
'entry' => the (string) HTML of the generated entry
-###'profile_sidebar_enter'
+### 'profile_sidebar_enter'
* called prior to generating the sidebar "short" profile for a page
* $b is the person's profile array
-###'profile_sidebar'
+### 'profile_sidebar'
'profile_sidebar is called when generating the sidebar "short" profile for a page.
$b is an array:
'profile' => profile (array) record for the person from the database
'entry' => the (string) HTML of the generated entry
-###'contact_block_end'
+### 'contact_block_end'
is called when formatting the block of contacts/friends on a profile sidebar has completed.
$b is an array:
'contacts' => array of contacts
'output' => the (string) generated HTML of the contact block
-###'bbcode'
+### 'bbcode'
* called during conversion of bbcode to html
* $b is a string converted text
-###'html2bbcode'
+### 'html2bbcode'
* called during conversion of html to bbcode (e.g. remote message posting)
* $b is a string converted text
-###'page_header'
+### 'page_header'
* called after building the page navigation section
* $b is a string HTML of nav region
-###'personal_xrd'
+### 'personal_xrd'
'personal_xrd' is called prior to output of personal XRD file.
$b is an array:
'user' => the user record for the person
'xml' => the complete XML to be output
-###'home_content'
+### 'home_content'
* called prior to output home page content, shown to unlogged users
* $b is (string) HTML of section region
-###'contact_edit'
+### 'contact_edit'
is called when editing contact details on an individual from the Contacts page.
$b is an array:
'contact' => contact record (array) of target contact
'output' => the (string) generated HTML of the contact edit page
-###'contact_edit_post'
+### 'contact_edit_post'
* called when posting the contact edit page.
* $b is the $_POST array
-###'init_1'
+### 'init_1'
* called just after DB has been opened and before session start
* $b is not used or passed
-###'page_end'
+### 'page_end'
* called after HTML content functions have completed
* $b is (string) HTML of content div
-###'avatar_lookup'
+### 'avatar_lookup'
'avatar_lookup' is called when looking up the avatar.
$b is an array:
@@ -245,11 +247,11 @@ $b is an array:
'email' => email to look up the avatar for
'url' => the (string) generated URL of the avatar
-###'emailer_send_prepare'
+### 'emailer_send_prepare'
'emailer_send_prepare' called from Emailer::send() before building the mime message.
$b is an array, params to Emailer::send()
- 'fromName' => name of the sender
+ 'fromName' => name of the sender
'fromEmail' => email fo the sender
'replyTo' => replyTo address to direct responses
'toEmail' => destination email address
@@ -258,20 +260,20 @@ $b is an array, params to Emailer::send()
'textVersion' => text only version of the message
'additionalMailHeader' => additions to the smtp mail header
-###'emailer_send'
+### 'emailer_send'
is called before calling PHP's mail().
$b is an array, params to mail()
- 'to'
- 'subject'
+ 'to'
+ 'subject'
'body'
'headers'
-###'nav_info'
+### 'nav_info'
is called after the navigational menu is build in include/nav.php.
$b is an array containing $nav from nav.php.
-###'template_vars'
+### 'template_vars'
is called before vars are passed to the template engine to render the page.
The registered function can add,change or remove variables passed to template.
$b is an array with:
@@ -463,4 +465,3 @@ mod/cb.php: call_hooks('cb_afterpost');
mod/cb.php: call_hooks('cb_content', $o);
mod/directory.php: call_hooks('directory_item', $arr);
-
diff --git a/doc/SSL.md b/doc/SSL.md
index a72eec2a1..bcff929fe 100644
--- a/doc/SSL.md
+++ b/doc/SSL.md
@@ -90,8 +90,8 @@ If you run your own server, upload the files and check out the Mozilla wiki link
Let's encrypt
---
-If you run your own server and you control your name server, the "Let's encrypt" initiative might become an interesting alternative.
-Their offer is not ready, yet.
+If you run your own server, the "Let's encrypt" initiative might become an interesting alternative.
+Their offer is in public beta right now.
Check out [their website](https://letsencrypt.org/) for status updates.
Web server settings
diff --git a/doc/Settings.md b/doc/Settings.md
index 86254cb29..7d909afa0 100644
--- a/doc/Settings.md
+++ b/doc/Settings.md
@@ -11,8 +11,6 @@ Hot Keys
Friendica traps the following keyboard events:
* [Pause] - Pauses "Ajax" update activity. This is the process that provides updates without reloading the page. You may wish to pause it to reduce network usage and/or as a debugging aid for javascript developers. A pause indicator will appear at the lower right hand corner of the page. Hit the [pause] key once again to resume.
-* [F8] - Displays a language selector
-
Birthday Notifications
---
diff --git a/doc/api.md b/doc/api.md
index ced078f55..7d6f440c5 100644
--- a/doc/api.md
+++ b/doc/api.md
@@ -1,12 +1,27 @@
Friendica API
===
-The Friendica API aims to be compatible to the [GNU Social API](http://skilledtests.com/wiki/Twitter-compatible_API) and the [Twitter API](https://dev.twitter.com/rest/public).
+The Friendica API aims to be compatible to the [GNU Social API](http://wiki.gnusocial.de/gnusocial:api) and the [Twitter API](https://dev.twitter.com/rest/public).
Please refer to the linked documentation for further information.
## Implemented API calls
### General
+#### HTTP Method
+
+API endpoints can restrict the method used to request them.
+Using an invalid method results in HTTP error 405 "Method Not Allowed".
+
+In this document, the required method is listed after the endpoint name. "*" means every method can be used.
+
+#### Auth
+
+Friendica supports basic http auth and OAuth 1 to authenticate the user to the api.
+
+OAuth settings can be added by the user in web UI under /settings/oauth/
+
+In this document, endpoints which requires auth are marked with "AUTH" after endpoint name
+
#### Unsupported parameters
* cursor: Not implemented in GNU Social
* trim_user: Not implemented in GNU Social
@@ -38,9 +53,9 @@ Error body is
json:
```
{
- "error": "Specific error message",
- "request": "API path requested",
- "code": "HTTP error code"
+ "error": "Specific error message",
+ "request": "API path requested",
+ "code": "HTTP error code"
}
```
@@ -54,19 +69,20 @@ xml:
```
---
-### account/rate_limit_status
+### account/rate_limit_status (*; AUTH)
---
-### account/verify_credentials
+### account/verify_credentials (*; AUTH)
#### Parameters
+
* skip_status: Don't show the "status" field. (Default: false)
* include_entities: "true" shows entities for pictures and links (Default: false)
---
-### conversation/show
+### conversation/show (*; AUTH)
Unofficial Twitter command. It shows all direct answers (excluding the original post) to a given id.
-#### Parameters
+#### Parameter
* id: id of the post
* count: Items per page (default: 20)
* page: page number
@@ -80,7 +96,7 @@ Unofficial Twitter command. It shows all direct answers (excluding the original
* contributor_details
---
-### direct_messages
+### direct_messages (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -93,7 +109,7 @@ Unofficial Twitter command. It shows all direct answers (excluding the original
* skip_status
---
-### direct_messages/all
+### direct_messages/all (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -102,7 +118,7 @@ Unofficial Twitter command. It shows all direct answers (excluding the original
* getText: Defines the format of the status field. Can be "html" or "plain"
---
-### direct_messages/conversation
+### direct_messages/conversation (*; AUTH)
Shows all direct messages of a conversation
#### Parameters
* count: Items per page (default: 20)
@@ -113,7 +129,7 @@ Shows all direct messages of a conversation
* uri: URI of the conversation
---
-### direct_messages/new
+### direct_messages/new (POST,PUT; AUTH)
#### Parameters
* user_id: id of the user
* screen_name: screen name (for technical reasons, this value is not unique!)
@@ -122,7 +138,7 @@ Shows all direct messages of a conversation
* title: Title of the direct message
---
-### direct_messages/sent
+### direct_messages/sent (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -132,7 +148,7 @@ Shows all direct messages of a conversation
* include_entities: "true" shows entities for pictures and links (Default: false)
---
-### favorites
+### favorites (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -144,22 +160,23 @@ Shows all direct messages of a conversation
* user_id
* screen_name
-Favorites aren't displayed to other users, so "user_id" and "screen_name". So setting this value will result in an empty array.
+Favorites aren't displayed to other users, so "user_id" and "screen_name" are unsupported.
+Set this values will result in an empty array.
---
-### favorites/create
+### favorites/create (POST,PUT; AUTH)
#### Parameters
* id
* include_entities: "true" shows entities for pictures and links (Default: false)
---
-### favorites/destroy
+### favorites/destroy (POST,DELETE; AUTH)
#### Parameters
* id
* include_entities: "true" shows entities for pictures and links (Default: false)
---
-### followers/ids
+### followers/ids (*; AUTH)
#### Parameters
* stringify_ids: Should the id numbers be sent as text (true) or number (false)? (default: false)
@@ -171,139 +188,7 @@ Favorites aren't displayed to other users, so "user_id" and "screen_name". So se
Friendica doesn't allow showing followers of other users.
---
-### friendica/activity/
-#### parameters
-* id: item id
-
-Add or remove an activity from an item.
-'verb' can be one of:
-- like
-- dislike
-- attendyes
-- attendno
-- attendmaybe
-
-To remove an activity, prepend the verb with "un", eg. "unlike" or "undislike"
-Attend verbs disable eachother: that means that if "attendyes" was added to an item, adding "attendno" remove previous "attendyes".
-Attend verbs should be used only with event-related items (there is no check at the moment)
-
-#### Return values
-
-On success:
-json
-```"ok"```
-
-xml
-```true```
-
-On error:
-HTTP 400 BadRequest
-
----
-### friendica/photo
-#### Parameters
-* photo_id: Resource id of a photo.
-* scale: (optional) scale value of the photo
-
-Returns data of a picture with the given resource.
-If 'scale' isn't provided, returned data include full url to each scale of the photo.
-If 'scale' is set, returned data include image data base64 encoded.
-
-possibile scale value are:
-0: original or max size by server settings
-1: image with or height at <= 640
-2: image with or height at <= 320
-3: thumbnail 160x160
-
-4: Profile image at 175x175
-5: Profile image at 80x80
-6: Profile image at 48x48
-
-An image used as profile image has only scale 4-6, other images only 0-3
-
-#### Return values
-
-json
-```
- {
- "id": "photo id"
- "created": "date(YYYY-MM-GG HH:MM:SS)",
- "edited": "date(YYYY-MM-GG HH:MM:SS)",
- "title": "photo title",
- "desc": "photo description",
- "album": "album name",
- "filename": "original file name",
- "type": "mime type",
- "height": "number",
- "width": "number",
- "profile": "1 if is profile photo",
- "link": {
- "": "url to image"
- ...
- },
- // if 'scale' is set
- "datasize": "size in byte",
- "data": "base64 encoded image data"
- }
-```
-
-xml
-```
-
- photo id
- date(YYYY-MM-GG HH:MM:SS)
- date(YYYY-MM-GG HH:MM:SS)
- photo title
- photo description
- album name
- original file name
- mime type
- number
- number
- 1 if is profile photo
-
-
- ...
-
-
-```
-
----
-### friendica/photos/list
-
-Returns a list of all photo resources of the logged in user.
-
-#### Return values
-
-json
-```
- [
- {
- id: "resource_id",
- album: "album name",
- filename: "original file name",
- type: "image mime type",
- thumb: "url to thumb sized image"
- },
- ...
- ]
-```
-
-xml
-```
-
-
- "url to thumb sized image"
-
- ...
-
-```
-
----
-### friends/ids
+### friends/ids (*; AUTH)
#### Parameters
* stringify_ids: Should the id numbers be sent as text (true) or number (false)? (default: false)
@@ -315,15 +200,15 @@ xml
Friendica doesn't allow showing friends of other users.
---
-### help/test
+### help/test (*)
---
-### media/upload
+### media/upload (POST,PUT; AUTH)
#### Parameters
* media: image data
---
-### oauth/request_token
+### oauth/request_token (*)
#### Parameters
* oauth_callback
@@ -331,7 +216,7 @@ Friendica doesn't allow showing friends of other users.
* x_auth_access_type
---
-### oauth/access_token
+### oauth/access_token (*)
#### Parameters
* oauth_verifier
@@ -341,7 +226,7 @@ Friendica doesn't allow showing friends of other users.
* x_auth_mode
---
-### statuses/destroy
+### statuses/destroy (POST,DELETE; AUTH)
#### Parameters
* id: message number
* include_entities: "true" shows entities for pictures and links (Default: false)
@@ -350,15 +235,21 @@ Friendica doesn't allow showing friends of other users.
* trim_user
---
-### statuses/followers
+### statuses/followers (*; AUTH)
+
+#### Parameters
+
* include_entities: "true" shows entities for pictures and links (Default: false)
---
-### statuses/friends
+### statuses/friends (*; AUTH)
+
+#### Parameters
+
* include_entities: "true" shows entities for pictures and links (Default: false)
---
-### statuses/friends_timeline
+### statuses/friends_timeline (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -374,7 +265,7 @@ Friendica doesn't allow showing friends of other users.
* contributor_details
---
-### statuses/home_timeline
+### statuses/home_timeline (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -390,7 +281,7 @@ Friendica doesn't allow showing friends of other users.
* contributor_details
---
-### statuses/mentions
+### statuses/mentions (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -404,7 +295,7 @@ Friendica doesn't allow showing friends of other users.
* contributor_details
---
-### statuses/public_timeline
+### statuses/public_timeline (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -418,7 +309,7 @@ Friendica doesn't allow showing friends of other users.
* trim_user
---
-### statuses/replies
+### statuses/replies (*; AUTH)
#### Parameters
* count: Items per page (default: 20)
* page: page number
@@ -432,7 +323,7 @@ Friendica doesn't allow showing friends of other users.
* contributor_details
---
-### statuses/retweet
+### statuses/retweet (POST,PUT; AUTH)
#### Parameters
* id: message number
* include_entities: "true" shows entities for pictures and links (Default: false)
@@ -441,7 +332,7 @@ Friendica doesn't allow showing friends of other users.
* trim_user
---
-### statuses/show
+### statuses/show (*; AUTH)
#### Parameters
* id: message number
* conversation: if set to "1" show all messages of the conversation with the given id
@@ -476,7 +367,7 @@ Friendica doesn't allow showing friends of other users.
* display_coordinates
---
-### statuses/user_timeline
+### statuses/user_timeline (*; AUTH)
#### Parameters
* user_id: id of the user
* screen_name: screen name (for technical reasons, this value is not unique!)
@@ -489,15 +380,28 @@ Friendica doesn't allow showing friends of other users.
* include_entities: "true" shows entities for pictures and links (Default: false)
#### Unsupported parameters
+
* include_rts
* trim_user
* contributor_details
---
-### statusnet/config
+### statusnet/config (*)
---
-### statusnet/version
+### statusnet/conversation (*; AUTH)
+It shows all direct answers (excluding the original post) to a given id.
+
+#### Parameter
+* id: id of the post
+* count: Items per page (default: 20)
+* page: page number
+* since_id: minimal id
+* max_id: maximum id
+* include_entities: "true" shows entities for pictures and links (Default: false)
+
+---
+### statusnet/version (*)
#### Unsupported parameters
* user_id
@@ -507,7 +411,7 @@ Friendica doesn't allow showing friends of other users.
Friendica doesn't allow showing followers of other users.
---
-### users/search
+### users/search (*)
#### Parameters
* q: name of the user
@@ -517,7 +421,7 @@ Friendica doesn't allow showing followers of other users.
* include_entities
---
-### users/show
+### users/show (*)
#### Parameters
* user_id: id of the user
* screen_name: screen name (for technical reasons, this value is not unique!)
@@ -533,8 +437,39 @@ Friendica doesn't allow showing friends of other users.
## Implemented API calls (not compatible with other APIs)
+
---
-### friendica/group_show
+### friendica/activity/
+#### parameters
+* id: item id
+
+Add or remove an activity from an item.
+'verb' can be one of:
+
+- like
+- dislike
+- attendyes
+- attendno
+- attendmaybe
+
+To remove an activity, prepend the verb with "un", eg. "unlike" or "undislike"
+Attend verbs disable eachother: that means that if "attendyes" was added to an item, adding "attendno" remove previous "attendyes".
+Attend verbs should be used only with event-related items (there is no check at the moment)
+
+#### Return values
+
+On success:
+json
+```"ok"```
+
+xml
+```true```
+
+On error:
+HTTP 400 BadRequest
+
+---
+### friendica/group_show (*; AUTH)
Return all or a specified group of the user with the containing contacts as array.
#### Parameters
@@ -542,22 +477,23 @@ Return all or a specified group of the user with the containing contacts as arra
#### Return values
Array of:
+
* name: name of the group
* gid: id of the group
* user: array of group members (return from api_get_user() function for each member)
---
-### friendica/group_delete
+### friendica/group_delete (POST,DELETE; AUTH)
delete the specified group of contacts; API call need to include the correct gid AND name of the group to be deleted.
----
-### Parameters
+#### Parameters
* gid: id of the group to be deleted
* name: name of the group to be deleted
#### Return values
Array of:
+
* success: true if successfully deleted
* gid: gid of the deleted group
* name: name of the deleted group
@@ -566,19 +502,22 @@ Array of:
---
-### friendica/group_create
+### friendica/group_create (POST,PUT; AUTH)
Create the group with the posted array of contacts as members.
+
#### Parameters
* name: name of the group to be created
#### POST data
-JSON data as Array like the result of „users/group_show“:
+JSON data as Array like the result of "users/group_show":
+
* gid
* name
* array of users
#### Return values
Array of:
+
* success: true if successfully created or reactivated
* gid: gid of the created group
* name: name of the created group
@@ -587,26 +526,175 @@ Array of:
---
-### friendica/group_update
+### friendica/group_update (POST)
Update the group with the posted array of contacts as members (post all members of the group to the call; function will remove members not posted).
+
#### Parameters
* gid: id of the group to be changed
* name: name of the group to be changed
#### POST data
JSON data as array like the result of „users/group_show“:
+
* gid
* name
* array of users
#### Return values
Array of:
+
* success: true if successfully updated
* gid: gid of the changed group
* name: name of the changed group
* status: „missing user“ | „ok“
* wrong users: array of users, which were not available in the contact table
+
+
+---
+### friendica/notifications (GET)
+Return last 50 notification for current user, ordered by date with unseen item on top
+
+#### Parameters
+none
+
+#### Return values
+Array of:
+
+* id: id of the note
+* type: type of notification as int (see NOTIFY_* constants in boot.php)
+* name: full name of the contact subject of the note
+* url: contact's profile url
+* photo: contact's profile photo
+* date: datetime string of the note
+* timestamp: timestamp of the node
+* date_rel: relative date of the note (eg. "1 hour ago")
+* msg: note message in bbcode
+* msg_html: note message in html
+* msg_plain: note message in plain text
+* link: link to note
+* seen: seen state: 0 or 1
+
+
+---
+### friendica/notifications/seen (POST)
+Set note as seen, returns item object if possible
+
+#### Parameters
+id: id of the note to set seen
+
+#### Return values
+If the note is linked to an item, the item is returned, just like one of the "statuses/*_timeline" api.
+
+If the note is not linked to an item, a success status is returned:
+
+* "success" (json) | "<status>success</status>" (xml)
+
+
+---
+### friendica/photo (*; AUTH)
+#### Parameters
+* photo_id: Resource id of a photo.
+* scale: (optional) scale value of the photo
+
+Returns data of a picture with the given resource.
+If 'scale' isn't provided, returned data include full url to each scale of the photo.
+If 'scale' is set, returned data include image data base64 encoded.
+
+possibile scale value are:
+
+* 0: original or max size by server settings
+* 1: image with or height at <= 640
+* 2: image with or height at <= 320
+* 3: thumbnail 160x160
+* 4: Profile image at 175x175
+* 5: Profile image at 80x80
+* 6: Profile image at 48x48
+
+An image used as profile image has only scale 4-6, other images only 0-3
+
+#### Return values
+
+json
+```
+ {
+ "id": "photo id"
+ "created": "date(YYYY-MM-GG HH:MM:SS)",
+ "edited": "date(YYYY-MM-GG HH:MM:SS)",
+ "title": "photo title",
+ "desc": "photo description",
+ "album": "album name",
+ "filename": "original file name",
+ "type": "mime type",
+ "height": "number",
+ "width": "number",
+ "profile": "1 if is profile photo",
+ "link": {
+ "": "url to image"
+ ...
+ },
+ // if 'scale' is set
+ "datasize": "size in byte",
+ "data": "base64 encoded image data"
+ }
+```
+
+xml
+```
+
+ photo id
+ date(YYYY-MM-GG HH:MM:SS)
+ date(YYYY-MM-GG HH:MM:SS)
+ photo title
+ photo description
+ album name
+ original file name
+ mime type
+ number
+ number
+ 1 if is profile photo
+
+
+ ...
+
+
+```
+
+---
+### friendica/photos/list (*; AUTH)
+
+Returns a list of all photo resources of the logged in user.
+
+#### Return values
+
+json
+```
+ [
+ {
+ id: "resource_id",
+ album: "album name",
+ filename: "original file name",
+ type: "image mime type",
+ thumb: "url to thumb sized image"
+ },
+ ...
+ ]
+```
+
+xml
+```
+
+
+ "url to thumb sized image"
+
+ ...
+
+```
+
+
---
## Not Implemented API calls
The following API calls are implemented in GNU Social but not in Friendica: (incomplete)
@@ -702,13 +790,13 @@ The following API calls from the Twitter API aren't implemented neither in Frien
### BASH / cURL
Betamax has documentated some example API usage from a [bash script](https://en.wikipedia.org/wiki/Bash_(Unix_shell) employing [curl](https://en.wikipedia.org/wiki/CURL) (see [his posting](https://betamax65.de/display/betamax65/43539)).
- /usr/bin/curl -u USER:PASS https://YOUR.FRIENDICA.TLD/api/statuses/update.xml -d source="some source id" -d status="the status you want to post"
+/usr/bin/curl -u USER:PASS https://YOUR.FRIENDICA.TLD/api/statuses/update.xml -d source="some source id" -d status="the status you want to post"
### Python
The [RSStoFriedika](https://github.com/pafcu/RSStoFriendika) code can be used as an example of how to use the API with python. The lines for posting are located at [line 21](https://github.com/pafcu/RSStoFriendika/blob/master/RSStoFriendika.py#L21) and following.
- def tweet(server, message, group_allow=None):
- url = server + '/api/statuses/update'
- urllib2.urlopen(url, urllib.urlencode({'status': message,'group_allow[]':group_allow}, doseq=True))
+def tweet(server, message, group_allow=None):
+url = server + '/api/statuses/update'
+urllib2.urlopen(url, urllib.urlencode({'status': message,'group_allow[]':group_allow}, doseq=True))
There is also a [module for python 3](https://bitbucket.org/tobiasd/python-friendica) for using the API.
diff --git a/doc/autoloader.md b/doc/autoloader.md
new file mode 100644
index 000000000..947eade23
--- /dev/null
+++ b/doc/autoloader.md
@@ -0,0 +1,209 @@
+Autoloader
+==========
+
+* [Home](help)
+
+There is some initial support to class autoloading in Friendica core.
+
+The autoloader code is in `include/autoloader.php`.
+It's derived from composer autoloader code.
+
+Namespaces and Classes are mapped to folders and files in `library/`,
+and the map must be updated by hand, because we don't use composer yet.
+The mapping is defined by files in `include/autoloader/` folder.
+
+Currently, only HTMLPurifier library is loaded using autoloader.
+
+
+## A quick introdution to class autoloading
+
+The autoloader it's a way for php to automagically include the file that define a class when the class is first used, without the need to use "require_once" every time.
+
+Once is setup you don't have to use it in any way. You need a class? you use the class.
+
+At his basic is a function passed to the "spl_autoload_register()" function, which receive as argument the class name the script want and is it job to include the correct php file where that class is defined.
+The best source for documentation is [php site](http://php.net/manual/en/language.oop5.autoload.php).
+
+One example, based on fictional friendica code.
+
+Let's say you have a php file in "include/" that define a very useful class:
+
+```
+ file: include/ItemsManager.php
+ array($baseDir."/include");
+ );
+```
+
+
+That tells the autoloader code to look for files that defines classes in "Friendica" namespace under "include/" folder. (And btw, that's why the file has the same name as the class it defines.)
+
+*note*: The structure of files in "include/autoloader/" has been copied from the code generated by composer, to ease the work of enable autoloader for external libraries under "library/"
+
+Let's say now that you need to load some items in a view, maybe in a fictional "mod/network.php".
+Somewere at the start of the scripts, the autoloader was initialized. In Friendica is done at the top of "boot.php", with "require_once('include/autoloader.php');".
+
+The code will be something like:
+
+```
+ file: mod/network.php
+ getAll();
+
+ // pass $items to template
+ // return result
+ }
+```
+
+That's a quite simple example, but look: no "require()"!
+You need to use a class, you use the class and you don't need to do anything more.
+
+Going further: now we have a bunch of "*Manager" classes that cause some code duplication, let's define a BaseManager class, where to move all code in common between all managers:
+
+```
+ file: include/BaseManager.php
+ [url]*url*[/url]
-Wenn *url* entweder oembed oder opengraph unterstützt wird das eingebettete
-Objekt (z.B. ein Dokument von scribd) eingebunden.
+Wenn *url* entweder oembed oder opengraph unterstützt wird das eingebettete Objekt (z.B. ein Dokument von scribd) eingebunden.
Der Titel der Seite mit einem Link zur *url* wird ebenfalls angezeigt.
Um eine Karte in einen Beitrag einzubinden, muss das *openstreetmap* Addon aktiviert werden. Ist dies der Fall, kann mit
@@ -145,11 +144,54 @@ eine Karte von [OpenStreetmap](http://openstreetmap.org) eingebettet werden. Zur
oder eine Adresse in obiger Form verwendet werden.
+Zusammenfassung für längere Beiträge
+------------------------------------
+
+Wenn man seine Beiträge über mehrere Netzwerke verbreiten möchte, hat man häufig das Problem, dass diese Netzwerke z.B. eine Längenbeschränkung haben.
+(Z.B. Twitter).
+
+Friendica benutzt zum Erzeugen eines Anreißtextes eine halbwegs intelligente Logik.
+Es kann aber dennoch von Interesse sein, eine eigene Zusammenfassung zu erstellen, die nur auf dem Fremdnetzwerk dargestellt wird.
+Dies geschieht mit dem [abstract]-Element.
+Beispiel:
+
+
[abstract]Total spannend! Unbedingt diesen Link anklicken![/abstract]
+Hier erzähle ich euch eine total langweilige Geschichte, die ihr noch
+nie hören wolltet.
+
+Auf Twitter würde das "Total spannend! Unbedingt diesen Link anklicken!" stehen, auf Friendica würde nur der Text nach "Hier erzähle ..." erscheinen.
+
+Es ist sogar möglich, für einzelne Netzwerke eigene Zusammenfassungen zu erstellen:
+
+
+[abstract]Hallo Leute, hier meine neuesten Bilder![abstract]
+[abstract=twit]Hallo Twitter-User, hier meine neuesten Bilder![abstract]
+[abstract=apdn]Hallo App.net-User, hier meine neuesten Bilder![abstract]
+Ich war heute wieder im Wald unterwegs und habe tolle Bilder geschossen ...
+
+
+Für Twitter und App.net nimmt das System die entsprechenden Texte.
+Bei anderen Netzwerken, bei denen der Inhalt gekürzt wird (z.B. beim "statusnet"-Connector, der für das Posten nach GNU Social verwendet wird) wird dann die Zusammenfassung unter [abstract] verwendet.
+
+Wenn man z.B. den "buffer"-Connector verwendet, um nach Facebook oder Google+ zu posten, kann man dieses Element ebenfalls verwenden, wenn man z.B. einen längeren Blogbeitrag erstellt hat, aber ihn nicht komplett in diese Netzwerke posten möchte.
+
+Netzwerke wie Facebook oder Google+ sind nicht in der Postinglänge beschränkt.
+Aus diesem Grund greift nicht die [abstract]-Zusammenfassung. Stattdessen muss man das Netzwerk explizit angeben:
+
+
+[abstract]Ich habe neulich wieder etwas erlebt, was ich euch mitteilen möchte.[abstract]
+[abstract=goog]Hallo meine Google+-Kreislinge. Ich habe neulich wieder
+etwas erlebt, was ich euch mitteilen möchte.[abstract]
+[abstract=face]Hallo Facebook-Freunde! Ich habe neulich wieder etwas
+erlebt, was ich euch mitteilen möchte.[abstract]
+Beim Bildermachen im Wald habe ich neulich eine interessante Person
+getroffen ...
+
+Das [abstract]-Element greift nicht bei der nativen OStatus-Verbindung oder bei Connectoren, die den HTML-Text posten wie z.B. die Connectoren zu Tumblr, Wordpress oder Pump.io.
+
Spezielle Tags
-------
Wenn Du über BBCode Tags in einer Nachricht schreiben möchtest, kannst Du [noparse], [nobb] oder [pre] verwenden um den BBCode Tags vor der Evaluierung zu schützen:
[noparse][b]fett[/b][/noparse]
: [b]fett[/b]
-
-
diff --git a/doc/de/Plugins.md b/doc/de/Plugins.md
index dcff41a4b..40be4a069 100644
--- a/doc/de/Plugins.md
+++ b/doc/de/Plugins.md
@@ -1,27 +1,28 @@
-**Friendica Addon/Plugin-Entwicklung**
+Friendica Addon/Plugin-Entwicklung
==============
* [Zur Startseite der Hilfe](help)
-Bitte schau dir das Beispiel-Addon "randplace" für ein funktionierendes Beispiel für manche der hier aufgeführten Funktionen an.
-Das Facebook-Addon bietet ein Beispiel dafür, die "addon"- und "module"-Funktion gemeinsam zu integrieren.
-Addons arbeiten, indem sie Event Hooks abfangen. Module arbeiten, indem bestimmte Seitenanfragen (durch den URL-Pfad) abgefangen werden
+Bitte schau dir das Beispiel-Addon "randplace" für ein funktionierendes Beispiel für manche der hier aufgeführten Funktionen an.
+Das Facebook-Addon bietet ein Beispiel dafür, die "addon"- und "module"-Funktion gemeinsam zu integrieren.
+Addons arbeiten, indem sie Event Hooks abfangen.
+Module arbeiten, indem bestimmte Seitenanfragen (durch den URL-Pfad) abgefangen werden.
-Plugin-Namen können keine Leerstellen oder andere Interpunktionen enthalten und werden als Datei- und Funktionsnamen genutzt.
-Du kannst einen lesbaren Namen im Kommentarblock eintragen.
-Jedes Addon muss beides beinhalten - eine Installations- und eine Deinstallationsfunktion, die auf dem Addon-/Plugin-Namen basieren; z.B. "plugin1name_install()".
-Diese beiden Funktionen haben keine Argumente und sind dafür verantwortlich, Event Hooks zu registrieren und abzumelden (unregistering), die dein Plugin benötigt.
-Die Installations- und Deinstallationsfunktionfunktionen werden auch ausgeführt (z.B. neu installiert), wenn sich das Plugin nach der Installation ändert - somit sollte deine Deinstallationsfunktion keine Daten zerstört und deine Installationsfunktion sollte bestehende Daten berücksichtigen.
+Plugin-Namen können keine Leerstellen oder andere Interpunktionen enthalten und werden als Datei- und Funktionsnamen genutzt.
+Du kannst einen lesbaren Namen im Kommentarblock eintragen.
+Jedes Addon muss beides beinhalten - eine Installations- und eine Deinstallationsfunktion, die auf dem Addon-/Plugin-Namen basieren; z.B. "plugin1name_install()".
+Diese beiden Funktionen haben keine Argumente und sind dafür verantwortlich, Event Hooks zu registrieren und abzumelden (unregistering), die dein Plugin benötigt.
+Die Installations- und Deinstallationsfunktionfunktionen werden auch ausgeführt (z.B. neu installiert), wenn sich das Plugin nach der Installation ändert - somit sollte deine Deinstallationsfunktion keine Daten zerstört und deine Installationsfunktion sollte bestehende Daten berücksichtigen.
Zukünftige Extensions werden möglicherweise "Setup" und "Entfernen" anbieten.
Plugins sollten einen Kommentarblock mit den folgenden vier Parametern enthalten:
- /*
- * Name: My Great Plugin
- * Description: This is what my plugin does. It's really cool
- * Version: 1.0
- * Author: John Q. Public
- */
+ /*
+ * Name: My Great Plugin
+ * Description: This is what my plugin does. It's really cool.
+ * Version: 1.0
+ * Author: John Q. Public
+ */
Registriere deine Plugin-Hooks während der Installation.
@@ -29,45 +30,50 @@ Registriere deine Plugin-Hooks während der Installation.
$hookname ist ein String und entspricht einem bekannten Friendica-Hook.
-$file steht für den Pfadnamen, der relativ zum Top-Level-Friendicaverzeichnis liegt.
+$file steht für den Pfadnamen, der relativ zum Top-Level-Friendicaverzeichnis liegt.
Das *sollte* "addon/plugin_name/plugin_name.php' sein.
$function ist ein String und der Name der Funktion, die ausgeführt wird, wenn der Hook aufgerufen wird.
+Argumente
+---
+
Deine Hook-Callback-Funktion wird mit mindestens einem und bis zu zwei Argumenten aufgerufen
function myhook_function(&$a, &$b) {
}
-Wenn du Änderungen an den aufgerufenen Daten vornehmen willst, musst du diese als Referenzvariable (mit "&") während der Funktionsdeklaration deklarieren.
+Wenn du Änderungen an den aufgerufenen Daten vornehmen willst, musst du diese als Referenzvariable (mit "&") während der Funktionsdeklaration deklarieren.
-$a ist die Friendica "App"-Klasse, die eine Menge an Informationen über den aktuellen Friendica-Status beinhaltet, u.a. welche Module genutzt werden, Konfigurationsinformationen, Inhalte der Seite zum Zeitpunkt des Hook-Aufrufs.
-Es ist empfohlen, diese Funktion "$a" zu nennen, um seine Nutzung an den Gebrauch an anderer Stelle anzugleichen.
+$a ist die Friendica "App"-Klasse, die eine Menge an Informationen über den aktuellen Friendica-Status beinhaltet, u.a. welche Module genutzt werden, Konfigurationsinformationen, Inhalte der Seite zum Zeitpunkt des Hook-Aufrufs.
+Es ist empfohlen, diese Funktion "$a" zu nennen, um seine Nutzung an den Gebrauch an anderer Stelle anzugleichen.
-$b kann frei benannt werden.
-Diese Information ist speziell auf den Hook bezogen, der aktuell bearbeitet wird, und beinhaltet normalerweise Daten, die du sofort nutzen, anzeigen oder bearbeiten kannst.
-Achte darauf, diese mit "&" zu deklarieren, wenn du sie bearbeiten willst.
+$b kann frei benannt werden.
+Diese Information ist speziell auf den Hook bezogen, der aktuell bearbeitet wird, und beinhaltet normalerweise Daten, die du sofort nutzen, anzeigen oder bearbeiten kannst.
+Achte darauf, diese mit "&" zu deklarieren, wenn du sie bearbeiten willst.
-**Module**
+Module
+---
-Plugins/Addons können auch als "Module" agieren und alle Seitenanfragen für eine bestimte URL abfangen.
-Um ein Plugin als Modul zu nutzen, ist es nötig, die Funktion "plugin_name_module()" zu definieren, die keine Argumente benötigt und nichts weiter machen muss.
+Plugins/Addons können auch als "Module" agieren und alle Seitenanfragen für eine bestimte URL abfangen.
+Um ein Plugin als Modul zu nutzen, ist es nötig, die Funktion "plugin_name_module()" zu definieren, die keine Argumente benötigt und nichts weiter machen muss.
-Wenn diese Funktion existiert, wirst du nun alle Seitenanfragen für "http://my.web.site/plugin_name" erhalten - mit allen URL-Komponenten als zusätzliche Argumente.
-Diese werden in ein Array $a->argv geparst und stimmen mit $a->argc überein, wobei sie die Anzahl der URL-Komponenten abbilden.
-So würde http://my.web.site/plugin/arg1/arg2 nach einem Modul "plugin" suchen und seiner Modulfunktion die $a-App-Strukur übergeben (dies ist für viele Komponenten verfügbar). Das umfasst:
+Wenn diese Funktion existiert, wirst du nun alle Seitenanfragen für "http://example.com/plugin_name" erhalten - mit allen URL-Komponenten als zusätzliche Argumente.
+Diese werden in ein Array $a->argv geparst und stimmen mit $a->argc überein, wobei sie die Anzahl der URL-Komponenten abbilden.
+So würde http://example.com/plugin/arg1/arg2 nach einem Modul "plugin" suchen und seiner Modulfunktion die $a-App-Strukur übergeben (dies ist für viele Komponenten verfügbar). Das umfasst:
- $a->argc = 3
- $a->argv = array(0 => 'plugin', 1 => 'arg1', 2 => 'arg2');
+ $a->argc = 3
+ $a->argv = array(0 => 'plugin', 1 => 'arg1', 2 => 'arg2');
-Deine Modulfunktionen umfassen oft die Funktion plugin_name_content(&$a), welche den Seiteninhalt definiert und zurückgibt.
-Sie können auch plugin_name_post(&$a) umfassen, welches vor der content-Funktion aufgerufen wird und normalerweise die Resultate der POST-Formulare handhabt.
+Deine Modulfunktionen umfassen oft die Funktion plugin_name_content(&$a), welche den Seiteninhalt definiert und zurückgibt.
+Sie können auch plugin_name_post(&$a) umfassen, welches vor der content-Funktion aufgerufen wird und normalerweise die Resultate der POST-Formulare handhabt.
Du kannst ebenso plugin_name_init(&$a) nutzen, was oft frühzeitig aufgerufen wird und das Modul initialisert.
-**Derzeitige Hooks:**
+Derzeitige Hooks
+---
**'authenticate'** - wird aufgerufen, wenn sich der User einloggt.
$b ist ein Array
@@ -180,6 +186,9 @@ Du kannst ebenso plugin_name_init(&$a) nutzen, was oft frühzeitig aufgerufen wi
- wird aufgerufen nachdem in include/nav,php der Inhalt des Navigations Menüs erzeugt wurde.
- $b ist ein Array, das $nav wiederspiegelt.
+Komplette Liste der Hook-Callbacks
+---
+
Eine komplette Liste aller Hook-Callbacks mit den zugehörigen Dateien (am 14-Feb-2012 generiert): Bitte schau in die Quellcodes für Details zu Hooks, die oben nicht dokumentiert sind.
boot.php: call_hooks('login_hook',$o);
@@ -204,7 +213,7 @@ include/text.php: call_hooks('contact_block_end', $arr);
include/text.php: call_hooks('smilie', $s);
-include/text.php: call_hooks('prepare_body_init', $item);
+include/text.php: call_hooks('prepare_body_init', $item);
include/text.php: call_hooks('prepare_body', $prep_arr);
@@ -359,4 +368,3 @@ mod/cb.php: call_hooks('cb_afterpost');
mod/cb.php: call_hooks('cb_content', $o);
mod/directory.php: call_hooks('directory_item', $arr);
-
diff --git a/doc/de/Settings.md b/doc/de/Settings.md
index 988b3657c..4ad9f39ba 100644
--- a/doc/de/Settings.md
+++ b/doc/de/Settings.md
@@ -14,9 +14,6 @@ Friendica erfasst die folgenden Tastaturbefehle:
* [Pause] - Pausiert die Update-Aktivität via "Ajax". Das ist ein Prozess, der Updates durchführt, ohne die Seite neu zu laden. Du kannst diesen Prozess pausieren, um deine Netzwerkauslastung zu reduzieren und/oder um es in der Javascript-Programmierung zum Debuggen zu nutzen. Ein Pausenzeichen erscheint unten links im Fenster. Klicke die [Pause]-Taste ein weiteres Mal, um die Pause zu beenden.
-* [F8] - Zeigt eine Sprachauswahl an
-
-
**Geburtstagsbenachrichtigung**
Geburtstage erscheinen auf deiner Startseite für alle Freunde, die in den nächsten 6 Tagen Geburtstag haben.
diff --git a/doc/htconfig.md b/doc/htconfig.md
index 4764c287c..a36e0bef2 100644
--- a/doc/htconfig.md
+++ b/doc/htconfig.md
@@ -34,6 +34,7 @@ line to your .htconfig.php:
* like_no_comment (Boolean) - Don't update the "commented" value of an item when it is liked.
* local_block (Boolean) - Used in conjunction with "block_public".
* local_search (Boolean) - Blocks the search for not logged in users to prevent crawlers from blocking your system.
+* max_connections - The poller process isn't started when 3/4 of the possible database connections are used. When the system can't detect the maximum numbers of connection then this value can be used.
* max_contact_queue - Default value is 500.
* max_batch_queue - Default value is 1000.
* no_oembed (Boolean) - Don't use OEmbed to fetch more information about a link.
@@ -63,9 +64,6 @@ line to your .htconfig.php:
* throttle_limit_week - Maximum number of posts that a user can send per week with the API.
* throttle_limit_month - Maximum number of posts that a user can send per month with the API.
* wall-to-wall_share (Boolean) - Displays forwarded posts like "wall-to-wall" posts.
-* worker (Boolean) - (Experimental) Use the worker system instead of calling several background processes. Reduces the overall load and speeds up item delivery.
-* worker_dont_fork (Boolean) - if enabled, the workers are only called from the poller process. Useful on systems that permit the use of "proc_open".
-* worker_queues - Number of parallel workers. Default value is 10 queues.
* xrd_timeout - Timeout for fetching the XRD links. Default value is 20 seconds.
## service_class ##
diff --git a/doc/snarty3-templates.md b/doc/smarty3-templates.md
similarity index 100%
rename from doc/snarty3-templates.md
rename to doc/smarty3-templates.md
diff --git a/include/Contact.php b/include/Contact.php
index 3799e0b18..79a14ab58 100644
--- a/include/Contact.php
+++ b/include/Contact.php
@@ -129,7 +129,7 @@ function terminate_friendship($user,$self,$contact) {
}
elseif($contact['network'] === NETWORK_DIASPORA) {
require_once('include/diaspora.php');
- diaspora_unshare($user,$contact);
+ diaspora::send_unshare($user,$contact);
}
elseif($contact['network'] === NETWORK_DFRN) {
require_once('include/dfrn.php');
@@ -555,60 +555,6 @@ function posts_from_gcontact($a, $gcontact_id) {
return $o;
}
-/**
- * @brief set the gcontact-id in all item entries
- *
- * This job has to be started multiple times until all entries are set.
- * It isn't started in the update function since it would consume too much time and can be done in the background.
- */
-function item_set_gcontact() {
- define ('POST_UPDATE_VERSION', 1192);
-
- // Was the script completed?
- if (get_config("system", "post_update_version") >= POST_UPDATE_VERSION)
- return;
-
- // Check if the first step is done (Setting "gcontact-id" in the item table)
- $r = q("SELECT `author-link`, `author-name`, `author-avatar`, `uid`, `network` FROM `item` WHERE `gcontact-id` = 0 LIMIT 1000");
- if (!$r) {
- // Are there unfinished entries in the thread table?
- $r = q("SELECT COUNT(*) AS `total` FROM `thread`
- INNER JOIN `item` ON `item`.`id` =`thread`.`iid`
- WHERE `thread`.`gcontact-id` = 0 AND
- (`thread`.`uid` IN (SELECT `uid` from `user`) OR `thread`.`uid` = 0)");
-
- if ($r AND ($r[0]["total"] == 0)) {
- set_config("system", "post_update_version", POST_UPDATE_VERSION);
- return false;
- }
-
- // Update the thread table from the item table
- q("UPDATE `thread` INNER JOIN `item` ON `item`.`id`=`thread`.`iid`
- SET `thread`.`gcontact-id` = `item`.`gcontact-id`
- WHERE `thread`.`gcontact-id` = 0 AND
- (`thread`.`uid` IN (SELECT `uid` from `user`) OR `thread`.`uid` = 0)");
-
- return false;
- }
-
- $item_arr = array();
- foreach ($r AS $item) {
- $index = $item["author-link"]."-".$item["uid"];
- $item_arr[$index] = array("author-link" => $item["author-link"],
- "uid" => $item["uid"],
- "network" => $item["network"]);
- }
-
- // Set the "gcontact-id" in the item table and add a new gcontact entry if needed
- foreach($item_arr AS $item) {
- $gcontact_id = get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
- "photo" => $item['author-avatar'], "name" => $item['author-name']));
- q("UPDATE `item` SET `gcontact-id` = %d WHERE `uid` = %d AND `author-link` = '%s' AND `gcontact-id` = 0",
- intval($gcontact_id), intval($item["uid"]), dbesc($item["author-link"]));
- }
- return true;
-}
-
/**
* @brief Returns posts from a given contact
*
diff --git a/include/ForumManager.php b/include/ForumManager.php
new file mode 100644
index 000000000..17a6b6730
--- /dev/null
+++ b/include/ForumManager.php
@@ -0,0 +1,190 @@
+ forum url
+ * 'name' => forum name
+ * 'id' => number of the key from the array
+ * 'micro' => contact photo in format micro
+ */
+ public static function get_list($uid, $showhidden = true, $lastitem, $showprivate = false) {
+
+ $forumlist = array();
+
+ $order = (($showhidden) ? '' : ' AND NOT `hidden` ');
+ $order .= (($lastitem) ? ' ORDER BY `last-item` DESC ' : ' ORDER BY `name` ASC ');
+ $select = '`forum` ';
+ if ($showprivate) {
+ $select = '(`forum` OR `prv`)';
+ }
+
+ $contacts = q("SELECT `contact`.`id`, `contact`.`url`, `contact`.`name`, `contact`.`micro` FROM `contact`
+ WHERE `network`= 'dfrn' AND $select AND `uid` = %d
+ AND NOT `blocked` AND NOT `hidden` AND NOT `pending` AND NOT `archive`
+ AND `success_update` > `failure_update`
+ $order ",
+ intval($uid)
+ );
+
+ if (!$contacts)
+ return($forumlist);
+
+ foreach($contacts as $contact) {
+ $forumlist[] = array(
+ 'url' => $contact['url'],
+ 'name' => $contact['name'],
+ 'id' => $contact['id'],
+ 'micro' => $contact['micro'],
+ );
+ }
+ return($forumlist);
+ }
+
+
+ /**
+ * @brief Forumlist widget
+ *
+ * Sidebar widget to show subcribed friendica forums. If activated
+ * in the settings, it appears at the notwork page sidebar
+ *
+ * @param int $uid The ID of the User
+ * @param int $cid
+ * The contact id which is used to mark a forum as "selected"
+ * @return string
+ */
+ public static function widget($uid,$cid = 0) {
+
+ if(! intval(feature_enabled(local_user(),'forumlist_widget')))
+ return;
+
+ $o = '';
+
+ //sort by last updated item
+ $lastitem = true;
+
+ $contacts = self::get_list($uid,true,$lastitem, true);
+ $total = count($contacts);
+ $visible_forums = 10;
+
+ if(count($contacts)) {
+
+ $id = 0;
+
+ foreach($contacts as $contact) {
+
+ $selected = (($cid == $contact['id']) ? ' forum-selected' : '');
+
+ $entry = array(
+ 'url' => 'network?f=&cid=' . $contact['id'],
+ 'external_url' => 'redir/' . $contact['id'],
+ 'name' => $contact['name'],
+ 'cid' => $contact['id'],
+ 'selected' => $selected,
+ 'micro' => App::remove_baseurl(proxy_url($contact['micro'], false, PROXY_SIZE_MICRO)),
+ 'id' => ++$id,
+ );
+ $entries[] = $entry;
+ }
+
+ $tpl = get_markup_template('widget_forumlist.tpl');
+
+ $o .= replace_macros($tpl,array(
+ '$title' => t('Forums'),
+ '$forums' => $entries,
+ '$link_desc' => t('External link to forum'),
+ '$total' => $total,
+ '$visible_forums' => $visible_forums,
+ '$showmore' => t('show more'),
+ ));
+ }
+
+ return $o;
+ }
+
+ /**
+ * @brief Format forumlist as contact block
+ *
+ * This function is used to show the forumlist in
+ * the advanced profile.
+ *
+ * @param int $uid The ID of the User
+ * @return string
+ *
+ */
+ public static function profile_advanced($uid) {
+
+ $profile = intval(feature_enabled($uid,'forumlist_profile'));
+ if(! $profile)
+ return;
+
+ $o = '';
+
+ // place holder in case somebody wants configurability
+ $show_total = 9999;
+
+ //don't sort by last updated item
+ $lastitem = false;
+
+ $contacts = self::get_list($uid,false,$lastitem,false);
+
+ $total_shown = 0;
+
+ foreach($contacts as $contact) {
+ $forumlist .= micropro($contact,false,'forumlist-profile-advanced');
+ $total_shown ++;
+ if($total_shown == $show_total)
+ break;
+ }
+
+ if(count($contacts) > 0)
+ $o .= $forumlist;
+ return $o;
+ }
+
+ /**
+ * @brief count unread forum items
+ *
+ * Count unread items of connected forums and private groups
+ *
+ * @return array
+ * 'id' => contact id
+ * 'name' => contact/forum name
+ * 'count' => counted unseen forum items
+ *
+ */
+ public static function count_unseen_items() {
+ $r = q("SELECT `contact`.`id`, `contact`.`name`, COUNT(*) AS `count` FROM `item`
+ INNER JOIN `contact` ON `item`.`contact-id` = `contact`.`id`
+ WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted` AND `item`.`unseen`
+ AND `contact`.`network`= 'dfrn' AND (`contact`.`forum` OR `contact`.`prv`)
+ AND NOT `contact`.`blocked` AND NOT `contact`.`hidden`
+ AND NOT `contact`.`pending` AND NOT `contact`.`archive`
+ AND `contact`.`success_update` > `failure_update`
+ GROUP BY `contact`.`id` ",
+ intval(local_user())
+ );
+
+ return $r;
+ }
+
+}
diff --git a/include/NotificationsManager.php b/include/NotificationsManager.php
new file mode 100644
index 000000000..5f8211eb8
--- /dev/null
+++ b/include/NotificationsManager.php
@@ -0,0 +1,136 @@
+a = get_app();
+ }
+
+ /**
+ * @brief set some extra note properties
+ *
+ * @param array $notes array of note arrays from db
+ * @return array Copy of input array with added properties
+ *
+ * Set some extra properties to note array from db:
+ * - timestamp as int in default TZ
+ * - date_rel : relative date string
+ * - msg_html: message as html string
+ * - msg_plain: message as plain text string
+ */
+ private function _set_extra($notes) {
+ $rets = array();
+ foreach($notes as $n) {
+ $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
+ $n['timestamp'] = strtotime($local_time);
+ $n['date_rel'] = relative_date($n['date']);
+ $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
+ $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
+
+ $rets[] = $n;
+ }
+ return $rets;
+ }
+
+
+ /**
+ * @brief get all notifications for local_user()
+ *
+ * @param array $filter optional Array "column name"=>value: filter query by columns values
+ * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
+ * @param string $limit optional Query limits
+ *
+ * @return array of results or false on errors
+ */
+ public function getAll($filter = array(), $order="-date", $limit="") {
+ $filter_str = array();
+ $filter_sql = "";
+ foreach($filter as $column => $value) {
+ $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
+ }
+ if (count($filter_str)>0) {
+ $filter_sql = "AND ".implode(" AND ", $filter_str);
+ }
+
+ $aOrder = explode(" ", $order);
+ $asOrder = array();
+ foreach($aOrder as $o) {
+ $dir = "asc";
+ if ($o[0]==="-") {
+ $dir = "desc";
+ $o = substr($o,1);
+ }
+ if ($o[0]==="+") {
+ $dir = "asc";
+ $o = substr($o,1);
+ }
+ $asOrder[] = "$o $dir";
+ }
+ $order_sql = implode(", ", $asOrder);
+
+ if ($limit!="") $limit = " LIMIT ".$limit;
+
+ $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
+ intval(local_user())
+ );
+ if ($r!==false && count($r)>0) return $this->_set_extra($r);
+ return false;
+ }
+
+ /**
+ * @brief get one note for local_user() by $id value
+ *
+ * @param int $id
+ * @return array note values or null if not found
+ */
+ public function getByID($id) {
+ $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
+ intval($id),
+ intval(local_user())
+ );
+ if($r!==false && count($r)>0) {
+ return $this->_set_extra($r)[0];
+ }
+ return null;
+ }
+
+ /**
+ * @brief set seen state of $note of local_user()
+ *
+ * @param array $note
+ * @param bool $seen optional true or false, default true
+ * @return bool true on success, false on errors
+ */
+ public function setSeen($note, $seen = true) {
+ return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
+ intval($seen),
+ dbesc($note['link']),
+ intval($note['parent']),
+ dbesc($note['otype']),
+ intval(local_user())
+ );
+ }
+
+ /**
+ * @brief set seen state of all notifications of local_user()
+ *
+ * @param bool $seen optional true or false. default true
+ * @return bool true on success, false on error
+ */
+ public function setAllSeen($seen = true) {
+ return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
+ intval($seen),
+ intval(local_user())
+ );
+ }
+}
diff --git a/include/Photo.php b/include/Photo.php
index 3f1608d3e..91fce55a8 100644
--- a/include/Photo.php
+++ b/include/Photo.php
@@ -726,10 +726,11 @@ function guess_image_type($filename, $fromcurl=false) {
* @param string $avatar Link to avatar picture
* @param int $uid User id of contact owner
* @param int $cid Contact id
+ * @param bool $force force picture update
*
* @return array Returns array of the different avatar sizes
*/
-function update_contact_avatar($avatar,$uid,$cid) {
+function update_contact_avatar($avatar,$uid,$cid, $force = false) {
$r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
if (!$r)
@@ -737,7 +738,7 @@ function update_contact_avatar($avatar,$uid,$cid) {
else
$data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
- if ($r[0]["avatar"] != $avatar) {
+ if (($r[0]["avatar"] != $avatar) OR $force) {
$photos = import_profile_photo($avatar,$uid,$cid, true);
if ($photos) {
diff --git a/include/Scrape.php b/include/Scrape.php
index ca6489b16..68926a997 100644
--- a/include/Scrape.php
+++ b/include/Scrape.php
@@ -2,6 +2,7 @@
require_once('library/HTML5/Parser.php');
require_once('include/crypto.php');
+require_once('include/feed.php');
if(! function_exists('scrape_dfrn')) {
function scrape_dfrn($url, $dont_probe = false) {
@@ -12,9 +13,25 @@ function scrape_dfrn($url, $dont_probe = false) {
logger('scrape_dfrn: url=' . $url);
+ // Try to fetch the data from noscrape. This is faster than parsing the HTML
+ $noscrape = str_replace("/hcard/", "/noscrape/", $url);
+ $noscrapejson = fetch_url($noscrape);
+ $noscrapedata = array();
+ if ($noscrapejson) {
+ $noscrapedata = json_decode($noscrapejson, true);
+
+ if (is_array($noscrapedata)) {
+ if ($noscrapedata["nick"] != "")
+ return($noscrapedata);
+ else
+ unset($noscrapedata["nick"]);
+ } else
+ $noscrapedata = array();
+ }
+
$s = fetch_url($url);
- if(! $s)
+ if (!$s)
return $ret;
if (!$dont_probe) {
@@ -91,8 +108,7 @@ function scrape_dfrn($url, $dont_probe = false) {
}
}
}
-
- return $ret;
+ return array_merge($ret, $noscrapedata);
}}
@@ -342,7 +358,7 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$result = array();
- if(! $url)
+ if (!$url)
return $result;
$result = Cache::get("probe_url:".$mode.":".$url);
@@ -351,6 +367,7 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
return $result;
}
+ $original_url = $url;
$network = null;
$diaspora = false;
$diaspora_base = '';
@@ -366,8 +383,6 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$network = NETWORK_TWITTER;
}
- // Twitter is deactivated since twitter closed its old API
- //$twitter = ((strpos($url,'twitter.com') !== false) ? true : false);
$lastfm = ((strpos($url,'last.fm/user') !== false) ? true : false);
$at_addr = ((strpos($url,'@') !== false) ? true : false);
@@ -381,7 +396,12 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
else
$links = lrdd($url);
- if(count($links)) {
+ if ((count($links) == 0) AND strstr($url, "/index.php")) {
+ $url = str_replace("/index.php", "", $url);
+ $links = lrdd($url);
+ }
+
+ if (count($links)) {
$has_lrdd = true;
logger('probe_url: found lrdd links: ' . print_r($links,true), LOGGER_DATA);
@@ -428,12 +448,21 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
// aliases, let's hope we're lucky and get one that matches the feed author-uri because
// otherwise we're screwed.
+ $backup_alias = "";
+
foreach($links as $link) {
if($link['@attributes']['rel'] === 'alias') {
if(strpos($link['@attributes']['href'],'@') === false) {
if(isset($profile)) {
- if($link['@attributes']['href'] !== $profile)
- $alias = unamp($link['@attributes']['href']);
+ $alias_url = $link['@attributes']['href'];
+
+ if(($alias_url !== $profile) AND ($backup_alias == "") AND
+ ($alias_url !== str_replace("/index.php", "", $profile)))
+ $backup_alias = $alias_url;
+
+ if(($alias_url !== $profile) AND !strstr($alias_url, "index.php") AND
+ ($alias_url !== str_replace("/index.php", "", $profile)))
+ $alias = $alias_url;
}
else
$profile = unamp($link['@attributes']['href']);
@@ -441,6 +470,9 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
}
}
+ if ($alias == "")
+ $alias = $backup_alias;
+
// If the profile is different from the url then the url is abviously an alias
if (($alias == "") AND ($profile != "") AND !$at_addr AND (normalise_link($profile) != normalise_link($url)))
$alias = $url;
@@ -604,21 +636,6 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$vcard['nick'] = $addr_parts[0];
}
- /* if($twitter) {
- logger('twitter: setup');
- $tid = basename($url);
- $tapi = 'https://api.twitter.com/1/statuses/user_timeline.rss';
- if(intval($tid))
- $poll = $tapi . '?user_id=' . $tid;
- else
- $poll = $tapi . '?screen_name=' . $tid;
- $profile = 'http://twitter.com/#!/' . $tid;
- //$vcard['photo'] = 'https://api.twitter.com/1/users/profile_image/' . $tid;
- $vcard['photo'] = 'https://api.twitter.com/1/users/profile_image?screen_name=' . $tid . '&size=bigger';
- $vcard['nick'] = $tid;
- $vcard['fn'] = $tid;
- } */
-
if($lastfm) {
$profile = $url;
$poll = str_replace(array('www.','last.fm/'),array('','ws.audioscrobbler.com/1.0/'),$url) . '/recenttracks.rss';
@@ -662,85 +679,41 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
if(x($feedret,'photo') && (! x($vcard,'photo')))
$vcard['photo'] = $feedret['photo'];
- require_once('library/simplepie/simplepie.inc');
- $feed = new SimplePie();
+
$cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
$xml = fetch_url($poll, false, $redirects, 0, Null, $cookiejar);
unlink($cookiejar);
logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
- $a = get_app();
- logger('probe_url: scrape_feed: headers: ' . $a->get_curl_headers(), LOGGER_DATA);
-
- // Don't try and parse an empty string
- $feed->set_raw_data(($xml) ? $xml : '');
-
- $feed->init();
- if($feed->error()) {
- logger('probe_url: scrape_feed: Error parsing XML: ' . $feed->error());
+ if ($xml == "") {
+ logger("scrape_feed: XML is empty for feed ".$poll);
$network = NETWORK_PHANTOM;
- }
+ } else {
+ $data = feed_import($xml,$dummy1,$dummy2, $dummy3, true);
- if(! x($vcard,'photo'))
- $vcard['photo'] = $feed->get_image_url();
- $author = $feed->get_author();
+ if (!is_array($data)) {
+ logger("scrape_feed: This doesn't seem to be a feed: ".$poll);
+ $network = NETWORK_PHANTOM;
+ } else {
+ if (($vcard["photo"] == "") AND ($data["header"]["author-avatar"] != ""))
+ $vcard["photo"] = $data["header"]["author-avatar"];
- if($author) {
- $vcard['fn'] = unxmlify(trim($author->get_name()));
- if(! $vcard['fn'])
- $vcard['fn'] = trim(unxmlify($author->get_email()));
- if(strpos($vcard['fn'],'@') !== false)
- $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
+ if (($vcard["fn"] == "") AND ($data["header"]["author-name"] != ""))
+ $vcard["fn"] = $data["header"]["author-name"];
- $email = unxmlify($author->get_email());
- if(! $profile && $author->get_link())
- $profile = trim(unxmlify($author->get_link()));
- if(! $vcard['photo']) {
- $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
- if($rawtags) {
- $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
- if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
- $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
- }
- }
- // Fetch fullname via poco:displayName
- $pocotags = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
- if ($pocotags) {
- $elems = $pocotags[0]['child']['http://portablecontacts.net/spec/1.0'];
- if (isset($elems["displayName"]))
- $vcard['fn'] = $elems["displayName"][0]["data"];
- if (isset($elems["preferredUsername"]))
- $vcard['nick'] = $elems["preferredUsername"][0]["data"];
- }
- }
- else {
- $item = $feed->get_item(0);
- if($item) {
- $author = $item->get_author();
- if($author) {
- $vcard['fn'] = trim(unxmlify($author->get_name()));
- if(! $vcard['fn'])
- $vcard['fn'] = trim(unxmlify($author->get_email()));
- if(strpos($vcard['fn'],'@') !== false)
- $vcard['fn'] = substr($vcard['fn'],0,strpos($vcard['fn'],'@'));
- $email = unxmlify($author->get_email());
- if(! $profile && $author->get_link())
- $profile = trim(unxmlify($author->get_link()));
- }
- if(! $vcard['photo']) {
- $rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/','thumbnail');
- if($rawmedia && $rawmedia[0]['attribs']['']['url'])
- $vcard['photo'] = unxmlify($rawmedia[0]['attribs']['']['url']);
- }
- if(! $vcard['photo']) {
- $rawtags = $item->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
- if($rawtags) {
- $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
- if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
- $vcard['photo'] = $elems['link'][0]['attribs']['']['href'];
- }
- }
+ if (($vcard["nick"] == "") AND ($data["header"]["author-nick"] != ""))
+ $vcard["nick"] = $data["header"]["author-nick"];
+
+ if ($network == NETWORK_OSTATUS) {
+ if ($data["header"]["author-id"] != "")
+ $alias = $data["header"]["author-id"];
+
+ if ($data["header"]["author-link"] != "")
+ $profile = $data["header"]["author-link"];
+
+ } elseif(!$profile AND ($data["header"]["author-link"] != "") AND !in_array($network, array("", NETWORK_FEED)))
+ $profile = $data["header"]["author-link"];
}
}
@@ -783,27 +756,9 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
}
}
- if((! $vcard['photo']) && strlen($email))
- $vcard['photo'] = avatar_img($email);
- if($poll === $profile)
- $lnk = $feed->get_permalink();
- if(isset($lnk) && strlen($lnk))
- $profile = $lnk;
-
- if(! $network) {
+ if(! $network)
$network = NETWORK_FEED;
- // If it is a feed, don't take the author name as feed name
- unset($vcard['fn']);
- }
- if(! (x($vcard,'fn')))
- $vcard['fn'] = notags($feed->get_title());
- if(! (x($vcard,'fn')))
- $vcard['fn'] = notags($feed->get_description());
- if(strpos($vcard['fn'],'Twitter / ') !== false) {
- $vcard['fn'] = substr($vcard['fn'],strpos($vcard['fn'],'/')+1);
- $vcard['fn'] = trim($vcard['fn']);
- }
if(! x($vcard,'nick')) {
$vcard['nick'] = strtolower(notags(unxmlify($vcard['fn'])));
if(strpos($vcard['nick'],' '))
@@ -816,7 +771,7 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
if(! x($vcard,'photo')) {
$a = get_app();
- $vcard['photo'] = $a->get_baseurl() . '/images/person-175.jpg' ;
+ $vcard['photo'] = App::get_baseurl() . '/images/person-175.jpg' ;
}
if(! $profile)
@@ -828,18 +783,21 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$vcard['fn'] = $url;
if (($notify != "") AND ($poll != "")) {
- $baseurl = matching(normalise_link($notify), normalise_link($poll));
+ $baseurl = matching_url(normalise_link($notify), normalise_link($poll));
- $baseurl2 = matching($baseurl, normalise_link($profile));
+ $baseurl2 = matching_url($baseurl, normalise_link($profile));
if ($baseurl2 != "")
$baseurl = $baseurl2;
}
if (($baseurl == "") AND ($notify != ""))
- $baseurl = matching(normalise_link($profile), normalise_link($notify));
+ $baseurl = matching_url(normalise_link($profile), normalise_link($notify));
if (($baseurl == "") AND ($poll != ""))
- $baseurl = matching(normalise_link($profile), normalise_link($poll));
+ $baseurl = matching_url(normalise_link($profile), normalise_link($poll));
+
+ if (substr($baseurl, -10) == "/index.php")
+ $baseurl = str_replace("/index.php", "", $baseurl);
$baseurl = rtrim($baseurl, "/");
@@ -888,25 +846,82 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
}
// Only store into the cache if the value seems to be valid
- if ($result['network'] != NETWORK_PHANTOM)
- Cache::set("probe_url:".$mode.":".$url,serialize($result), CACHE_DAY);
+ if ($result['network'] != NETWORK_PHANTOM) {
+ Cache::set("probe_url:".$mode.":".$original_url,serialize($result), CACHE_DAY);
+
+ /// @todo temporary fix - we need a real contact update function that updates only changing fields
+ /// The biggest problem is the avatar picture that could have a reduced image size.
+ /// It should only be updated if the existing picture isn't existing anymore.
+ if (($result['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
+ $result["name"] AND $result["nick"] AND $result["url"] AND $result["addr"] AND $result["poll"])
+ q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
+ `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
+ WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
+ dbesc($result["name"]),
+ dbesc($result["nick"]),
+ dbesc($result["url"]),
+ dbesc($result["addr"]),
+ dbesc($result["notify"]),
+ dbesc($result["poll"]),
+ dbesc($result["alias"]),
+ dbesc(datetime_convert()),
+ dbesc(normalise_link($result['url']))
+ );
+ }
return $result;
}
-function matching($part1, $part2) {
- $len = min(strlen($part1), strlen($part2));
+/**
+ * @brief Find the matching part between two url
+ *
+ * @param string $url1
+ * @param string $url2
+ * @return string The matching part
+ */
+function matching_url($url1, $url2) {
+
+ if (($url1 == "") OR ($url2 == ""))
+ return "";
+
+ $url1 = normalise_link($url1);
+ $url2 = normalise_link($url2);
+
+ $parts1 = parse_url($url1);
+ $parts2 = parse_url($url2);
+
+ if (!isset($parts1["host"]) OR !isset($parts2["host"]))
+ return "";
+
+ if ($parts1["scheme"] != $parts2["scheme"])
+ return "";
+
+ if ($parts1["host"] != $parts2["host"])
+ return "";
+
+ if ($parts1["port"] != $parts2["port"])
+ return "";
+
+ $match = $parts1["scheme"]."://".$parts1["host"];
+
+ if ($parts1["port"])
+ $match .= ":".$parts1["port"];
+
+ $pathparts1 = explode("/", $parts1["path"]);
+ $pathparts2 = explode("/", $parts2["path"]);
- $match = "";
- $matching = true;
$i = 0;
- while (($i <= $len) AND $matching) {
- if (substr($part1, $i, 1) == substr($part2, $i, 1))
- $match .= substr($part1, $i, 1);
- else
- $matching = false;
+ $path = "";
+ do {
+ $path1 = $pathparts1[$i];
+ $path2 = $pathparts2[$i];
- $i++;
- }
- return($match);
+ if ($path1 == $path2)
+ $path .= $path1."/";
+
+ } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
+
+ $match .= $path;
+
+ return normalise_link($match);
}
diff --git a/include/Smilies.php b/include/Smilies.php
index 193f3b555..9cb2d6f2b 100644
--- a/include/Smilies.php
+++ b/include/Smilies.php
@@ -1,7 +1,8 @@
',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '',
- '~friendica ',
- 'redmatrix',
- 'redmatrix'
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '~friendica ',
+ 'redmatrix',
+ 'redmatrix'
);
$params = array('texts' => $texts, 'icons' => $icons);
diff --git a/include/api.php b/include/api.php
index 4d206da28..305a86ca1 100644
--- a/include/api.php
+++ b/include/api.php
@@ -23,6 +23,7 @@
require_once('include/message.php');
require_once('include/group.php');
require_once('include/like.php');
+ require_once('include/NotificationsManager.php');
define('API_METHOD_ANY','*');
@@ -160,10 +161,7 @@
if (!isset($_SERVER['PHP_AUTH_USER'])) {
logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
- header('HTTP/1.0 401 Unauthorized');
- die((api_error($a, 'json', "This api requires login")));
-
- //die('This api requires login');
+ throw new UnauthorizedException("This API requires login");
}
$user = $_SERVER['PHP_AUTH_USER'];
@@ -215,8 +213,9 @@
if((! $record) || (! count($record))) {
logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
- header('HTTP/1.0 401 Unauthorized');
- die('This api requires login');
+ #header('HTTP/1.0 401 Unauthorized');
+ #die('This api requires login');
+ throw new UnauthorizedException("This API requires login");
}
authenticate_success($record); $_SESSION["allow_api"] = true;
@@ -250,7 +249,7 @@
*/
function api_call(&$a){
GLOBAL $API, $called_api;
-
+
$type="json";
if (strpos($a->query_string, ".xml")>0) $type="xml";
if (strpos($a->query_string, ".json")>0) $type="json";
@@ -330,7 +329,8 @@
*
* @param Api $a
* @param string $type Return type (xml, json, rss, as)
- * @param string $error Error message
+ * @param HTTPException $error Error object
+ * @return strin error message formatted as $type
*/
function api_error(&$a, $type, $e) {
$error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
@@ -680,6 +680,34 @@
}
+ /**
+ * @brief transform $data array in xml without a template
+ *
+ * @param array $data
+ * @return string xml string
+ */
+ function api_array_to_xml($data, $ename="") {
+ $attrs="";
+ $childs="";
+ if (count($data)==1 && !is_array($data[0])) {
+ $ename = array_keys($data)[0];
+ $v = $data[$ename];
+ return "<$ename>$v$ename>";
+ }
+ foreach($data as $k=>$v) {
+ $k=trim($k,'$');
+ if (!is_array($v)) {
+ $attrs .= sprintf('%s="%s" ', $k, $v);
+ } else {
+ if (is_numeric($k)) $k=trim($ename,'s');
+ $childs.=api_array_to_xml($v, $k);
+ }
+ }
+ $res = $childs;
+ if ($ename!="") $res = "<$ename $attrs>$res$ename>";
+ return $res;
+ }
+
/**
* load api $templatename for $type and replace $data array
*/
@@ -692,13 +720,17 @@
case "rss":
case "xml":
$data = array_xmlify($data);
- $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
- if(! $tpl) {
- header ("Content-Type: text/xml");
- echo ''."\n".'not implemented';
- killme();
+ if ($templatename==="") {
+ $ret = api_array_to_xml($data);
+ } else {
+ $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
+ if(! $tpl) {
+ header ("Content-Type: text/xml");
+ echo ''."\n".'not implemented';
+ killme();
+ }
+ $ret = replace_macros($tpl, $data);
}
- $ret = replace_macros($tpl, $data);
break;
case "json":
$ret = $data;
@@ -781,8 +813,6 @@
if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
- require_once('library/HTMLPurifier.auto.php');
-
$txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null);
@@ -822,9 +852,6 @@
if(requestdata('htmlstatus')) {
$txt = requestdata('htmlstatus');
if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
-
- require_once('library/HTMLPurifier.auto.php');
-
$txt = html2bb_video($txt);
$config = HTMLPurifier_Config::createDefault();
@@ -875,7 +902,8 @@
if ($posts_day > $throttle_day) {
logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
- die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
+ #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
+ throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
}
}
@@ -894,7 +922,9 @@
if ($posts_week > $throttle_week) {
logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
- die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
+ #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
+ throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
+
}
}
@@ -913,7 +943,8 @@
if ($posts_month > $throttle_month) {
logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
- die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
+ #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
+ throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
}
}
@@ -1493,15 +1524,21 @@
if ($max_id > 0)
$sql_extra = ' AND `item`.`id` <= '.intval($max_id);
+ // Not sure why this query was so complicated. We should keep it here for a while,
+ // just to make sure that we really don't need it.
+ // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
+ // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
+
$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
- FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
- ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
- WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
- AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
- AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
+ FROM `item`
+ INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
+ WHERE `item`.`parent` = %d AND `item`.`visible`
+ AND NOT `item`.`moderated` AND NOT `item`.`deleted`
+ AND `item`.`uid` = %d AND `item`.`verb` = '%s'
+ AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
AND `item`.`id`>%d $sql_extra
ORDER BY `item`.`id` DESC LIMIT %d ,%d",
intval($id), intval(api_user()),
@@ -1519,6 +1556,7 @@
return api_apply_template("timeline", $type, $data);
}
api_register_func('api/conversation/show','api_conversation_show', true);
+ api_register_func('api/statusnet/conversation','api_conversation_show', true);
/**
@@ -1660,13 +1698,13 @@
`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
- FROM `item`, `contact`
+ FROM `item` FORCE INDEX (`uid_id`), `contact`
WHERE `item`.`uid` = %d AND `verb` = '%s'
AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
- AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
+ AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
AND `contact`.`id` = `item`.`contact-id`
- AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
- AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
+ AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
+ AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
$sql_extra
AND `item`.`id`>%d
ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
@@ -1781,7 +1819,7 @@
$action_argv_id=2;
if ($a->argv[1]=="1.1") $action_argv_id=3;
- if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
+ if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
$action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
if ($a->argc==$action_argv_id+2) {
$itemid = intval($a->argv[$action_argv_id+1]);
@@ -2027,6 +2065,16 @@
$statushtml = trim(bbcode($body, false, false));
+ $search = array(" ", "