diff --git a/README.translate.md b/README.translate.md
index f43406361..728a56ab3 100644
--- a/README.translate.md
+++ b/README.translate.md
@@ -4,42 +4,32 @@ Friendica translations
Translation Process
-------------------
-The strings used in the UI of Friendica is translated at [Transifex] [1] and then
-included in the git repository at github. If you want to help with translation
-for any language, be it correcting terms or translating friendica to a
-currently not supported language, please register an account at transifex.com
-and contact the friendica translation team there.
+The strings used in the UI of Friendica is translated at [Transifex] [1] and then included in the git repository at github.
+If you want to help with translation for any language, be it correcting terms or translating friendica to a currently not supported language, please register an account at transifex.com and contact the friendica translation team there.
-Translating friendica is simple. Just use the online tool at transifex. If you
-don't want to deal with git & co. that is fine, we check the status of the
-translations regularly and import them into the source tree at github so that
-others can use them.
+Translating friendica is simple.
+Just use the online tool at transifex.
+If you don't want to deal with git & co. that is fine, we check the status of the translations regularly and import them into the source tree at github so that others can use them.
-We do not include every translation from transifex in the source tree to avoid
-a scattered and disturbed overall experience. As an uneducated guess we have a
-lower limit of 50% translated strings before we include the language (for the
-core message.po file, addon translation will be included once all strings of
-an addon are translated. This limit is judging only by the amount of translated
-strings under the assumption that the most prominent strings for the UI will be
-translated first by a translation team. If you feel your translation useable
-before this limit, please contact us and we will probably include your teams
-work in the source tree.
+We do not include every translation from transifex in the source tree to avoid a scattered and disturbed overall experience.
+As an uneducated guess we have a lower limit of 50% translated strings before we include the language (for the core messages.po file, addont translation will be included once all strings of an addon are translated.
+This limit is judging only by the amount of translated strings under the assumption that the most prominent strings for the UI will be translated first by a translation team.
+If you feel your translation useable before this limit, please contact us and we will probably include your teams work in the source tree.
-If you want to get your work into the source tree yourself, feel free to do so
-and contact us with and question that arises. The process is simple and
-friendica ships with all the tools necessary.
+If you want to help translating, please concentrate on the core messages.po file first.
+We will only include translations with a sufficient translated messages.po file.
+Translations of addons will only be included, when the core file is included as well.
+
+If you want to get your work into the source tree yourself, feel free to do so and contact us with and question that arises.
+The process is simple and friendica ships with all the tools necessary.
The location of the translated files in the source tree is
/view/LNG-CODE/
where LNG-CODE is the language code used, e.g. de for German or fr for French.
-For the email templates (the *.tpl files) just place them into the directory
-and you are done. The translated strings come as a "message.po" file from
-transifex which needs to be translated into the PHP file friendica uses. To do
-so, place the file in the directory mentioned above and use the "po2php"
-utility from the util directory of your friendica installation.
+The translated strings come as a "message.po" file from transifex which needs to be translated into the PHP file friendica uses.
+To do so, place the file in the directory mentioned above and use the "po2php" utility from the util directory of your friendica installation.
-Assuming you want to convert the German localization which is placed in
-view/de/message.po you would do the following.
+Assuming you want to convert the German localization which is placed in view/de/message.po you would do the following.
1. Navigate at the command prompt to the base directory of your
friendica installation
@@ -51,11 +41,11 @@ view/de/message.po you would do the following.
The output of the script will be placed at view/de/strings.php where
friendica is expecting it, so you can test your translation immediately.
-
+
3. Visit your friendica page to check if it still works in the language you
just translated. If not try to find the error, most likely PHP will give
you a hint in the log/warnings.about the error.
-
+
For debugging you can also try to "run" the file with PHP. This should
not give any output if the file is ok but might give a hint for
searching the bug in the file.
@@ -69,30 +59,10 @@ view/de/message.po you would do the following.
Utilities
---------
-Additional to the po2php script there are some more utilities for translation
-in the "util" directory of the friendica source tree. If you only want to
-translate friendica into another language you won't need any of these tools most
-likely but it gives you an idea how the translation process of friendica
-works.
+Additional to the po2php script there are some more utilities for translation in the "util" directory of the friendica source tree.
+If you only want to translate friendica into another language you wont need any of these tools most likely but it gives you an idea how the translation process of friendica works.
For further information see the utils/README file.
-Known Problems
---------------
-
-Friendica uses the language setting of the visitors browser to determain the
-language for the UI. Most of the time this works, but there are some known
-quirks.
-
-One is that some browsers, like Safari, do the setting to "de-de" but friendica
-only has a "de" localisation. A workaround would be to add a symbolic link
-from
- $friendica/view/de-de
-pointing to
- $friendica/view/de
-
-Links
------
-
[1]: https://www.transifex.com/projects/p/friendica/
diff --git a/boot.php b/boot.php
index 497a97b0e..dd70040c6 100644
--- a/boot.php
+++ b/boot.php
@@ -17,6 +17,8 @@
* 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');
@@ -36,7 +38,7 @@ define ( 'FRIENDICA_PLATFORM', 'Friendica');
define ( 'FRIENDICA_CODENAME', 'Asparagus');
define ( 'FRIENDICA_VERSION', '3.5-dev' );
define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
-define ( 'DB_UPDATE_VERSION', 1191 );
+define ( 'DB_UPDATE_VERSION', 1194 );
/**
* @brief Constant with a HTML line break.
@@ -467,6 +469,7 @@ class App {
public $is_tablet;
public $is_friendica_app;
public $performance = array();
+ public $callstack = array();
public $nav_sel;
@@ -529,6 +532,8 @@ class App {
private $cached_profile_image;
private $cached_profile_picdate;
+ private static $a;
+
/**
* @brief App constructor.
*/
@@ -554,6 +559,12 @@ class App {
$this->performance["marktime"] = 0;
$this->performance["markstart"] = microtime(true);
+ $this->callstack["database"] = array();
+ $this->callstack["network"] = array();
+ $this->callstack["file"] = array();
+ $this->callstack["rendering"] = array();
+ $this->callstack["parser"] = array();
+
$this->config = array();
$this->page = array();
$this->pager= array();
@@ -703,6 +714,8 @@ class App {
}
}
+ self::$a = $this;
+
}
function get_basepath() {
@@ -727,6 +740,10 @@ class App {
function get_baseurl($ssl = false) {
+ // Is the function called statically?
+ if (!is_object($this))
+ return(self::$a->get_baseurl($ssl));
+
$scheme = $this->scheme;
if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
@@ -903,6 +920,10 @@ class App {
}
function get_cached_avatar_image($avatar_image){
+ return $avatar_image;
+
+ // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
+ /*
if($this->cached_profile_image[$avatar_image])
return $this->cached_profile_image[$avatar_image];
@@ -922,6 +943,7 @@ class App {
}
}
return $this->cached_profile_image[$avatar_image];
+ */
}
@@ -1016,6 +1038,20 @@ class App {
$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);
+
+ array_shift($trace);
+
+ $function = array();
+ foreach ($trace AS $func)
+ $function[] = $func["function"];
+
+ $function = implode(", ", $function);
+
+ $this->callstack[$value][$function] += (float)$duration;
+
}
function mark_timestamp($mark) {
diff --git a/database.sql b/database.sql
index e3768c1ef..70b315ea2 100644
--- a/database.sql
+++ b/database.sql
@@ -1,6 +1,6 @@
-- ------------------------------------------
--- Friendica 3.4.2 (Lily of the valley)
--- DB_UPDATE_VERSION 1190
+-- Friendica 3.5-dev (Asparagus)
+-- DB_UPDATE_VERSION 1193
-- ------------------------------------------
@@ -8,20 +8,21 @@
-- TABLE addon
--
CREATE TABLE IF NOT EXISTS `addon` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL DEFAULT '',
`version` varchar(255) NOT NULL DEFAULT '',
`installed` tinyint(1) NOT NULL DEFAULT 0,
`hidden` tinyint(1) NOT NULL DEFAULT 0,
`timestamp` bigint(20) NOT NULL DEFAULT 0,
- `plugin_admin` tinyint(1) NOT NULL DEFAULT 0
+ `plugin_admin` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE attach
--
CREATE TABLE IF NOT EXISTS `attach` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`hash` varchar(64) NOT NULL DEFAULT '',
`filename` varchar(255) NOT NULL DEFAULT '',
@@ -33,28 +34,31 @@ CREATE TABLE IF NOT EXISTS `attach` (
`allow_cid` mediumtext NOT NULL,
`allow_gid` mediumtext NOT NULL,
`deny_cid` mediumtext NOT NULL,
- `deny_gid` mediumtext NOT NULL
+ `deny_gid` mediumtext NOT NULL,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE auth_codes
--
CREATE TABLE IF NOT EXISTS `auth_codes` (
- `id` varchar(40) NOT NULL PRIMARY KEY,
+ `id` varchar(40) NOT NULL,
`client_id` varchar(20) NOT NULL DEFAULT '',
`redirect_uri` varchar(200) NOT NULL DEFAULT '',
`expires` int(11) NOT NULL DEFAULT 0,
- `scope` varchar(250) NOT NULL DEFAULT ''
+ `scope` varchar(250) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE cache
--
CREATE TABLE IF NOT EXISTS `cache` (
- `k` varchar(255) NOT NULL PRIMARY KEY,
+ `k` varchar(255) NOT NULL,
`v` text NOT NULL,
`expire_mode` int(11) NOT NULL DEFAULT 0,
`updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`k`),
INDEX `updated` (`updated`)
) DEFAULT CHARSET=utf8;
@@ -62,34 +66,37 @@ CREATE TABLE IF NOT EXISTS `cache` (
-- TABLE challenge
--
CREATE TABLE IF NOT EXISTS `challenge` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`challenge` varchar(255) NOT NULL DEFAULT '',
`dfrn-id` varchar(255) NOT NULL DEFAULT '',
`expire` int(11) NOT NULL DEFAULT 0,
`type` varchar(255) NOT NULL DEFAULT '',
- `last_update` varchar(255) NOT NULL DEFAULT ''
+ `last_update` varchar(255) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE clients
--
CREATE TABLE IF NOT EXISTS `clients` (
- `client_id` varchar(20) NOT NULL PRIMARY KEY,
+ `client_id` varchar(20) NOT NULL,
`pw` varchar(20) NOT NULL DEFAULT '',
`redirect_uri` varchar(200) NOT NULL DEFAULT '',
`name` text,
`icon` text,
- `uid` int(11) NOT NULL DEFAULT 0
+ `uid` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`client_id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE config
--
CREATE TABLE IF NOT EXISTS `config` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`cat` varchar(255) NOT NULL DEFAULT '',
`k` varchar(255) NOT NULL DEFAULT '',
`v` text NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `cat_k` (`cat`(30),`k`(30))
) DEFAULT CHARSET=utf8;
@@ -97,7 +104,7 @@ CREATE TABLE IF NOT EXISTS `config` (
-- TABLE contact
--
CREATE TABLE IF NOT EXISTS `contact` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`self` tinyint(1) NOT NULL DEFAULT 0,
@@ -162,6 +169,7 @@ CREATE TABLE IF NOT EXISTS `contact` (
`notify_new_posts` tinyint(1) NOT NULL DEFAULT 0,
`fetch_further_information` tinyint(1) NOT NULL DEFAULT 0,
`ffi_keyword_blacklist` mediumtext NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`)
) DEFAULT CHARSET=utf8;
@@ -169,7 +177,7 @@ CREATE TABLE IF NOT EXISTS `contact` (
-- TABLE conv
--
CREATE TABLE IF NOT EXISTS `conv` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`guid` varchar(64) NOT NULL DEFAULT '',
`recips` mediumtext NOT NULL,
`uid` int(11) NOT NULL DEFAULT 0,
@@ -177,6 +185,7 @@ CREATE TABLE IF NOT EXISTS `conv` (
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`subject` mediumtext NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`)
) DEFAULT CHARSET=utf8;
@@ -184,27 +193,29 @@ CREATE TABLE IF NOT EXISTS `conv` (
-- TABLE deliverq
--
CREATE TABLE IF NOT EXISTS `deliverq` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`cmd` varchar(32) NOT NULL DEFAULT '',
`item` int(11) NOT NULL DEFAULT 0,
- `contact` int(11) NOT NULL DEFAULT 0
+ `contact` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE dsprphotoq
--
CREATE TABLE IF NOT EXISTS `dsprphotoq` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `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
+ `attempt` tinyint(4) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE event
--
CREATE TABLE IF NOT EXISTS `event` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`cid` int(11) NOT NULL DEFAULT 0,
`uri` varchar(255) NOT NULL DEFAULT '',
@@ -223,6 +234,7 @@ CREATE TABLE IF NOT EXISTS `event` (
`allow_gid` mediumtext NOT NULL,
`deny_cid` mediumtext NOT NULL,
`deny_gid` mediumtext NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`)
) DEFAULT CHARSET=utf8;
@@ -230,7 +242,7 @@ CREATE TABLE IF NOT EXISTS `event` (
-- TABLE fcontact
--
CREATE TABLE IF NOT EXISTS `fcontact` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`url` varchar(255) NOT NULL DEFAULT '',
`name` varchar(255) NOT NULL DEFAULT '',
`photo` varchar(255) NOT NULL DEFAULT '',
@@ -246,6 +258,7 @@ CREATE TABLE IF NOT EXISTS `fcontact` (
`alias` varchar(255) NOT NULL DEFAULT '',
`pubkey` text NOT NULL,
`updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`),
INDEX `addr` (`addr`)
) DEFAULT CHARSET=utf8;
@@ -253,20 +266,22 @@ CREATE TABLE IF NOT EXISTS `fcontact` (
-- TABLE ffinder
--
CREATE TABLE IF NOT EXISTS `ffinder` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`cid` int(10) unsigned NOT NULL DEFAULT 0,
- `fid` int(10) unsigned NOT NULL DEFAULT 0
+ `fid` int(10) unsigned NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE fserver
--
CREATE TABLE IF NOT EXISTS `fserver` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`server` varchar(255) NOT NULL DEFAULT '',
`posturl` varchar(255) NOT NULL DEFAULT '',
`key` text NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `server` (`server`)
) DEFAULT CHARSET=utf8;
@@ -274,7 +289,7 @@ CREATE TABLE IF NOT EXISTS `fserver` (
-- TABLE fsuggest
--
CREATE TABLE IF NOT EXISTS `fsuggest` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`cid` int(11) NOT NULL DEFAULT 0,
`name` varchar(255) NOT NULL DEFAULT '',
@@ -282,16 +297,18 @@ CREATE TABLE IF NOT EXISTS `fsuggest` (
`request` varchar(255) NOT NULL DEFAULT '',
`photo` varchar(255) NOT NULL DEFAULT '',
`note` text NOT NULL,
- `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE gcign
--
CREATE TABLE IF NOT EXISTS `gcign` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`gcid` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`),
INDEX `gcid` (`gcid`)
) DEFAULT CHARSET=utf8;
@@ -300,7 +317,7 @@ CREATE TABLE IF NOT EXISTS `gcign` (
-- TABLE gcontact
--
CREATE TABLE IF NOT EXISTS `gcontact` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(255) NOT NULL DEFAULT '',
`nick` varchar(255) NOT NULL DEFAULT '',
`url` varchar(255) NOT NULL DEFAULT '',
@@ -315,11 +332,17 @@ CREATE TABLE IF NOT EXISTS `gcontact` (
`about` text NOT NULL,
`keywords` text NOT NULL,
`gender` varchar(32) NOT NULL DEFAULT '',
+ `birthday` varchar(32) NOT NULL DEFAULT '0000-00-00',
`community` tinyint(1) NOT NULL DEFAULT 0,
+ `hide` tinyint(1) NOT NULL DEFAULT 0,
+ `nsfw` tinyint(1) NOT NULL DEFAULT 0,
`network` varchar(255) NOT NULL DEFAULT '',
`addr` varchar(255) NOT NULL DEFAULT '',
+ `notify` text NOT NULL,
+ `alias` varchar(255) NOT NULL DEFAULT '',
`generation` tinyint(3) NOT NULL DEFAULT 0,
`server_url` varchar(255) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`),
INDEX `nurl` (`nurl`),
INDEX `updated` (`updated`)
) DEFAULT CHARSET=utf8;
@@ -328,12 +351,13 @@ CREATE TABLE IF NOT EXISTS `gcontact` (
-- TABLE glink
--
CREATE TABLE IF NOT EXISTS `glink` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`cid` int(11) NOT NULL DEFAULT 0,
`uid` int(11) NOT NULL DEFAULT 0,
`gcid` int(11) NOT NULL DEFAULT 0,
`zcid` int(11) NOT NULL DEFAULT 0,
`updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`),
INDEX `cid_uid_gcid_zcid` (`cid`,`uid`,`gcid`,`zcid`),
INDEX `gcid` (`gcid`),
INDEX `zcid` (`zcid`)
@@ -343,11 +367,12 @@ CREATE TABLE IF NOT EXISTS `glink` (
-- TABLE group
--
CREATE TABLE IF NOT EXISTS `group` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`visible` tinyint(1) NOT NULL DEFAULT 0,
`deleted` tinyint(1) NOT NULL DEFAULT 0,
`name` varchar(255) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`)
) DEFAULT CHARSET=utf8;
@@ -355,10 +380,11 @@ CREATE TABLE IF NOT EXISTS `group` (
-- TABLE group_member
--
CREATE TABLE IF NOT EXISTS `group_member` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`gid` int(10) unsigned NOT NULL DEFAULT 0,
`contact-id` int(10) unsigned NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `uid_gid_contactid` (`uid`,`gid`,`contact-id`)
) DEFAULT CHARSET=utf8;
@@ -366,7 +392,7 @@ CREATE TABLE IF NOT EXISTS `group_member` (
-- TABLE gserver
--
CREATE TABLE IF NOT EXISTS `gserver` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`url` varchar(255) NOT NULL DEFAULT '',
`nurl` varchar(255) NOT NULL DEFAULT '',
`version` varchar(255) NOT NULL DEFAULT '',
@@ -381,6 +407,7 @@ CREATE TABLE IF NOT EXISTS `gserver` (
`last_poco_query` datetime DEFAULT '0000-00-00 00:00:00',
`last_contact` datetime DEFAULT '0000-00-00 00:00:00',
`last_failure` datetime DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`),
INDEX `nurl` (`nurl`)
) DEFAULT CHARSET=utf8;
@@ -388,11 +415,12 @@ CREATE TABLE IF NOT EXISTS `gserver` (
-- TABLE guid
--
CREATE TABLE IF NOT EXISTS `guid` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `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`)
@@ -402,11 +430,12 @@ CREATE TABLE IF NOT EXISTS `guid` (
-- TABLE hook
--
CREATE TABLE IF NOT EXISTS `hook` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`hook` varchar(255) NOT NULL DEFAULT '',
`file` varchar(255) NOT NULL DEFAULT '',
`function` varchar(255) NOT NULL DEFAULT '',
`priority` int(11) unsigned NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `hook_file_function` (`hook`(30),`file`(60),`function`(30))
) DEFAULT CHARSET=utf8;
@@ -414,7 +443,7 @@ CREATE TABLE IF NOT EXISTS `hook` (
-- TABLE intro
--
CREATE TABLE IF NOT EXISTS `intro` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`fid` int(11) NOT NULL DEFAULT 0,
`contact-id` int(11) NOT NULL DEFAULT 0,
@@ -424,18 +453,20 @@ CREATE TABLE IF NOT EXISTS `intro` (
`hash` varchar(255) NOT NULL DEFAULT '',
`datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`blocked` tinyint(1) NOT NULL DEFAULT 1,
- `ignore` tinyint(1) NOT NULL DEFAULT 0
+ `ignore` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE item
--
CREATE TABLE IF NOT EXISTS `item` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`guid` varchar(255) NOT NULL DEFAULT '',
`uri` varchar(255) NOT NULL DEFAULT '',
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`contact-id` int(11) NOT NULL DEFAULT 0,
+ `gcontact-id` int(11) unsigned NOT NULL DEFAULT 0,
`type` varchar(255) NOT NULL DEFAULT '',
`wall` tinyint(1) NOT NULL DEFAULT 0,
`gravity` tinyint(1) NOT NULL DEFAULT 0,
@@ -493,6 +524,7 @@ CREATE TABLE IF NOT EXISTS `item` (
`rendered-hash` varchar(32) NOT NULL DEFAULT '',
`rendered-html` mediumtext NOT NULL,
`global` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `guid` (`guid`),
INDEX `uri` (`uri`),
INDEX `parent` (`parent`),
@@ -509,6 +541,7 @@ CREATE TABLE IF NOT EXISTS `item` (
INDEX `uid_thrparent` (`uid`,`thr-parent`),
INDEX `uid_parenturi` (`uid`,`parent-uri`),
INDEX `uid_contactid_created` (`uid`,`contact-id`,`created`),
+ INDEX `gcontactid_uid_created` (`gcontact-id`,`uid`,`created`),
INDEX `wall_body` (`wall`,`body`(6)),
INDEX `uid_visible_moderated_created` (`uid`,`visible`,`moderated`,`created`),
INDEX `uid_uri` (`uid`,`uri`),
@@ -531,11 +564,12 @@ CREATE TABLE IF NOT EXISTS `item` (
-- TABLE item_id
--
CREATE TABLE IF NOT EXISTS `item_id` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`iid` int(11) NOT NULL DEFAULT 0,
`uid` int(11) NOT NULL DEFAULT 0,
`sid` varchar(255) NOT NULL DEFAULT '',
`service` varchar(255) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`),
INDEX `sid` (`sid`),
INDEX `service` (`service`),
@@ -546,17 +580,18 @@ CREATE TABLE IF NOT EXISTS `item_id` (
-- TABLE locks
--
CREATE TABLE IF NOT EXISTS `locks` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`name` varchar(128) NOT NULL DEFAULT '',
`locked` tinyint(1) NOT NULL DEFAULT 0,
- `created` datetime DEFAULT '0000-00-00 00:00:00'
+ `created` datetime DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE mail
--
CREATE TABLE IF NOT EXISTS `mail` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`guid` varchar(64) NOT NULL DEFAULT '',
`from-name` varchar(255) NOT NULL DEFAULT '',
@@ -573,6 +608,7 @@ CREATE TABLE IF NOT EXISTS `mail` (
`uri` varchar(255) NOT NULL DEFAULT '',
`parent-uri` varchar(255) NOT NULL DEFAULT '',
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`),
INDEX `guid` (`guid`),
INDEX `convid` (`convid`),
@@ -585,7 +621,7 @@ CREATE TABLE IF NOT EXISTS `mail` (
-- TABLE mailacct
--
CREATE TABLE IF NOT EXISTS `mailacct` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`server` varchar(255) NOT NULL DEFAULT '',
`port` int(11) NOT NULL DEFAULT 0,
@@ -597,16 +633,18 @@ CREATE TABLE IF NOT EXISTS `mailacct` (
`action` int(11) NOT NULL DEFAULT 0,
`movetofolder` varchar(255) NOT NULL DEFAULT '',
`pubmail` tinyint(1) NOT NULL DEFAULT 0,
- `last_check` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
+ `last_check` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE manage
--
CREATE TABLE IF NOT EXISTS `manage` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`mid` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `uid_mid` (`uid`,`mid`)
) DEFAULT CHARSET=utf8;
@@ -614,7 +652,7 @@ CREATE TABLE IF NOT EXISTS `manage` (
-- TABLE notify
--
CREATE TABLE IF NOT EXISTS `notify` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`hash` varchar(64) NOT NULL DEFAULT '',
`type` int(11) NOT NULL DEFAULT 0,
`name` varchar(255) NOT NULL DEFAULT '',
@@ -629,6 +667,7 @@ CREATE TABLE IF NOT EXISTS `notify` (
`seen` tinyint(1) NOT NULL DEFAULT 0,
`verb` varchar(255) NOT NULL DEFAULT '',
`otype` varchar(16) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`)
) DEFAULT CHARSET=utf8;
@@ -636,24 +675,50 @@ CREATE TABLE IF NOT EXISTS `notify` (
-- TABLE notify-threads
--
CREATE TABLE IF NOT EXISTS `notify-threads` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`notify-id` int(11) NOT NULL DEFAULT 0,
`master-parent-item` int(10) unsigned NOT NULL DEFAULT 0,
`parent-item` int(10) unsigned NOT NULL DEFAULT 0,
`receiver-uid` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `master-parent-item` (`master-parent-item`),
INDEX `receiver-uid` (`receiver-uid`)
) DEFAULT CHARSET=utf8;
+--
+-- TABLE oembed
+--
+CREATE TABLE IF NOT EXISTS `oembed` (
+ `url` varchar(255) NOT NULL,
+ `content` text NOT NULL,
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`url`),
+ INDEX `created` (`created`)
+) DEFAULT CHARSET=utf8;
+
+--
+-- TABLE parsed_url
+--
+CREATE TABLE IF NOT EXISTS `parsed_url` (
+ `url` varchar(255) NOT NULL,
+ `guessing` tinyint(1) NOT NULL DEFAULT 0,
+ `oembed` tinyint(1) NOT NULL DEFAULT 0,
+ `content` text NOT NULL,
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`url`,`guessing`,`oembed`),
+ INDEX `created` (`created`)
+) DEFAULT CHARSET=utf8;
+
--
-- TABLE pconfig
--
CREATE TABLE IF NOT EXISTS `pconfig` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`cat` varchar(255) NOT NULL DEFAULT '',
`k` varchar(255) NOT NULL DEFAULT '',
`v` mediumtext NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `uid_cat_k` (`uid`,`cat`(30),`k`(30))
) DEFAULT CHARSET=utf8;
@@ -661,7 +726,7 @@ CREATE TABLE IF NOT EXISTS `pconfig` (
-- TABLE photo
--
CREATE TABLE IF NOT EXISTS `photo` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`contact-id` int(10) unsigned NOT NULL DEFAULT 0,
`guid` varchar(64) NOT NULL DEFAULT '',
@@ -683,6 +748,7 @@ CREATE TABLE IF NOT EXISTS `photo` (
`allow_gid` mediumtext NOT NULL,
`deny_cid` mediumtext NOT NULL,
`deny_gid` mediumtext NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`),
INDEX `resource-id` (`resource-id`),
INDEX `guid` (`guid`)
@@ -692,7 +758,7 @@ CREATE TABLE IF NOT EXISTS `photo` (
-- TABLE poll
--
CREATE TABLE IF NOT EXISTS `poll` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`q0` mediumtext NOT NULL,
`q1` mediumtext NOT NULL,
@@ -704,6 +770,7 @@ CREATE TABLE IF NOT EXISTS `poll` (
`q7` mediumtext NOT NULL,
`q8` mediumtext NOT NULL,
`q9` mediumtext NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`)
) DEFAULT CHARSET=utf8;
@@ -711,9 +778,10 @@ CREATE TABLE IF NOT EXISTS `poll` (
-- TABLE poll_result
--
CREATE TABLE IF NOT EXISTS `poll_result` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`poll_id` int(11) NOT NULL DEFAULT 0,
`choice` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `poll_id` (`poll_id`),
INDEX `choice` (`choice`)
) DEFAULT CHARSET=utf8;
@@ -722,7 +790,7 @@ CREATE TABLE IF NOT EXISTS `poll_result` (
-- TABLE profile
--
CREATE TABLE IF NOT EXISTS `profile` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`profile-name` varchar(255) NOT NULL DEFAULT '',
`is-default` tinyint(1) NOT NULL DEFAULT 0,
@@ -763,6 +831,7 @@ CREATE TABLE IF NOT EXISTS `profile` (
`thumb` varchar(255) NOT NULL DEFAULT '',
`publish` tinyint(1) NOT NULL DEFAULT 0,
`net-publish` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `hometown` (`hometown`)
) DEFAULT CHARSET=utf8;
@@ -770,39 +839,42 @@ CREATE TABLE IF NOT EXISTS `profile` (
-- TABLE profile_check
--
CREATE TABLE IF NOT EXISTS `profile_check` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`cid` int(10) unsigned NOT NULL DEFAULT 0,
`dfrn_id` varchar(255) NOT NULL DEFAULT '',
`sec` varchar(255) NOT NULL DEFAULT '',
- `expire` int(11) NOT NULL DEFAULT 0
+ `expire` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE push_subscriber
--
CREATE TABLE IF NOT EXISTS `push_subscriber` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`callback_url` varchar(255) NOT NULL DEFAULT '',
`topic` varchar(255) NOT NULL DEFAULT '',
`nickname` varchar(255) NOT NULL DEFAULT '',
`push` int(11) NOT NULL DEFAULT 0,
`last_update` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
- `secret` varchar(255) NOT NULL DEFAULT ''
+ `secret` varchar(255) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE queue
--
CREATE TABLE IF NOT EXISTS `queue` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`cid` int(11) NOT NULL DEFAULT 0,
`network` varchar(32) NOT NULL DEFAULT '',
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`last` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`content` mediumtext NOT NULL,
`batch` tinyint(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `cid` (`cid`),
INDEX `created` (`created`),
INDEX `last` (`last`),
@@ -814,21 +886,23 @@ CREATE TABLE IF NOT EXISTS `queue` (
-- TABLE register
--
CREATE TABLE IF NOT EXISTS `register` (
- `id` int(11) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) unsigned NOT NULL auto_increment,
`hash` varchar(255) NOT NULL DEFAULT '',
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`uid` int(11) unsigned NOT NULL DEFAULT 0,
`password` varchar(255) NOT NULL DEFAULT '',
- `language` varchar(16) NOT NULL DEFAULT ''
+ `language` varchar(16) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE search
--
CREATE TABLE IF NOT EXISTS `search` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`term` varchar(255) NOT NULL DEFAULT '',
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`),
INDEX `term` (`term`)
) DEFAULT CHARSET=utf8;
@@ -837,10 +911,11 @@ CREATE TABLE IF NOT EXISTS `search` (
-- TABLE session
--
CREATE TABLE IF NOT EXISTS `session` (
- `id` bigint(20) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `id` bigint(20) unsigned NOT NULL auto_increment,
`sid` varchar(255) NOT NULL DEFAULT '',
`data` text NOT NULL,
`expire` int(10) unsigned NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`),
INDEX `sid` (`sid`),
INDEX `expire` (`expire`)
) DEFAULT CHARSET=utf8;
@@ -849,12 +924,13 @@ CREATE TABLE IF NOT EXISTS `session` (
-- TABLE sign
--
CREATE TABLE IF NOT EXISTS `sign` (
- `id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `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`)
) DEFAULT CHARSET=utf8;
@@ -863,12 +939,13 @@ CREATE TABLE IF NOT EXISTS `sign` (
-- TABLE spam
--
CREATE TABLE IF NOT EXISTS `spam` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`uid` int(11) NOT NULL DEFAULT 0,
`spam` int(11) NOT NULL DEFAULT 0,
`ham` int(11) NOT NULL DEFAULT 0,
`term` varchar(255) NOT NULL DEFAULT '',
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`),
INDEX `uid` (`uid`),
INDEX `spam` (`spam`),
INDEX `ham` (`ham`),
@@ -879,7 +956,7 @@ CREATE TABLE IF NOT EXISTS `spam` (
-- TABLE term
--
CREATE TABLE IF NOT EXISTS `term` (
- `tid` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
+ `tid` int(10) unsigned NOT NULL auto_increment,
`oid` int(10) unsigned NOT NULL DEFAULT 0,
`otype` tinyint(3) unsigned NOT NULL DEFAULT 0,
`type` tinyint(3) unsigned NOT NULL DEFAULT 0,
@@ -891,6 +968,7 @@ CREATE TABLE IF NOT EXISTS `term` (
`global` tinyint(1) NOT NULL DEFAULT 0,
`aid` int(10) unsigned NOT NULL DEFAULT 0,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
+ PRIMARY KEY(`tid`),
INDEX `oid_otype_type_term` (`oid`,`otype`,`type`,`term`),
INDEX `uid_term_tid` (`uid`,`term`,`tid`),
INDEX `type_term` (`type`,`term`),
@@ -903,9 +981,10 @@ CREATE TABLE IF NOT EXISTS `term` (
-- TABLE thread
--
CREATE TABLE IF NOT EXISTS `thread` (
- `iid` int(10) unsigned NOT NULL DEFAULT 0 PRIMARY KEY,
+ `iid` int(10) unsigned NOT NULL DEFAULT 0,
`uid` int(10) unsigned NOT NULL DEFAULT 0,
`contact-id` int(11) unsigned NOT NULL DEFAULT 0,
+ `gcontact-id` int(11) unsigned NOT NULL DEFAULT 0,
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`edited` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`commented` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -926,12 +1005,15 @@ CREATE TABLE IF NOT EXISTS `thread` (
`forum_mode` tinyint(1) NOT NULL DEFAULT 0,
`mention` tinyint(1) NOT NULL DEFAULT 0,
`network` varchar(32) NOT NULL DEFAULT '',
+ PRIMARY KEY(`iid`),
INDEX `created` (`created`),
INDEX `commented` (`commented`),
INDEX `uid_network_commented` (`uid`,`network`,`commented`),
INDEX `uid_network_created` (`uid`,`network`,`created`),
INDEX `uid_contactid_commented` (`uid`,`contact-id`,`commented`),
INDEX `uid_contactid_created` (`uid`,`contact-id`,`created`),
+ INDEX `uid_gcontactid_commented` (`uid`,`gcontact-id`,`commented`),
+ INDEX `uid_gcontactid_created` (`uid`,`gcontact-id`,`created`),
INDEX `wall_private_received` (`wall`,`private`,`received`),
INDEX `uid_created` (`uid`,`created`),
INDEX `uid_commented` (`uid`,`commented`)
@@ -941,33 +1023,20 @@ CREATE TABLE IF NOT EXISTS `thread` (
-- TABLE tokens
--
CREATE TABLE IF NOT EXISTS `tokens` (
- `id` varchar(40) NOT NULL PRIMARY KEY,
+ `id` varchar(40) NOT NULL,
`secret` text NOT NULL,
`client_id` varchar(20) NOT NULL DEFAULT '',
`expires` int(11) NOT NULL DEFAULT 0,
`scope` varchar(200) NOT NULL DEFAULT '',
- `uid` int(11) NOT NULL DEFAULT 0
-) DEFAULT CHARSET=utf8;
-
---
--- TABLE unique_contacts
---
-CREATE TABLE IF NOT EXISTS `unique_contacts` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
- `url` varchar(255) NOT NULL DEFAULT '',
- `nick` varchar(255) NOT NULL DEFAULT '',
- `name` varchar(255) NOT NULL DEFAULT '',
- `avatar` varchar(255) NOT NULL DEFAULT '',
- `location` varchar(255) NOT NULL DEFAULT '',
- `about` text NOT NULL,
- INDEX `url` (`url`)
+ `uid` int(11) NOT NULL DEFAULT 0,
+ PRIMARY KEY(`id`)
) DEFAULT CHARSET=utf8;
--
-- TABLE user
--
CREATE TABLE IF NOT EXISTS `user` (
- `uid` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `uid` int(11) NOT NULL auto_increment,
`guid` varchar(64) NOT NULL DEFAULT '',
`username` varchar(255) NOT NULL DEFAULT '',
`password` varchar(255) NOT NULL DEFAULT '',
@@ -1009,6 +1078,7 @@ CREATE TABLE IF NOT EXISTS `user` (
`deny_cid` mediumtext NOT NULL,
`deny_gid` mediumtext NOT NULL,
`openidserver` text NOT NULL,
+ PRIMARY KEY(`uid`),
INDEX `nickname` (`nickname`)
) DEFAULT CHARSET=utf8;
@@ -1016,8 +1086,9 @@ CREATE TABLE IF NOT EXISTS `user` (
-- TABLE userd
--
CREATE TABLE IF NOT EXISTS `userd` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`username` varchar(255) NOT NULL,
+ PRIMARY KEY(`id`),
INDEX `username` (`username`)
) DEFAULT CHARSET=utf8;
@@ -1025,12 +1096,13 @@ CREATE TABLE IF NOT EXISTS `userd` (
-- TABLE workerqueue
--
CREATE TABLE IF NOT EXISTS `workerqueue` (
- `id` int(11) NOT NULL auto_increment PRIMARY KEY,
+ `id` int(11) NOT NULL auto_increment,
`parameter` text NOT NULL,
`priority` tinyint(3) unsigned NOT NULL DEFAULT 0,
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`pid` int(11) NOT NULL DEFAULT 0,
`executed` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ PRIMARY KEY(`id`),
INDEX `created` (`created`)
) DEFAULT CHARSET=utf8;
diff --git a/doc/Forums.md b/doc/Forums.md
index 2eac81a72..54e8e3879 100644
--- a/doc/Forums.md
+++ b/doc/Forums.md
@@ -53,9 +53,12 @@ Posting to Community forums
If you are a member of a community forum, you may post to the forum by including an @-tag in the post mentioning the forum.
For example @bicycle would send my post to all members of the group "bicycle" in addition to the normal recipients.
-If your post is private you must also explicitly include the group in the post permissions (to allow the forum "contact" to see the post) **and** mention it in a tag (which redistributes the post to the forum members).
+If you mention a forum (you are a member of) in a new posting, the posting will be distributed to all members of the forum, regardless of your privacy settings for the posting.
+Also, if the forum is a public forum, your posting will be public for the all internet users.
+If your post is private you must also explicitly include the group in the post permissions (to allow the forum "contact" to see the post) **and** mention it in a tag (which redistributes the post to the forum members).
+Posting privately to a public forum, will result in your posting being displayed on the forum wall, but not on yours.
-You may also post to a community forum by posting a "wall-to-wall" post using secure cross-site authentication.
+You may also post to a community forum by posting a "wall-to-wall" post using secure cross-site authentication.
Comments which are relayed to community forums will be relayed back to the original post creator.
Mentioning the forum with an @-tag in a comment does not relay the message, as distribution is controlled entirely by the original post creator.
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 ae7d91607..86254cb29 100644
--- a/doc/Settings.md
+++ b/doc/Settings.md
@@ -24,6 +24,9 @@ You are not required to provide the year.
System settings
---
+**Settings should be done in the admin panel** (/admin).
+Those settings found in the database, will always override the settings added to the ``.htconfig.php`` file.
+
###Language
Please see util/README for information on creating language translations.
@@ -219,6 +222,8 @@ LOGGER_DEBUG will show a good deal of information about system activity but will
You may also select LOGGER_ALL but due to the volume of information we recommend only enabling this when you are tracking down a specific problem.
Other log levels are possible but are not being used at the present time.
+Please be aware that turning on the logging can fill up the disk space on your server relatively quick.
+You should take preventions with e.g. [logrotate](https://en.wikipedia.org/wiki/Log_rotation) or similar tools.
###PHP error logging
@@ -237,4 +242,6 @@ The vast majority of issues reported at these levels are completely harmless.
Please report to the developers any errors you encounter in the logs using the recommended settings above.
They generally indicate issues which need to be resolved.
-If you encounter a blank (white) page when using the application, view the PHP logs - as this almost always indicates an error has occurred.
+If you encounter a blank (white) page when using the application, view the PHP logs - as this almost always indicates an error has occurred.
+
+*Note*: PHP logging cannot be activated from the admin panel but has to be configured from the ``.htconfig.php`` file.
diff --git a/doc/Tags-and-Mentions.md b/doc/Tags-and-Mentions.md
index 5501d0d58..eac2c97f8 100644
--- a/doc/Tags-and-Mentions.md
+++ b/doc/Tags-and-Mentions.md
@@ -21,11 +21,22 @@ You can tag a person on a different network or one that is **not in your social
* @mike@macgirvin.com - This is called a "remote mention" and can only be an email-style locator, not a web URL.
-Unless their system blocks unsolicited "mentions", the person tagged will likely receive a "Mention" post/activity or become a direct participant in the conversation in the case of public posts. Please note that Friendica blocks incoming "mentions" from people with no relationship to you. This is a spam prevention measure.
+Unless their system blocks unsolicited "mentions", the person tagged will likely receive a "Mention" post/activity or become a direct participant in the conversation in the case of public posts.
+Friendica blocks incoming “mentions” from people with no relationship to you.
+The exception is an ongiong conversation started from a contact of both you and the 3rd person or a conversation in a forum where you are a member of.
+This is a spam prevention measure.
-Remote mentions are delivered using the OStatus protocol. This protocol is used by Friendica and GNU Social and several other systems, but is not currently implemented in Diaspora.
+Remote mentions are delivered using the OStatus protocol.
+This protocol is used by Friendica and GNU Social and several other systems, but is not currently implemented in Diaspora.
+As the OStatus protocol allows this Friendica user can be @-mentioned by users from platforms using this protocol in conversations if the "Enable OStatus support" is activated on the Friendica node.
+These @-mentions wont be blocked, even if there is no relationship between the sender and the receiver of the message.
-Friendica makes no distinction between people and groups for the purpose of tagging. (Some other networks use !group to indicate a group.)
+Friendica makes no distinction between people and forums for the purpose of tagging.
+(Some other networks use !forum to indicate a forum.)
+
+If you sort your contacts into groups, you cannot @-mention these groups.
+But you can select the group in the access control when creating a new posting, to allow (or disallow) a certain group of people to see the posting.
+See [Groups and Privacy](help/Groups-and-Privacy) for more details about grouping your contacts.
**Topical Tags**
diff --git a/doc/api.md b/doc/api.md
index ced078f55..c020f403f 100644
--- a/doc/api.md
+++ b/doc/api.md
@@ -7,6 +7,21 @@ 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,16 @@ 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/version (*)
#### Unsupported parameters
* user_id
@@ -507,7 +399,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 +409,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 +425,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 +465,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 +490,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 +514,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 +778,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
+
- */
+ /*
+ * 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/htconfig.md b/doc/htconfig.md
index 4764c287c..f9c92bfa0 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.
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/doc/translations.md b/doc/translations.md
index b874e9ea2..728a56ab3 100644
--- a/doc/translations.md
+++ b/doc/translations.md
@@ -4,42 +4,32 @@ Friendica translations
Translation Process
-------------------
-The strings used in the UI of Friendica is translated at [Transifex] [1] and then
-included in the git repository at github. If you want to help with translation
-for any language, be it correcting terms or translating friendica to a
-currently not supported language, please register an account at transifex.com
-and contact the friendica translation team there.
+The strings used in the UI of Friendica is translated at [Transifex] [1] and then included in the git repository at github.
+If you want to help with translation for any language, be it correcting terms or translating friendica to a currently not supported language, please register an account at transifex.com and contact the friendica translation team there.
-Translating friendica is simple. Just use the online tool at transifex. If you
-don't want to deal with git & co. that is fine, we check the status of the
-translations regularly and import them into the source tree at github so that
-others can use them.
+Translating friendica is simple.
+Just use the online tool at transifex.
+If you don't want to deal with git & co. that is fine, we check the status of the translations regularly and import them into the source tree at github so that others can use them.
-We do not include every translation from transifex in the source tree to avoid
-a scattered and disturbed overall experience. As an uneducated guess we have a
-lower limit of 50% translated strings before we include the language (for the
-core message.po file, addont translation will be included once all strings of
-an addon are translated. This limit is judging only by the amount of translated
-strings under the assumption that the most prominent strings for the UI will be
-translated first by a translation team. If you feel your translation useable
-before this limit, please contact us and we will probably include your teams
-work in the source tree.
+We do not include every translation from transifex in the source tree to avoid a scattered and disturbed overall experience.
+As an uneducated guess we have a lower limit of 50% translated strings before we include the language (for the core messages.po file, addont translation will be included once all strings of an addon are translated.
+This limit is judging only by the amount of translated strings under the assumption that the most prominent strings for the UI will be translated first by a translation team.
+If you feel your translation useable before this limit, please contact us and we will probably include your teams work in the source tree.
-If you want to get your work into the source tree yourself, feel free to do so
-and contact us with and question that arises. The process is simple and
-friendica ships with all the tools necessary.
+If you want to help translating, please concentrate on the core messages.po file first.
+We will only include translations with a sufficient translated messages.po file.
+Translations of addons will only be included, when the core file is included as well.
+
+If you want to get your work into the source tree yourself, feel free to do so and contact us with and question that arises.
+The process is simple and friendica ships with all the tools necessary.
The location of the translated files in the source tree is
/view/LNG-CODE/
where LNG-CODE is the language code used, e.g. de for German or fr for French.
-For the email templates (the *.tpl files) just place them into the directory
-and you are done. The translated strings come as a "message.po" file from
-transifex which needs to be translated into the PHP file friendica uses. To do
-so, place the file in the directory mentioned above and use the "po2php"
-utility from the util directory of your friendica installation.
+The translated strings come as a "message.po" file from transifex which needs to be translated into the PHP file friendica uses.
+To do so, place the file in the directory mentioned above and use the "po2php" utility from the util directory of your friendica installation.
-Assuming you want to convert the German localization which is placed in
-view/de/message.po you would do the following.
+Assuming you want to convert the German localization which is placed in view/de/message.po you would do the following.
1. Navigate at the command prompt to the base directory of your
friendica installation
@@ -47,15 +37,15 @@ view/de/message.po you would do the following.
2. Execute the po2php script, which will place the translation
in the strings.php file that is used by friendica.
- $> php util/po2php.php view/de/message.po
+ $> php util/po2php.php view/de/messages.po
The output of the script will be placed at view/de/strings.php where
- froemdoca os expecting it, so you can test your translation mmediately.
-
+ friendica is expecting it, so you can test your translation immediately.
+
3. Visit your friendica page to check if it still works in the language you
just translated. If not try to find the error, most likely PHP will give
you a hint in the log/warnings.about the error.
-
+
For debugging you can also try to "run" the file with PHP. This should
not give any output if the file is ok but might give a hint for
searching the bug in the file.
@@ -69,27 +59,10 @@ view/de/message.po you would do the following.
Utilities
---------
-Additional to the po2php script there are some more utilities for translation
-in the "util" directory of the friendica source tree. If you only want to
-translate friendica into another language you wont need any of these tools most
-likely but it gives you an idea how the translation process of friendica
-works.
+Additional to the po2php script there are some more utilities for translation in the "util" directory of the friendica source tree.
+If you only want to translate friendica into another language you wont need any of these tools most likely but it gives you an idea how the translation process of friendica works.
For further information see the utils/README file.
-Known Problems
---------------
-
-Friendica uses the language setting of the visitors browser to determain the
-language for the UI. Most of the time this works, but there are some known
-quirks.
-
-One is that some browsers, like Safari, do the setting to "de-de" but friendica
-only has a "de" localisation. A workaround would be to add a symbolic link
-from
- $friendica/view/de-de
-pointing to
- $friendica/view/de
-
[1]: https://www.transifex.com/projects/p/friendica/
diff --git a/friendica_test_data.sql b/friendica_test_data.sql
index c39a05765..45080e44d 100644
--- a/friendica_test_data.sql
+++ b/friendica_test_data.sql
@@ -1657,35 +1657,6 @@ LOCK TABLES `tokens` WRITE;
/*!40000 ALTER TABLE `tokens` ENABLE KEYS */;
UNLOCK TABLES;
---
--- Table structure for table `unique_contacts`
---
-
-DROP TABLE IF EXISTS `unique_contacts`;
-/*!40101 SET @saved_cs_client = @@character_set_client */;
-/*!40101 SET character_set_client = utf8 */;
-CREATE TABLE `unique_contacts` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `url` varchar(255) NOT NULL DEFAULT '',
- `nick` varchar(255) NOT NULL DEFAULT '',
- `name` varchar(255) NOT NULL DEFAULT '',
- `avatar` varchar(255) NOT NULL DEFAULT '',
- `location` varchar(255) NOT NULL DEFAULT '',
- `about` text NOT NULL,
- PRIMARY KEY (`id`),
- KEY `url` (`url`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-/*!40101 SET character_set_client = @saved_cs_client */;
-
---
--- Dumping data for table `unique_contacts`
---
-
-LOCK TABLES `unique_contacts` WRITE;
-/*!40000 ALTER TABLE `unique_contacts` DISABLE KEYS */;
-/*!40000 ALTER TABLE `unique_contacts` ENABLE KEYS */;
-UNLOCK TABLES;
-
--
-- Table structure for table `user`
--
diff --git a/htconfig.php b/htconfig.php
index 508de9a32..fe6c0d82e 100644
--- a/htconfig.php
+++ b/htconfig.php
@@ -57,7 +57,7 @@ $a->config['system']['huburl'] = '[internal]';
// allowed themes (change this from admin panel after installation)
-$a->config['system']['allowed_themes'] = 'dispy,quattro,vier,darkzero,duepuntozero,greenzero,purplezero,slackr,diabook';
+$a->config['system']['allowed_themes'] = 'quattro,vier,duepuntozero';
// default system theme
diff --git a/include/Contact.php b/include/Contact.php
index a3cbbfed1..3799e0b18 100644
--- a/include/Contact.php
+++ b/include/Contact.php
@@ -132,8 +132,8 @@ function terminate_friendship($user,$self,$contact) {
diaspora_unshare($user,$contact);
}
elseif($contact['network'] === NETWORK_DFRN) {
- require_once('include/items.php');
- dfrn_deliver($user,$contact,'placeholder', 1);
+ require_once('include/dfrn.php');
+ dfrn::deliver($user,$contact,'placeholder', 1);
}
}
@@ -205,60 +205,49 @@ function get_contact_details_by_url($url, $uid = -1) {
if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND
in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
proc_run('php',"include/update_gcontact.php", $profile["gid"]);
-
- } else {
- $r = q("SELECT `url`, `name`, `nick`, `avatar` AS `photo`, `location`, `about` FROM `unique_contacts` WHERE `url` = '%s'",
- dbesc(normalise_link($url)));
-
- if (count($r)) {
- $profile = $r[0];
- $profile["keywords"] = "";
- $profile["gender"] = "";
- $profile["community"] = false;
- $profile["network"] = "";
- $profile["addr"] = "";
- }
}
// Fetching further contact data from the contact table
- $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `network` = '%s'",
+ $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd`, `self` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `network` IN ('%s', '')",
dbesc(normalise_link($url)), intval($uid), dbesc($profile["network"]));
- if (!count($r))
- $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
+ if (!count($r) AND !isset($profile))
+ $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd`, `self` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
dbesc(normalise_link($url)), intval($uid));
- if (!count($r))
- $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
+ if (!count($r) AND !isset($profile))
+ $r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
dbesc(normalise_link($url)));
if ($r) {
- if (isset($r[0]["url"]) AND $r[0]["url"])
+ if (!isset($profile["url"]) AND $r[0]["url"])
$profile["url"] = $r[0]["url"];
- if (isset($r[0]["name"]) AND $r[0]["name"])
+ if (!isset($profile["name"]) AND $r[0]["name"])
$profile["name"] = $r[0]["name"];
- if (isset($r[0]["nick"]) AND $r[0]["nick"] AND ($profile["nick"] == ""))
+ if (!isset($profile["nick"]) AND $r[0]["nick"])
$profile["nick"] = $r[0]["nick"];
- if (isset($r[0]["addr"]) AND $r[0]["addr"] AND ($profile["addr"] == ""))
+ if (!isset($profile["addr"]) AND $r[0]["addr"])
$profile["addr"] = $r[0]["addr"];
- if (isset($r[0]["photo"]) AND $r[0]["photo"])
+ if ((!isset($profile["photo"]) OR $r[0]["self"]) AND $r[0]["photo"])
$profile["photo"] = $r[0]["photo"];
- if (isset($r[0]["location"]) AND $r[0]["location"])
+ if (!isset($profile["location"]) AND $r[0]["location"])
$profile["location"] = $r[0]["location"];
- if (isset($r[0]["about"]) AND $r[0]["about"])
+ if (!isset($profile["about"]) AND $r[0]["about"])
$profile["about"] = $r[0]["about"];
- if (isset($r[0]["keywords"]) AND $r[0]["keywords"])
+ if (!isset($profile["keywords"]) AND $r[0]["keywords"])
$profile["keywords"] = $r[0]["keywords"];
- if (isset($r[0]["gender"]) AND $r[0]["gender"])
+ if (!isset($profile["gender"]) AND $r[0]["gender"])
$profile["gender"] = $r[0]["gender"];
if (isset($r[0]["forum"]) OR isset($r[0]["prv"]))
$profile["community"] = ($r[0]["forum"] OR $r[0]["prv"]);
- if (isset($r[0]["network"]) AND $r[0]["network"])
+ if (!isset($profile["network"]) AND $r[0]["network"])
$profile["network"] = $r[0]["network"];
- if (isset($r[0]["addr"]) AND $r[0]["addr"])
+ if (!isset($profile["addr"]) AND $r[0]["addr"])
$profile["addr"] = $r[0]["addr"];
- if (isset($r[0]["bd"]) AND $r[0]["bd"])
+ if (!isset($profile["bd"]) AND $r[0]["bd"])
$profile["bd"] = $r[0]["bd"];
+ if (isset($r[0]["thumb"]))
+ $profile["thumb"] = $r[0]["thumb"];
if ($r[0]["uid"] == 0)
$profile["cid"] = 0;
else
@@ -415,6 +404,7 @@ function get_contact($url, $uid = 0) {
$contactid = 0;
// is it an address in the format user@server.tld?
+ /// @todo use gcontact and/or the addr field for a lookup
if (!strstr($url, "http") OR strstr($url, "@")) {
$data = probe_url($url);
$url = $data["url"];
@@ -422,12 +412,12 @@ function get_contact($url, $uid = 0) {
return 0;
}
- $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
+ $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
dbesc(normalise_link($url)),
intval($uid));
if (!$contact)
- $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d",
+ $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d ORDER BY `id` LIMIT 1",
dbesc($url),
dbesc(normalise_link($url)),
intval($uid));
@@ -451,9 +441,7 @@ function get_contact($url, $uid = 0) {
if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
return 0;
- // tempory programming. Can be deleted after 2015-02-07
- if (($data["alias"] == "") AND (normalise_link($data["url"]) != normalise_link($url)))
- $data["alias"] = normalise_link($url);
+ $url = $data["url"];
if ($contactid == 0) {
q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
@@ -482,7 +470,7 @@ function get_contact($url, $uid = 0) {
dbesc($data["poco"])
);
- $contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
+ $contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
dbesc(normalise_link($data["url"])),
intval($uid));
if (!$contact)
@@ -491,25 +479,217 @@ function get_contact($url, $uid = 0) {
$contactid = $contact[0]["id"];
}
+ if ((count($contact) > 1) AND ($uid == 0) AND ($contactid != 0) AND ($url != ""))
+ q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d",
+ dbesc(normalise_link($url)),
+ intval($contactid));
+
require_once("Photo.php");
- $photos = import_profile_photo($data["photo"],$uid,$contactid);
+ update_contact_avatar($data["photo"],$uid,$contactid);
- q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s',
- `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
- `name-date` = '%s', `uri-date` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
- dbesc($photos[0]),
- dbesc($photos[1]),
- dbesc($photos[2]),
+ q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
+ `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
dbesc($data["addr"]),
dbesc($data["alias"]),
dbesc($data["name"]),
dbesc($data["nick"]),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
- dbesc(datetime_convert()),
intval($contactid)
);
return $contactid;
}
+
+/**
+ * @brief Returns posts from a given gcontact
+ *
+ * @param App $a argv application class
+ * @param int $gcontact_id Global contact
+ *
+ * @return string posts in HTML
+ */
+function posts_from_gcontact($a, $gcontact_id) {
+
+ require_once('include/conversation.php');
+
+ // There are no posts with "uid = 0" with connector networks
+ // This speeds up the query a lot
+ $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
+ if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
+ $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND `item`.`private`))";
+ else
+ $sql = "`item`.`uid` = %d";
+
+ if(get_config('system', 'old_pager')) {
+ $r = q("SELECT COUNT(*) AS `total` FROM `item`
+ WHERE `gcontact-id` = %d and $sql",
+ intval($gcontact_id),
+ intval(local_user()));
+
+ $a->set_pager_total($r[0]['total']);
+ }
+
+ $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
+ `author-name` AS `name`, `owner-avatar` AS `photo`,
+ `owner-link` AS `url`, `owner-avatar` AS `thumb`
+ FROM `item` FORCE INDEX (`gcontactid_uid_created`)
+ WHERE `gcontact-id` = %d AND $sql AND
+ NOT `deleted` AND NOT `moderated` AND `visible`
+ ORDER BY `item`.`created` DESC LIMIT %d, %d",
+ intval($gcontact_id),
+ intval(local_user()),
+ intval($a->pager['start']),
+ intval($a->pager['itemspage'])
+ );
+
+ $o = conversation($a,$r,'community',false);
+
+ if(!get_config('system', 'old_pager')) {
+ $o .= alt_pager($a,count($r));
+ } else {
+ $o .= paginate($a);
+ }
+
+ 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
+ *
+ * @param App $a argv application class
+ * @param int $contact_id contact
+ *
+ * @return string posts in HTML
+ */
+function posts_from_contact($a, $contact_id) {
+
+ require_once('include/conversation.php');
+
+ $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
+ if (!$r)
+ return false;
+
+ $contact = $r[0];
+
+ if(get_config('system', 'old_pager')) {
+ $r = q("SELECT COUNT(*) AS `total` FROM `item`
+ WHERE `item`.`uid` = %d AND `author-link` IN ('%s', '%s')",
+ intval(local_user()),
+ dbesc(str_replace("https://", "http://", $contact["url"])),
+ dbesc(str_replace("http://", "https://", $contact["url"])));
+
+ $a->set_pager_total($r[0]['total']);
+ }
+
+ $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
+ `author-name` AS `name`, `owner-avatar` AS `photo`,
+ `owner-link` AS `url`, `owner-avatar` AS `thumb`
+ FROM `item` FORCE INDEX (`uid_contactid_created`)
+ WHERE `item`.`uid` = %d AND `contact-id` = %d
+ AND `author-link` IN ('%s', '%s')
+ AND NOT `deleted` AND NOT `moderated` AND `visible`
+ ORDER BY `item`.`created` DESC LIMIT %d, %d",
+ intval(local_user()),
+ intval($contact_id),
+ dbesc(str_replace("https://", "http://", $contact["url"])),
+ dbesc(str_replace("http://", "https://", $contact["url"])),
+ intval($a->pager['start']),
+ intval($a->pager['itemspage'])
+ );
+
+ $o .= conversation($a,$r,'community',false);
+
+ if(!get_config('system', 'old_pager'))
+ $o .= alt_pager($a,count($r));
+ else
+ $o .= paginate($a);
+
+ return $o;
+}
+
+/**
+ * @brief Returns a formatted location string from the given profile array
+ *
+ * @param array $profile Profile array (Generated from the "profile" table)
+ *
+ * @return string Location string
+ */
+function formatted_location($profile) {
+ $location = '';
+
+ if($profile['locality'])
+ $location .= $profile['locality'];
+
+ if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
+ if($location)
+ $location .= ', ';
+
+ $location .= $profile['region'];
+ }
+
+ if($profile['country-name']) {
+ if($location)
+ $location .= ', ';
+
+ $location .= $profile['country-name'];
+ }
+
+ return $location;
+}
+?>
diff --git a/include/ForumManager.php b/include/ForumManager.php
new file mode 100644
index 000000000..49417d183
--- /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' => z_root() . '/network?f=&cid=' . $contact['id'],
+ 'external_url' => z_root() . '/redir/' . $contact['id'],
+ 'name' => $contact['name'],
+ 'cid' => $contact['id'],
+ 'selected' => $selected,
+ 'micro' => 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;
+ }
+
+}
\ No newline at end of file
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 30424747d..91fce55a8 100644
--- a/include/Photo.php
+++ b/include/Photo.php
@@ -720,65 +720,101 @@ function guess_image_type($filename, $fromcurl=false) {
}
-function import_profile_photo($photo,$uid,$cid) {
+/**
+ * @brief Updates the avatar links in a contact only if needed
+ *
+ * @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, $force = false) {
- $a = get_app();
+ $r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
+ if (!$r)
+ return false;
+ else
+ $data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
- $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
- intval($uid),
- intval($cid)
- );
- if(count($r) && strlen($r[0]['resource-id'])) {
- $hash = $r[0]['resource-id'];
- }
- else {
- $hash = photo_new_resource();
- }
+ if (($r[0]["avatar"] != $avatar) OR $force) {
+ $photos = import_profile_photo($avatar,$uid,$cid, true);
- $photo_failure = false;
+ if ($photos) {
+ q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
+ dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
+ dbesc(datetime_convert()), intval($cid));
+ return $photos;
+ }
+ }
- $filename = basename($photo);
- $img_str = fetch_url($photo,true);
+ return $data;
+}
- $type = guess_image_type($photo,true);
- $img = new Photo($img_str, $type);
- if($img->is_valid()) {
+function import_profile_photo($photo,$uid,$cid, $quit_on_error = false) {
- $img->scaleImageSquare(175);
+ $a = get_app();
- $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
+ $r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
+ intval($uid),
+ intval($cid)
+ );
+ if(count($r) && strlen($r[0]['resource-id'])) {
+ $hash = $r[0]['resource-id'];
+ } else {
+ $hash = photo_new_resource();
+ }
- if($r === false)
- $photo_failure = true;
+ $photo_failure = false;
- $img->scaleImage(80);
+ $filename = basename($photo);
+ $img_str = fetch_url($photo,true);
- $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
+ if ($quit_on_error AND ($img_str == ""))
+ return false;
- if($r === false)
- $photo_failure = true;
+ $type = guess_image_type($photo,true);
+ $img = new Photo($img_str, $type);
+ if($img->is_valid()) {
- $img->scaleImage(48);
+ $img->scaleImageSquare(175);
- $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
+ $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
- if($r === false)
- $photo_failure = true;
+ if($r === false)
+ $photo_failure = true;
- $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
- $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
- $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
- }
- else
- $photo_failure = true;
+ $img->scaleImage(80);
- if($photo_failure) {
- $photo = $a->get_baseurl() . '/images/person-175.jpg';
- $thumb = $a->get_baseurl() . '/images/person-80.jpg';
- $micro = $a->get_baseurl() . '/images/person-48.jpg';
- }
+ $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
- return(array($photo,$thumb,$micro));
+ if($r === false)
+ $photo_failure = true;
+
+ $img->scaleImage(48);
+
+ $r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
+
+ if($r === false)
+ $photo_failure = true;
+
+ $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
+ $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
+ $micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
+ } else
+ $photo_failure = true;
+
+ if($photo_failure AND $quit_on_error)
+ return false;
+
+ if($photo_failure) {
+ $photo = $a->get_baseurl() . '/images/person-175.jpg';
+ $thumb = $a->get_baseurl() . '/images/person-80.jpg';
+ $micro = $a->get_baseurl() . '/images/person-48.jpg';
+ }
+
+ return(array($photo,$thumb,$micro));
}
@@ -792,15 +828,19 @@ function get_photo_info($url) {
$filesize = strlen($img_str);
- $tempfile = tempnam(get_temppath(), "cache");
+ if (function_exists("getimagesizefromstring"))
+ $data = getimagesizefromstring($img_str);
+ else {
+ $tempfile = tempnam(get_temppath(), "cache");
- $a = get_app();
- $stamp1 = microtime(true);
- file_put_contents($tempfile, $img_str);
- $a->save_timestamp($stamp1, "file");
+ $a = get_app();
+ $stamp1 = microtime(true);
+ file_put_contents($tempfile, $img_str);
+ $a->save_timestamp($stamp1, "file");
- $data = getimagesize($tempfile);
- unlink($tempfile);
+ $data = getimagesize($tempfile);
+ unlink($tempfile);
+ }
if ($data)
$data["size"] = $filesize;
diff --git a/include/Scrape.php b/include/Scrape.php
index cb192c77c..ca6489b16 100644
--- a/include/Scrape.php
+++ b/include/Scrape.php
@@ -235,7 +235,9 @@ function scrape_feed($url) {
$a = get_app();
$ret = array();
- $s = fetch_url($url);
+ $cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
+ $s = fetch_url($url, false, $redirects, 0, Null, $cookiejar);
+ unlink($cookiejar);
$headers = $a->get_curl_headers();
$code = $a->get_curl_code();
@@ -559,10 +561,11 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$pubkey = $hcard_key;
}
}
-
if($diaspora && $diaspora_base && $diaspora_guid) {
- if($mode == PROBE_DIASPORA || ! $notify) {
- $notify = $diaspora_base . 'receive/users/' . $diaspora_guid;
+ $diaspora_notify = $diaspora_base.'receive/users/'.$diaspora_guid;
+
+ if($mode == PROBE_DIASPORA || ! $notify || ($notify == $diaspora_notify)) {
+ $notify = $diaspora_notify;
$batch = $diaspora_base . 'receive/public' ;
}
if(strpos($url,'@'))
@@ -661,7 +664,9 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$vcard['photo'] = $feedret['photo'];
require_once('library/simplepie/simplepie.inc');
$feed = new SimplePie();
- $xml = fetch_url($poll);
+ $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();
diff --git a/include/acl_selectors.php b/include/acl_selectors.php
index 4ef3d05ea..69181b735 100644
--- a/include/acl_selectors.php
+++ b/include/acl_selectors.php
@@ -20,7 +20,7 @@ function group_select($selname,$selclass,$preselected = false,$size = 4) {
$o .= "';
return $o;
-}}
+}
-// return a select using 'field_select_raw' template, with timezones
-// groupped (primarily) by continent
-// arguments follow convetion as other field_* template array:
-// 'name', 'label', $value, 'help'
-if (!function_exists('field_timezone')){
+
+
+/**
+ * @brief Generating a Timezone selector
+ *
+ * Return a select using 'field_select_raw' template, with timezones
+ * groupped (primarily) by continent
+ * arguments follow convetion as other field_* template array:
+ * 'name', 'label', $value, 'help'
+ *
+ * @param string $name Name of the selector
+ * @param string $label Label for the selector
+ * @param string $current Timezone
+ * @param string $help Help text
+ *
+ * @return string Parsed HTML
+ */
function field_timezone($name='timezone', $label='', $current = 'America/Los_Angeles', $help){
$options = select_timezone($current);
$options = str_replace('
' . "\r\n";
- if (strpos($ev['location'], "[map")===False) {
+ if (strpos($ev['location'], "[map") !== False) {
$map = generate_named_map($ev['location']);
if ($map!==$ev['location']) $o.=$map;
}
@@ -76,7 +76,6 @@ function format_event_html($ev, $simple = false) {
function parse_event($h) {
require_once('include/Scrape.php');
- require_once('library/HTMLPurifier.auto.php');
require_once('include/html2bbcode');
$h = '' . $h . '';
diff --git a/include/expire.php b/include/expire.php
index 308680421..873c594e8 100644
--- a/include/expire.php
+++ b/include/expire.php
@@ -18,7 +18,6 @@ function expire_run(&$argv, &$argc){
require_once('include/session.php');
require_once('include/datetime.php');
- require_once('library/simplepie/simplepie.inc');
require_once('include/items.php');
require_once('include/Contact.php');
diff --git a/include/features.php b/include/features.php
index 263960457..87a9b46d5 100644
--- a/include/features.php
+++ b/include/features.php
@@ -1,23 +1,25 @@
$uid, 'feature' => $feature, 'enabled' => $x);
call_hooks('feature_enabled',$arr);
@@ -42,14 +44,17 @@ function get_feature_default($feature) {
}
/**
- * @ brief get a list of all available features
+ * @brief Get a list of all available features
+ *
* The array includes the setting group, the setting name,
* explainations for the setting and if it's enabled or disabled
* by default
*
+ * @param bool $filtered True removes any locked features
+ *
* @return array
*/
-function get_features() {
+function get_features($filtered = true) {
$arr = array(
@@ -57,56 +62,78 @@ function get_features() {
'general' => array(
t('General Features'),
//array('expire', t('Content Expiration'), t('Remove old posts/comments after a period of time')),
- array('multi_profiles', t('Multiple Profiles'), t('Ability to create multiple profiles'),false),
- array('photo_location', t('Photo Location'), t('Photo metadata is normally stripped. This extracts the location (if present) prior to stripping metadata and links it to a map.'),false),
+ array('multi_profiles', t('Multiple Profiles'), t('Ability to create multiple profiles'), false, get_config('feature_lock','multi_profiles')),
+ array('photo_location', t('Photo Location'), t('Photo metadata is normally stripped. This extracts the location (if present) prior to stripping metadata and links it to a map.'), false, get_config('feature_lock','photo_location')),
),
// Post composition
'composition' => array(
t('Post Composition Features'),
- array('richtext', t('Richtext Editor'), t('Enable richtext editor'),false),
- array('preview', t('Post Preview'), t('Allow previewing posts and comments before publishing them'),false),
- array('aclautomention', t('Auto-mention Forums'), t('Add/remove mention when a fourm page is selected/deselected in ACL window.'),false),
+ array('richtext', t('Richtext Editor'), t('Enable richtext editor'), false, get_config('feature_lock','richtext')),
+ array('preview', t('Post Preview'), t('Allow previewing posts and comments before publishing them'), false, get_config('feature_lock','preview')),
+ array('aclautomention', t('Auto-mention Forums'), t('Add/remove mention when a fourm page is selected/deselected in ACL window.'), false, get_config('feature_lock','aclautomention')),
),
// Network sidebar widgets
'widgets' => array(
t('Network Sidebar Widgets'),
- array('archives', t('Search by Date'), t('Ability to select posts by date ranges'),false),
- array('forumlist_widget', t('List Forums'), t('Enable widget to display the forums your are connected with'),true),
- array('groups', t('Group Filter'), t('Enable widget to display Network posts only from selected group'),false),
- array('networks', t('Network Filter'), t('Enable widget to display Network posts only from selected network'),false),
- array('savedsearch', t('Saved Searches'), t('Save search terms for re-use'),false),
+ array('archives', t('Search by Date'), t('Ability to select posts by date ranges'), false, get_config('feature_lock','archives')),
+ array('forumlist_widget', t('List Forums'), t('Enable widget to display the forums your are connected with'), true, get_config('feature_lock','forumlist_widget')),
+ array('groups', t('Group Filter'), t('Enable widget to display Network posts only from selected group'), false, get_config('feature_lock','groups')),
+ array('networks', t('Network Filter'), t('Enable widget to display Network posts only from selected network'), false, get_config('feature_lock','networks')),
+ array('savedsearch', t('Saved Searches'), t('Save search terms for re-use'), false, get_config('feature_lock','savedsearch')),
),
// Network tabs
'net_tabs' => array(
t('Network Tabs'),
- array('personal_tab', t('Network Personal Tab'), t('Enable tab to display only Network posts that you\'ve interacted on'),false),
- array('new_tab', t('Network New Tab'), t('Enable tab to display only new Network posts (from the last 12 hours)'),false),
- array('link_tab', t('Network Shared Links Tab'), t('Enable tab to display only Network posts with links in them'),false),
+ array('personal_tab', t('Network Personal Tab'), t('Enable tab to display only Network posts that you\'ve interacted on'), false, get_config('feature_lock','personal_tab')),
+ array('new_tab', t('Network New Tab'), t('Enable tab to display only new Network posts (from the last 12 hours)'), false, get_config('feature_lock','new_tab')),
+ array('link_tab', t('Network Shared Links Tab'), t('Enable tab to display only Network posts with links in them'), false, get_config('feature_lock','link_tab')),
),
// Item tools
'tools' => array(
t('Post/Comment Tools'),
- array('multi_delete', t('Multiple Deletion'), t('Select and delete multiple posts/comments at once'),false),
- array('edit_posts', t('Edit Sent Posts'), t('Edit and correct posts and comments after sending'),false),
- array('commtag', t('Tagging'), t('Ability to tag existing posts'),false),
- array('categories', t('Post Categories'), t('Add categories to your posts'),false),
- array('filing', t('Saved Folders'), t('Ability to file posts under folders'),false),
- array('dislike', t('Dislike Posts'), t('Ability to dislike posts/comments')),
- array('star_posts', t('Star Posts'), t('Ability to mark special posts with a star indicator'),false),
- array('ignore_posts', t('Mute Post Notifications'), t('Ability to mute notifications for a thread'),false),
+ array('multi_delete', t('Multiple Deletion'), t('Select and delete multiple posts/comments at once'), false, get_config('feature_lock','multi_delete')),
+ array('edit_posts', t('Edit Sent Posts'), t('Edit and correct posts and comments after sending'), false, get_config('feature_lock','edit_posts')),
+ array('commtag', t('Tagging'), t('Ability to tag existing posts'), false, get_config('feature_lock','commtag')),
+ array('categories', t('Post Categories'), t('Add categories to your posts'), false, get_config('feature_lock','categories')),
+ array('filing', t('Saved Folders'), t('Ability to file posts under folders'), false, get_config('feature_lock','filing')),
+ array('dislike', t('Dislike Posts'), t('Ability to dislike posts/comments'), false, get_config('feature_lock','dislike')),
+ array('star_posts', t('Star Posts'), t('Ability to mark special posts with a star indicator'), false, get_config('feature_lock','star_posts')),
+ array('ignore_posts', t('Mute Post Notifications'), t('Ability to mute notifications for a thread'), false, get_config('feature_lock','ignore_posts')),
),
// Advanced Profile Settings
'advanced_profile' => array(
t('Advanced Profile Settings'),
- array('forumlist_profile', t('List Forums'), t('Show visitors public community forums at the Advanced Profile Page'),false),
+ array('forumlist_profile', t('List Forums'), t('Show visitors public community forums at the Advanced Profile Page'), false, get_config('feature_lock','forumlist_profile')),
),
);
+ // removed any locked features and remove the entire category if this makes it empty
+
+ if($filtered) {
+ foreach($arr as $k => $x) {
+ $has_items = false;
+ $kquantity = count($arr[$k]);
+ for($y = 0; $y < $kquantity; $y ++) {
+ if(is_array($arr[$k][$y])) {
+ if($arr[$k][$y][4] === false) {
+ $has_items = true;
+ }
+ else {
+ unset($arr[$k][$y]);
+ }
+ }
+ }
+ if(! $has_items) {
+ unset($arr[$k]);
+ }
+ }
+ }
+
call_hooks('get_features',$arr);
return $arr;
}
diff --git a/include/follow.php b/include/follow.php
index 21c05c8f3..22ff079b6 100644
--- a/include/follow.php
+++ b/include/follow.php
@@ -264,24 +264,8 @@ function new_contact($uid,$url,$interactive = false) {
require_once("include/Photo.php");
- $photos = import_profile_photo($ret['photo'],$uid,$contact_id);
-
- $r = q("UPDATE `contact` SET `photo` = '%s',
- `thumb` = '%s',
- `micro` = '%s',
- `name-date` = '%s',
- `uri-date` = '%s',
- `avatar-date` = '%s'
- WHERE `id` = %d",
- dbesc($photos[0]),
- dbesc($photos[1]),
- dbesc($photos[2]),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
- intval($contact_id)
- );
-
+ // Update the avatar
+ update_contact_avatar($ret['photo'],$uid,$contact_id);
// pull feed and consume it, which should subscribe to the hub.
diff --git a/include/forums.php b/include/forums.php
deleted file mode 100644
index 995a29cad..000000000
--- a/include/forums.php
+++ /dev/null
@@ -1,182 +0,0 @@
- forum url
- * 'name' => forum name
- * 'id' => number of the key from the array
- * 'micro' => contact photo in format micro
- */
-function get_forumlist($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)
- );
-
- 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
- * @param int $cid
- * The contact id which is used to mark a forum as "selected"
- * @return string
- */
-function widget_forumlist($uid,$cid = 0) {
-
- if(! intval(feature_enabled(local_user(),'forumlist_widget')))
- return;
-
- $o = '';
-
- //sort by last updated item
- $lastitem = true;
-
- $contacts = get_forumlist($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' => z_root() . '/network?f=&cid=' . $contact['id'],
- 'external_url' => z_root() . '/redir/' . $contact['id'],
- 'name' => $contact['name'],
- 'cid' => $contact['id'],
- 'selected' => $selected,
- 'micro' => 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
- * @return string
- *
- */
-function forumlist_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 = get_forumlist($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
- *
- */
-
-function forums_count_unseen() {
- $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/friendica_smarty.php b/include/friendica_smarty.php
index 99dc12bf8..9ba2d2a74 100644
--- a/include/friendica_smarty.php
+++ b/include/friendica_smarty.php
@@ -60,6 +60,8 @@ class FriendicaSmartyEngine implements ITemplateEngine {
$template = $s;
$s = new FriendicaSmarty();
}
+
+ $r['$APP'] = get_app();
// "middleware": inject variables into templates
$arr = array(
diff --git a/include/gprobe.php b/include/gprobe.php
index 84292f263..dfa9137d7 100644
--- a/include/gprobe.php
+++ b/include/gprobe.php
@@ -33,7 +33,7 @@ function gprobe_run(&$argv, &$argc){
$url = hex2bin($argv[1]);
- $r = q("select * from gcontact where nurl = '%s' limit 1",
+ $r = q("SELECT `id`, `url`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 1",
dbesc(normalise_link($url))
);
@@ -58,21 +58,16 @@ function gprobe_run(&$argv, &$argc){
if (is_null($result))
Cache::set("gprobe:".$urlparts["host"],serialize($arr));
- if(count($arr) && x($arr,'network') && $arr['network'] === NETWORK_DFRN) {
- q("insert into `gcontact` (`name`,`url`,`nurl`,`photo`)
- values ( '%s', '%s', '%s', '%s') ",
- dbesc($arr['name']),
- dbesc($arr['url']),
- dbesc(normalise_link($arr['url'])),
- dbesc($arr['photo'])
- );
- }
- $r = q("select * from gcontact where nurl = '%s' limit 1",
+ if (!in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))
+ update_gcontact($arr);
+
+ $r = q("SELECT `id`, `url`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 1",
dbesc(normalise_link($url))
);
}
if(count($r))
- poco_load(0,0,$r[0]['id'], str_replace('/profile/','/poco/',$r[0]['url']));
+ if ($r[0]["network"] == NETWORK_DFRN)
+ poco_load(0,0,$r[0]['id'], str_replace('/profile/','/poco/',$r[0]['url']));
logger("gprobe end for ".normalise_link($url), LOGGER_DEBUG);
return;
diff --git a/include/group.php b/include/group.php
index fd1c97dfd..2b872f16a 100644
--- a/include/group.php
+++ b/include/group.php
@@ -215,7 +215,7 @@ function mini_group_select($uid,$gid = 0) {
/**
* @brief Create group sidebar widget
- *
+ *
* @param string $every
* @param string $each
* @param string $editmode
@@ -234,7 +234,7 @@ function group_side($every="contacts",$each="group",$editmode = "standard", $gro
return '';
$groups = array();
-
+
$groups[] = array(
'text' => t('Everybody'),
'id' => 0,
@@ -255,7 +255,7 @@ function group_side($every="contacts",$each="group",$editmode = "standard", $gro
if(count($r)) {
foreach($r as $rr) {
$selected = (($group_id == $rr['id']) ? ' group-selected' : '');
-
+
if ($editmode == "full") {
$groupedit = array(
'href' => "group/".$rr['id'],
@@ -264,7 +264,7 @@ function group_side($every="contacts",$each="group",$editmode = "standard", $gro
} else {
$groupedit = null;
}
-
+
$groups[] = array(
'id' => $rr['id'],
'cid' => $cid,
@@ -297,17 +297,26 @@ function group_side($every="contacts",$each="group",$editmode = "standard", $gro
return $o;
}
-function expand_groups($a,$check_dead = false) {
+function expand_groups($a,$check_dead = false, $use_gcontact = false) {
if(! (is_array($a) && count($a)))
return array();
$groups = implode(',', $a);
$groups = dbesc($groups);
- $r = q("SELECT `contact-id` FROM `group_member` WHERE `gid` IN ( $groups )");
+
+ if ($use_gcontact)
+ $r = q("SELECT `gcontact`.`id` AS `contact-id` FROM `group_member`
+ INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
+ INNER JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
+ WHERE `gid` IN ($groups)");
+ else
+ $r = q("SELECT `contact-id` FROM `group_member` WHERE `gid` IN ( $groups )");
+
+
$ret = array();
if(count($r))
foreach($r as $rr)
$ret[] = $rr['contact-id'];
- if($check_dead) {
+ if($check_dead AND !$use_gcontact) {
require_once('include/acl_selectors.php');
$ret = prune_deadguys($ret);
}
@@ -353,17 +362,16 @@ function groups_containing($uid,$c) {
*/
function groups_count_unseen() {
- $r = q("SELECT `group`.`id`, `group`.`name`, COUNT(`item`.`id`) AS `count` FROM `group`, `group_member`, `item`
- WHERE `group`.`uid` = %d
- AND `item`.`uid` = %d
- AND `item`.`unseen` AND `item`.`visible`
- AND NOT `item`.`deleted`
- AND `item`.`contact-id` = `group_member`.`contact-id`
- AND `group_member`.`gid` = `group`.`id`
- GROUP BY `group`.`id` ",
+ $r = q("SELECT `group`.`id`, `group`.`name`,
+ (SELECT COUNT(*) FROM `item`
+ WHERE `uid` = %d AND `unseen` AND
+ `contact-id` IN (SELECT `contact-id` FROM `group_member`
+ WHERE `group_member`.`gid` = `group`.`id` AND `group_member`.`uid` = %d)) AS `count`
+ FROM `group` WHERE `group`.`uid` = %d;",
+ intval(local_user()),
intval(local_user()),
intval(local_user())
);
return $r;
-}
\ No newline at end of file
+}
diff --git a/include/identity.php b/include/identity.php
index fb405b90f..ec66225d0 100644
--- a/include/identity.php
+++ b/include/identity.php
@@ -3,7 +3,7 @@
* @file include/identity.php
*/
-require_once('include/forums.php');
+require_once('include/ForumManager.php');
require_once('include/bbcode.php');
require_once("mod/proxy.php");
@@ -300,6 +300,7 @@ function profile_sidebar($profile, $block = 0) {
$account_type = "";
if((x($profile,'address') == 1)
+ || (x($profile,'location') == 1)
|| (x($profile,'locality') == 1)
|| (x($profile,'region') == 1)
|| (x($profile,'postal-code') == 1)
@@ -368,6 +369,8 @@ function profile_sidebar($profile, $block = 0) {
if (isset($p["address"]))
$p["address"] = bbcode($p["address"]);
+ else
+ $p["address"] = bbcode($p["location"]);
if (isset($p["photo"]))
$p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
@@ -652,7 +655,7 @@ function advanced_profile(&$a) {
//show subcribed forum if it is enabled in the usersettings
if (feature_enabled($uid,'forumlist_profile')) {
- $profile['forumlist'] = array( t('Forums:'), forumlist_profile_advanced($uid));
+ $profile['forumlist'] = array( t('Forums:'), ForumManager::profile_advanced($uid));
}
if ($a->profile['uid'] == local_user())
diff --git a/include/items.php b/include/items.php
index c9e13b1a1..1af6fe1b5 100644
--- a/include/items.php
+++ b/include/items.php
@@ -14,314 +14,19 @@ require_once('include/socgraph.php');
require_once('include/plaintext.php');
require_once('include/ostatus.php');
require_once('include/feed.php');
+require_once('include/Contact.php');
require_once('mod/share.php');
+require_once('include/enotify.php');
+require_once('include/dfrn.php');
require_once('library/defuse/php-encryption-1.2.1/Crypto.php');
-
-function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0, $forpubsub = false) {
-
-
- $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
- $public_feed = (($dfrn_id) ? false : true);
- $starred = false; // not yet implemented, possible security issues
- $converse = false;
-
- if($public_feed && $a->argc > 2) {
- for($x = 2; $x < $a->argc; $x++) {
- if($a->argv[$x] == 'converse')
- $converse = true;
- if($a->argv[$x] == 'starred')
- $starred = true;
- if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
- $category = $a->argv[$x+1];
- }
- }
-
-
-
- // default permissions - anonymous user
-
- $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
-
- $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
- FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
- WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
- dbesc($owner_nick)
- );
-
- if(! count($r))
- killme();
-
- $owner = $r[0];
- $owner_id = $owner['user_uid'];
- $owner_nick = $owner['nickname'];
-
- $birthday = feed_birthday($owner_id,$owner['timezone']);
-
- $sql_post_table = "";
- $visibility = "";
-
- if(! $public_feed) {
-
- $sql_extra = '';
- switch($direction) {
- case (-1):
- $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
- $my_id = $dfrn_id;
- break;
- case 0:
- $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
- $my_id = '1:' . $dfrn_id;
- break;
- case 1:
- $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
- $my_id = '0:' . $dfrn_id;
- break;
- default:
- return false;
- break; // NOTREACHED
- }
-
- $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
- intval($owner_id)
- );
-
- if(! count($r))
- killme();
-
- $contact = $r[0];
- require_once('include/security.php');
- $groups = init_groups_visitor($contact['id']);
-
- if(count($groups)) {
- for($x = 0; $x < count($groups); $x ++)
- $groups[$x] = '<' . intval($groups[$x]) . '>' ;
- $gs = implode('|', $groups);
- }
- else
- $gs = '<<>>' ; // Impossible to match
-
- $sql_extra = sprintf("
- AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
- AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
- AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
- AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
- ",
- intval($contact['id']),
- intval($contact['id']),
- dbesc($gs),
- dbesc($gs)
- );
- }
-
- if($public_feed)
- $sort = 'DESC';
- else
- $sort = 'ASC';
-
- // Include answers to status.net posts in pubsub feeds
- if($forpubsub) {
- $sql_post_table = "INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`
- LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`";
- $visibility = sprintf("AND (`item`.`parent` = `item`.`id`) OR (`item`.`network` = '%s' AND ((`thread`.`network`='%s') OR (`thritem`.`network` = '%s')))",
- dbesc(NETWORK_DFRN), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS));
- $date_field = "`received`";
- $sql_order = "`item`.`received` DESC";
- } else {
- $date_field = "`changed`";
- $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
- }
-
- if(! strlen($last_update))
- $last_update = 'now -30 days';
-
- if(isset($category)) {
- $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
- dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
- //$sql_extra .= file_tag_file_query('item',$category,'category');
- }
-
- if($public_feed) {
- if(! $converse)
- $sql_extra .= " AND `contact`.`self` = 1 ";
- }
-
- $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
-
- // AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
- // dbesc($check_date),
-
- $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`,
- `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
- `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
- `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
- `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
- `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
- FROM `item` $sql_post_table
- INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
- AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
- LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
- WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
- AND ((`item`.`wall` = 1) $visibility) AND `item`.$date_field > '%s'
- $sql_extra
- ORDER BY $sql_order LIMIT 0, 300",
- intval($owner_id),
- dbesc($check_date),
- dbesc($sort)
- );
-
- // Will check further below if this actually returned results.
- // We will provide an empty feed if that is the case.
-
- $items = $r;
-
- $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
-
- $atom = '';
-
- $hubxml = feed_hublinks();
-
- $salmon = feed_salmonlinks($owner_nick);
-
- $alternatelink = $owner['url'];
-
- if(isset($category))
- $alternatelink .= "/category/".$category;
-
- $atom .= replace_macros($feed_template, array(
- '$version' => xmlify(FRIENDICA_VERSION),
- '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
- '$feed_title' => xmlify($owner['name']),
- '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
- '$hub' => $hubxml,
- '$salmon' => $salmon,
- '$alternatelink' => xmlify($alternatelink),
- '$name' => xmlify($owner['name']),
- '$profile_page' => xmlify($owner['url']),
- '$photo' => xmlify($owner['photo']),
- '$thumb' => xmlify($owner['thumb']),
- '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
- '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
- '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
- '$birthday' => ((strlen($birthday)) ? '' . xmlify($birthday) . '' : ''),
- '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '1' : '')
- ));
-
- call_hooks('atom_feed', $atom);
-
- if(! count($items)) {
-
- call_hooks('atom_feed_end', $atom);
-
- $atom .= '' . "\r\n";
- return $atom;
- }
-
- foreach($items as $item) {
-
- // prevent private email from leaking.
- if($item['network'] === NETWORK_MAIL)
- continue;
-
- // public feeds get html, our own nodes use bbcode
-
- if($public_feed) {
- $type = 'html';
- // catch any email that's in a public conversation and make sure it doesn't leak
- if($item['private'])
- continue;
- }
- else {
- $type = 'text';
- }
-
- $atom .= atom_entry($item,$type,null,$owner,true);
- }
-
- call_hooks('atom_feed_end', $atom);
-
- $atom .= '' . "\r\n";
-
- return $atom;
-}
-
-
function construct_verb($item) {
if($item['verb'])
return $item['verb'];
return ACTIVITY_POST;
}
-function construct_activity_object($item) {
-
- if($item['object']) {
- $o = '' . "\r\n";
- $r = parse_xml_string($item['object'],false);
-
-
- if(! $r)
- return '';
- if($r->type)
- $o .= '' . xmlify($r->type) . '' . "\r\n";
- if($r->id)
- $o .= '' . xmlify($r->id) . '' . "\r\n";
- if($r->title)
- $o .= '' . xmlify($r->title) . '' . "\r\n";
- if($r->link) {
- if(substr($r->link,0,1) === '<') {
- // patch up some facebook "like" activity objects that got stored incorrectly
- // for a couple of months prior to 9-Jun-2011 and generated bad XML.
- // we can probably remove this hack here and in the following function in a few months time.
- if(strstr($r->link,'&') && (! strstr($r->link,'&')))
- $r->link = str_replace('&','&', $r->link);
- $r->link = preg_replace('/\/','',$r->link);
- $o .= $r->link;
- }
- else
- $o .= '' . "\r\n";
- }
- if($r->content)
- $o .= '' . xmlify(bbcode($r->content)) . '' . "\r\n";
- $o .= '' . "\r\n";
- return $o;
- }
-
- return '';
-}
-
-function construct_activity_target($item) {
-
- if($item['target']) {
- $o = '' . "\r\n";
- $r = parse_xml_string($item['target'],false);
- if(! $r)
- return '';
- if($r->type)
- $o .= '' . xmlify($r->type) . '' . "\r\n";
- if($r->id)
- $o .= '' . xmlify($r->id) . '' . "\r\n";
- if($r->title)
- $o .= '' . xmlify($r->title) . '' . "\r\n";
- if($r->link) {
- if(substr($r->link,0,1) === '<') {
- if(strstr($r->link,'&') && (! strstr($r->link,'&')))
- $r->link = str_replace('&','&', $r->link);
- $r->link = preg_replace('/\/','',$r->link);
- $o .= $r->link;
- }
- else
- $o .= '' . "\r\n";
- }
- if($r->content)
- $o .= '' . xmlify(bbcode($r->content)) . '' . "\r\n";
- $o .= '' . "\r\n";
- return $o;
- }
-
- return '';
-}
-
/* limit_body_size()
*
* The purpose of this function is to apply system message length limits to
@@ -440,482 +145,6 @@ function title_is_body($title, $body) {
return($title == $body);
}
-
-
-function get_atom_elements($feed, $item, $contact = array()) {
-
- require_once('library/HTMLPurifier.auto.php');
- require_once('include/html2bbcode.php');
-
- $best_photo = array();
-
- $res = array();
-
- $author = $item->get_author();
- if($author) {
- $res['author-name'] = unxmlify($author->get_name());
- $res['author-link'] = unxmlify($author->get_link());
- }
- else {
- $res['author-name'] = unxmlify($feed->get_title());
- $res['author-link'] = unxmlify($feed->get_permalink());
- }
- $res['uri'] = unxmlify($item->get_id());
- $res['title'] = unxmlify($item->get_title());
- $res['body'] = unxmlify($item->get_content());
- $res['plink'] = unxmlify($item->get_link(0));
-
- if (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND strstr($res['plink'], ".app.net/")) {
- logger("get_atom_elements: detected app.net posting: ".print_r($res, true), LOGGER_DEBUG);
- $res['title'] = "";
- $res['body'] = nl2br($res['body']);
- }
-
- // removing the content of the title if its identically to the body
- // This helps with auto generated titles e.g. from tumblr
- if (title_is_body($res["title"], $res["body"]))
- $res['title'] = "";
-
- if($res['plink'])
- $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
- else
- $base_url = '';
-
- // look for a photo. We should check media size and find the best one,
- // but for now let's just find any author photo
- // Additionally we look for an alternate author link. On OStatus this one is the one we want.
-
- $authorlinks = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"]["http://www.w3.org/2005/Atom"]["link"];
- if (is_array($authorlinks)) {
- foreach ($authorlinks as $link) {
- $linkdata = array_shift($link["attribs"]);
-
- if ($linkdata["rel"] == "alternate")
- $res["author-link"] = $linkdata["href"];
- };
- }
-
- $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
-
- if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
- $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
- foreach($base as $link) {
- if($link['attribs']['']['rel'] === 'alternate')
- $res['author-link'] = unxmlify($link['attribs']['']['href']);
-
- if(!x($res, 'author-avatar') || !$res['author-avatar']) {
- if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
- $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
- }
- }
- }
-
- $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
-
- if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
- $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
- if($base && count($base)) {
- foreach($base as $link) {
- if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
- $res['author-link'] = unxmlify($link['attribs']['']['href']);
- if(!x($res, 'author-avatar') || !$res['author-avatar']) {
- if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
- $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
- }
- }
- }
- }
-
- // No photo/profile-link on the item - look at the feed level
-
- if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
- $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
- if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
- $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
- foreach($base as $link) {
- if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
- $res['author-link'] = unxmlify($link['attribs']['']['href']);
- if(! $res['author-avatar']) {
- if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
- $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
- }
- }
- }
-
- $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
-
- if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
- $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
-
- if($base && count($base)) {
- foreach($base as $link) {
- if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
- $res['author-link'] = unxmlify($link['attribs']['']['href']);
- if(! (x($res,'author-avatar'))) {
- if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
- $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
- }
- }
- }
- }
- }
-
- $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
- if($apps && $apps[0]['attribs']['']['source']) {
- $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
- if($res['app'] === 'web')
- $res['app'] = 'OStatus';
- }
-
- // base64 encoded json structure representing Diaspora signature
-
- $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
- if($dsig) {
- $res['dsprsig'] = unxmlify($dsig[0]['data']);
- }
-
- $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
- if($dguid)
- $res['guid'] = unxmlify($dguid[0]['data']);
-
- $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
- if($bm)
- $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
-
-
- /**
- * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
- */
-
- $have_real_body = false;
-
- $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
- if($rawenv) {
- $have_real_body = true;
- $res['body'] = $rawenv[0]['data'];
- $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
- // make sure nobody is trying to sneak some html tags by us
- $res['body'] = notags(base64url_decode($res['body']));
- }
-
-
- $res['body'] = limit_body_size($res['body']);
-
- // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
- // the content type. Our own network only emits text normally, though it might have been converted to
- // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
- // have to assume it is all html and needs to be purified.
-
- // It doesn't matter all that much security wise - because before this content is used anywhere, we are
- // going to escape any tags we find regardless, but this lets us import a limited subset of html from
- // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
- // html.
-
- if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
-
- $res['body'] = reltoabs($res['body'],$base_url);
-
- $res['body'] = html2bb_video($res['body']);
-
- $res['body'] = oembed_html2bbcode($res['body']);
-
- $config = HTMLPurifier_Config::createDefault();
- $config->set('Cache.DefinitionImpl', null);
-
- // we shouldn't need a whitelist, because the bbcode converter
- // will strip out any unsupported tags.
-
- $purifier = new HTMLPurifier($config);
- $res['body'] = $purifier->purify($res['body']);
-
- $res['body'] = @html2bbcode($res['body']);
-
-
- }
- elseif(! $have_real_body) {
-
- // it's not one of our messages and it has no tags
- // so it's probably just text. We'll escape it just to be safe.
-
- $res['body'] = escape_tags($res['body']);
- }
-
-
- // this tag is obsolete but we keep it for really old sites
-
- $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
- if($allow && $allow[0]['data'] == 1)
- $res['last-child'] = 1;
- else
- $res['last-child'] = 0;
-
- $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
- if($private && intval($private[0]['data']) > 0)
- $res['private'] = intval($private[0]['data']);
- else
- $res['private'] = 0;
-
- $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
- if($extid && $extid[0]['data'])
- $res['extid'] = $extid[0]['data'];
-
- $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
- if($rawlocation)
- $res['location'] = unxmlify($rawlocation[0]['data']);
-
-
- $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
- if($rawcreated)
- $res['created'] = unxmlify($rawcreated[0]['data']);
-
-
- $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
- if($rawedited)
- $res['edited'] = unxmlify($rawedited[0]['data']);
-
- if((x($res,'edited')) && (! (x($res,'created'))))
- $res['created'] = $res['edited'];
-
- if(! $res['created'])
- $res['created'] = $item->get_date('c');
-
- if(! $res['edited'])
- $res['edited'] = $item->get_date('c');
-
-
- // Disallow time travelling posts
-
- $d1 = strtotime($res['created']);
- $d2 = strtotime($res['edited']);
- $d3 = strtotime('now');
-
- if($d1 > $d3)
- $res['created'] = datetime_convert();
- if($d2 > $d3)
- $res['edited'] = datetime_convert();
-
- $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
- if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
- $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
- elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
- $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
- if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
- $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
- elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
- $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
-
- if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
- $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
-
- foreach($base as $link) {
- if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
- if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
- $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
- }
- }
- }
-
- $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
- if($rawgeo)
- $res['coord'] = unxmlify($rawgeo[0]['data']);
-
- if ($contact["network"] == NETWORK_FEED) {
- $res['verb'] = ACTIVITY_POST;
- $res['object-type'] = ACTIVITY_OBJ_NOTE;
- }
-
- $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
-
- // select between supported verbs
-
- if($rawverb) {
- $res['verb'] = unxmlify($rawverb[0]['data']);
- }
-
- // translate OStatus unfollow to activity streams if it happened to get selected
-
- if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
- $res['verb'] = ACTIVITY_UNFOLLOW;
-
- $cats = $item->get_categories();
- if($cats) {
- $tag_arr = array();
- foreach($cats as $cat) {
- $term = $cat->get_term();
- if(! $term)
- $term = $cat->get_label();
- $scheme = $cat->get_scheme();
- if($scheme && $term && stristr($scheme,'X-DFRN:'))
- $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
- elseif($term)
- $tag_arr[] = notags(trim($term));
- }
- $res['tag'] = implode(',', $tag_arr);
- }
-
- $attach = $item->get_enclosures();
- if($attach) {
- $att_arr = array();
- foreach($attach as $att) {
- $len = intval($att->get_length());
- $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
- $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
- $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
- if(strpos($type,';'))
- $type = substr($type,0,strpos($type,';'));
- if((! $link) || (strpos($link,'http') !== 0))
- continue;
-
- if(! $title)
- $title = ' ';
- if(! $type)
- $type = 'application/octet-stream';
-
- $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
- }
- $res['attach'] = implode(',', $att_arr);
- }
-
- $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
-
- if($rawobj) {
- $res['object'] = '' . "\n";
- }
-
- $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
-
- if($rawobj) {
- $res['target'] = '' . "\n";
- $child = $rawobj[0]['child'];
- if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
- $res['target'] .= '' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '' . "\n";
- }
- if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
- $res['target'] .= '' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '' . "\n";
- if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
- $res['target'] .= '' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '' . "\n";
- if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
- $res['target'] .= '' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '' . "\n";
- if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
- $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
- if(! $body)
- $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
- // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
- $res['target'] .= '' . xmlify($body) . '' . "\n";
- if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
-
- $body = html2bb_video($body);
-
- $config = HTMLPurifier_Config::createDefault();
- $config->set('Cache.DefinitionImpl', null);
-
- $purifier = new HTMLPurifier($config);
- $body = $purifier->purify($body);
- $body = html2bbcode($body);
- }
-
- $res['target'] .= '' . $body . '' . "\n";
- }
-
- $res['target'] .= '' . "\n";
- }
-
- // This is some experimental stuff. By now retweets are shown with "RT:"
- // But: There is data so that the message could be shown similar to native retweets
- // There is some better way to parse this array - but it didn't worked for me.
- $child = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://activitystrea.ms/spec/1.0/"][object][0]["child"];
- if (is_array($child)) {
- logger('get_atom_elements: Looking for status.net repeated message');
-
- $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
- $orig_id = ostatus_convert_href($child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["id"][0]["data"]);
- $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
- $uri = $author["uri"][0]["data"];
- $name = $author["name"][0]["data"];
- $avatar = @array_shift($author["link"][2]["attribs"]);
- $avatar = $avatar["href"];
-
- if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
- logger('get_atom_elements: fixing sender of repeated message. '.$orig_id, LOGGER_DEBUG);
-
- if (!intval(get_config('system','wall-to-wall_share'))) {
- $prefix = share_header($name, $uri, $avatar, "", "", $orig_link);
-
- $res["body"] = $prefix.html2bbcode($message)."[/share]";
- } else {
- $res["owner-name"] = $res["author-name"];
- $res["owner-link"] = $res["author-link"];
- $res["owner-avatar"] = $res["author-avatar"];
-
- $res["author-name"] = $name;
- $res["author-link"] = $uri;
- $res["author-avatar"] = $avatar;
-
- $res["body"] = html2bbcode($message);
- }
- }
- }
-
- if (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND $contact['fetch_further_information']) {
- $preview = "";
-
- // Handle enclosures and treat them as preview picture
- if (isset($attach))
- foreach ($attach AS $attachment)
- if ($attachment->type == "image/jpeg")
- $preview = $attachment->link;
-
- $res["body"] = $res["title"].add_page_info($res['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_blacklist']);
- $res["tag"] = add_page_keywords($res['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_blacklist']);
- $res["title"] = "";
- $res["object-type"] = ACTIVITY_OBJ_BOOKMARK;
- unset($res["attach"]);
- } elseif (isset($contact["network"]) AND ($contact["network"] == NETWORK_OSTATUS))
- $res["body"] = add_page_info_to_body($res["body"]);
- elseif (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND strstr($res['plink'], ".app.net/")) {
- $res["body"] = add_page_info_to_body($res["body"]);
- }
-
- $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
-
- call_hooks('parse_atom', $arr);
-
- return $res;
-}
-
function add_page_info_data($data) {
call_hooks('page_info_data', $data);
@@ -955,8 +184,9 @@ function add_page_info_data($data) {
$a = get_app();
$hashtags = "\n";
foreach ($data["keywords"] AS $keyword) {
- $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
- array("","", "", "", "", ""), $keyword);
+ /// @todo make a positive list of allowed characters
+ $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"),
+ array("","", "", "", "", "", "", "", "", "", "", ""), $keyword);
$hashtags .= "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag)."]".$hashtag."[/url] ";
}
}
@@ -967,12 +197,7 @@ function add_page_info_data($data) {
function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
require_once("mod/parse_url.php");
- $data = Cache::get("parse_url:".$url);
- if (is_null($data)){
- $data = parseurl_getsiteinfo($url, true);
- Cache::set("parse_url:".$url,serialize($data), CACHE_DAY);
- } else
- $data = unserialize($data);
+ $data = parseurl_getsiteinfo_cached($url, true);
if ($photo != "")
$data["images"][0]["src"] = $photo;
@@ -1066,37 +291,6 @@ function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
return $body;
}
-function encode_rel_links($links) {
- $o = '';
- if(! ((is_array($links)) && (count($links))))
- return $o;
- foreach($links as $link) {
- $o .= '') !== false))
@@ -1253,6 +444,10 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa
if ($notify)
$guid_prefix = "";
+ elseif ((trim($arr['guid']) == "") AND (trim($arr['plink']) != ""))
+ $arr['guid'] = uri_to_guid($arr['plink']);
+ elseif ((trim($arr['guid']) == "") AND (trim($arr['uri']) != ""))
+ $arr['guid'] = uri_to_guid($arr['uri']);
else {
$parsed = parse_url($arr["author-link"]);
$guid_prefix = hash("crc32", $parsed["host"]);
@@ -1304,6 +499,16 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa
$arr['inform'] = ((x($arr,'inform')) ? trim($arr['inform']) : '');
$arr['file'] = ((x($arr,'file')) ? trim($arr['file']) : '');
+
+ if (($arr['author-link'] == "") AND ($arr['owner-link'] == "")) {
+ $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
+ foreach ($trace AS $func)
+ $function[] = $func["function"];
+
+ $function = implode(", ", $function);
+ logger("Both author-link and owner-link are empty. Called by: ".$function, LOGGER_DEBUG);
+ }
+
if ($arr['plink'] == "") {
$a = get_app();
$arr['plink'] = $a->get_baseurl().'/display/'.urlencode($arr['guid']);
@@ -1338,6 +543,38 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa
logger("item_store: Set network to ".$arr["network"]." for ".$arr["uri"], LOGGER_DEBUG);
}
+ // The contact-id should be set before "item_store" was called - but there seems to be some issues
+ if ($arr["contact-id"] == 0) {
+ // First we are looking for a suitable contact that matches with the author of the post
+ // This is done only for comments (See below explanation at "gcontact-id")
+ if($arr['parent-uri'] != $arr['uri'])
+ $arr["contact-id"] = get_contact($arr['author-link'], $uid);
+
+ // If not present then maybe the owner was found
+ if ($arr["contact-id"] == 0)
+ $arr["contact-id"] = get_contact($arr['owner-link'], $uid);
+
+ // Still missing? Then use the "self" contact of the current user
+ if ($arr["contact-id"] == 0) {
+ $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
+ if ($r)
+ $arr["contact-id"] = $r[0]["id"];
+ }
+ logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
+ }
+
+ if ($arr["gcontact-id"] == 0) {
+ // The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
+ // This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
+ // On comments the author is the better choice.
+ if($arr['parent-uri'] === $arr['uri'])
+ $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['owner-link'], "network" => $arr['network'],
+ "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']));
+ else
+ $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['author-link'], "network" => $arr['network'],
+ "photo" => $arr['author-avatar'], "name" => $arr['author-name']));
+ }
+
if ($arr['guid'] != "") {
// Checking if there is already an item with the same guid
logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
@@ -1531,9 +768,6 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa
return 0;
} elseif(count($r)) {
- // Store the guid and other relevant data
- add_guid($arr);
-
$current_post = $r[0]['id'];
logger('item_store: created item ' . $current_post);
@@ -1609,6 +843,14 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa
);
if($dsprsig) {
+
+ // Friendica servers lower than 3.4.3-2 had double encoded the signature ...
+ // We can check for this condition when we decode and encode the stuff again.
+ if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
+ $dsprsig->signature = base64_decode($dsprsig->signature);
+ logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
+ }
+
q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
intval($current_post),
dbesc($dsprsig->signed_text),
@@ -1653,67 +895,15 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa
create_files_from_item($current_post);
// Only check for notifications on start posts
- if ($arr['parent-uri'] === $arr['uri']) {
+ if ($arr['parent-uri'] === $arr['uri'])
add_thread($current_post);
- logger('item_store: Check notification for contact '.$arr['contact-id'].' and post '.$current_post, LOGGER_DEBUG);
-
- // Send a notification for every new post?
- $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
- intval($arr['contact-id']),
- intval($arr['uid'])
- );
- $send_notification = count($r);
-
- if (!$send_notification) {
- $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
- intval(TERM_OBJ_POST), intval($current_post), intval(TERM_MENTION), intval($arr['uid']));
-
- if (count($tags)) {
- foreach ($tags AS $tag) {
- $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
- normalise_link($tag["url"]), intval($arr['uid']));
- if (count($r))
- $send_notification = true;
- }
- }
- }
-
- if ($send_notification) {
- logger('item_store: Send notification for contact '.$arr['contact-id'].' and post '.$current_post, LOGGER_DEBUG);
- $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
- intval($arr['uid']));
-
- $item = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d",
- intval($current_post),
- intval($arr['uid'])
- );
-
- $a = get_app();
-
- require_once('include/enotify.php');
- notification(array(
- 'type' => NOTIFY_SHARE,
- 'notify_flags' => $u[0]['notify-flags'],
- 'language' => $u[0]['language'],
- 'to_name' => $u[0]['username'],
- 'to_email' => $u[0]['email'],
- 'uid' => $u[0]['uid'],
- 'item' => $item[0],
- 'link' => $a->get_baseurl().'/display/'.urlencode($arr['guid']),
- 'source_name' => $item[0]['author-name'],
- 'source_link' => $item[0]['author-link'],
- 'source_photo' => $item[0]['author-avatar'],
- 'verb' => ACTIVITY_TAG,
- 'otype' => 'item',
- 'parent' => $arr['parent']
- ));
- logger('item_store: Notification sent for contact '.$arr['contact-id'].' and post '.$current_post, LOGGER_DEBUG);
- }
- } else {
+ else {
update_thread($parent_id);
add_shadow_entry($arr);
}
+ check_item_notification($current_post, $uid);
+
if ($notify)
proc_run('php', "include/notifier.php", $notify_type, $current_post);
@@ -1909,37 +1099,6 @@ function tag_deliver($uid,$item_id) {
return;
}
-
- // send a notification
-
- // use a local photo if we have one
-
- $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
- intval($u[0]['uid']),
- dbesc(normalise_link($item['author-link']))
- );
- $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
-
-
- require_once('include/enotify.php');
- notification(array(
- 'type' => NOTIFY_TAGSELF,
- 'notify_flags' => $u[0]['notify-flags'],
- 'language' => $u[0]['language'],
- 'to_name' => $u[0]['username'],
- 'to_email' => $u[0]['email'],
- 'uid' => $u[0]['uid'],
- 'item' => $item,
- 'link' => $a->get_baseurl() . '/display/'.urlencode(get_item_guid($item['id'])),
- 'source_name' => $item['author-name'],
- 'source_link' => $item['author-link'],
- 'source_photo' => $photo,
- 'verb' => ACTIVITY_TAG,
- 'otype' => 'item',
- 'parent' => $item['parent']
- ));
-
-
$arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
call_hooks('tagged', $arr);
@@ -2036,245 +1195,9 @@ function tgroup_check($uid,$item) {
if((! $community_page) && (! $prvgroup))
return false;
-
-
return true;
-
}
-
-
-
-
-
-function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
-
- $a = get_app();
-
- $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
-
- if($contact['duplex'] && $contact['dfrn-id'])
- $idtosend = '0:' . $orig_id;
- if($contact['duplex'] && $contact['issued-id'])
- $idtosend = '1:' . $orig_id;
-
-
- $rino = get_config('system','rino_encrypt');
- $rino = intval($rino);
- // use RINO1 if mcrypt isn't installed and RINO2 was selected
- if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
-
- logger("Local rino version: ". $rino, LOGGER_DEBUG);
-
- $ssl_val = intval(get_config('system','ssl_policy'));
- $ssl_policy = '';
-
- switch($ssl_val){
- case SSL_POLICY_FULL:
- $ssl_policy = 'full';
- break;
- case SSL_POLICY_SELFSIGN:
- $ssl_policy = 'self';
- break;
- case SSL_POLICY_NONE:
- default:
- $ssl_policy = 'none';
- break;
- }
-
- $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
-
- logger('dfrn_deliver: ' . $url);
-
- $xml = fetch_url($url);
-
- $curl_stat = $a->get_curl_code();
- if(! $curl_stat)
- return(-1); // timed out
-
- logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
-
- if(! $xml)
- return 3;
-
- if(strpos($xml,'status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
- return (($res->status) ? $res->status : 3);
-
- $postvars = array();
- $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
- $challenge = hex2bin((string) $res->challenge);
- $perm = (($res->perm) ? $res->perm : null);
- $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
- $rino_remote_version = intval($res->rino);
- $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
-
- logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
-
- if($owner['page-flags'] == PAGE_PRVGROUP)
- $page = 2;
-
- $final_dfrn_id = '';
-
- if($perm) {
- if((($perm == 'rw') && (! intval($contact['writable'])))
- || (($perm == 'r') && (intval($contact['writable'])))) {
- q("update contact set writable = %d where id = %d",
- intval(($perm == 'rw') ? 1 : 0),
- intval($contact['id'])
- );
- $contact['writable'] = (string) 1 - intval($contact['writable']);
- }
- }
-
- if(($contact['duplex'] && strlen($contact['pubkey']))
- || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
- || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
- openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
- openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
- }
- else {
- openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
- openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
- }
-
- $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
-
- if(strpos($final_dfrn_id,':') == 1)
- $final_dfrn_id = substr($final_dfrn_id,2);
-
- if($final_dfrn_id != $orig_id) {
- logger('dfrn_deliver: wrong dfrn_id.');
- // did not decode properly - cannot trust this site
- return 3;
- }
-
- $postvars['dfrn_id'] = $idtosend;
- $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
- if($dissolve)
- $postvars['dissolve'] = '1';
-
-
- if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
- $postvars['data'] = $atom;
- $postvars['perm'] = 'rw';
- }
- else {
- $postvars['data'] = str_replace('1','0',$atom);
- $postvars['perm'] = 'r';
- }
-
- $postvars['ssl_policy'] = $ssl_policy;
-
- if($page)
- $postvars['page'] = $page;
-
-
- if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
- logger('rino version: '. $rino_remote_version);
-
- switch($rino_remote_version) {
- case 1:
- // Deprecated rino version!
- $key = substr(random_string(),0,16);
- $data = aes_encrypt($postvars['data'],$key);
- break;
- case 2:
- // RINO 2 based on php-encryption
- try {
- $key = Crypto::createNewRandomKey();
- } catch (CryptoTestFailed $ex) {
- logger('Cannot safely create a key');
- return -1;
- } catch (CannotPerformOperation $ex) {
- logger('Cannot safely create a key');
- return -1;
- }
- try {
- $data = Crypto::encrypt($postvars['data'], $key);
- } catch (CryptoTestFailed $ex) {
- logger('Cannot safely perform encryption');
- return -1;
- } catch (CannotPerformOperation $ex) {
- logger('Cannot safely perform encryption');
- return -1;
- }
- break;
- default:
- logger("rino: invalid requested verision '$rino_remote_version'");
- return -1;
- }
-
- $postvars['rino'] = $rino_remote_version;
- $postvars['data'] = bin2hex($data);
-
- #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
-
-
- if($dfrn_version >= 2.1) {
- if(($contact['duplex'] && strlen($contact['pubkey']))
- || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
- || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
-
- openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
- }
- else {
- openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
- }
- }
- else {
- if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
- openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
- }
- else {
- openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
- }
- }
-
- logger('md5 rawkey ' . md5($postvars['key']));
-
- $postvars['key'] = bin2hex($postvars['key']);
- }
-
-
- logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
-
- $xml = post_url($contact['notify'],$postvars);
-
- logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
-
- $curl_stat = $a->get_curl_code();
- if((! $curl_stat) || (! strlen($xml)))
- return(-1); // timed out
-
- if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
- return(-1);
-
- if(strpos($xml,'status;
-}
-
-
/*
This function returns true if $update has an edited timestamp newer
than $existing, i.e. $update contains new data which should override
@@ -2342,639 +1265,25 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
return;
}
- require_once('library/simplepie/simplepie.inc');
- require_once('include/contact_selectors.php');
-
- if(! strlen($xml)) {
- logger('consume_feed: empty input');
- return;
- }
-
- $feed = new SimplePie();
- $feed->set_raw_data($xml);
- if($datedir)
- $feed->enable_order_by_date(true);
- else
- $feed->enable_order_by_date(false);
- $feed->init();
-
- if($feed->error())
- logger('consume_feed: Error parsing XML: ' . $feed->error());
-
- $permalink = $feed->get_permalink();
-
- // Check at the feed level for updated contact name and/or photo
-
- $name_updated = '';
- $new_name = '';
- $photo_timestamp = '';
- $photo_url = '';
- $birthday = '';
- $contact_updated = '';
-
- $hubs = $feed->get_links('hub');
- logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
-
- if(count($hubs))
- $hub = implode(',', $hubs);
-
- $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
- if(! $rawtags)
- $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
- if($rawtags) {
- $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
- if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
- $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
- $new_name = $elems['name'][0]['data'];
-
- // Manually checking for changed contact names
- if (($new_name != $contact['name']) AND ($new_name != "") AND ($name_updated <= $contact['name-date'])) {
- $name_updated = date("c");
- $photo_timestamp = date("c");
- }
- }
- if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
- if ($photo_timestamp == "")
- $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
- $photo_url = $elems['link'][0]['attribs']['']['href'];
- }
-
- if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
- $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
- }
- }
-
- if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
- logger('consume_feed: Updating photo for '.$contact['name'].' from '.$photo_url.' uid: '.$contact['uid']);
-
- $contact_updated = $photo_timestamp;
-
- require_once("include/Photo.php");
- $photos = import_profile_photo($photo_url,$contact['uid'],$contact['id']);
-
- q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
- WHERE `uid` = %d AND `id` = %d AND NOT `self`",
- dbesc(datetime_convert()),
- dbesc($photos[0]),
- dbesc($photos[1]),
- dbesc($photos[2]),
- intval($contact['uid']),
- intval($contact['id'])
- );
- }
-
- if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
- if ($name_updated > $contact_updated)
- $contact_updated = $name_updated;
-
- $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
- intval($contact['uid']),
- intval($contact['id'])
- );
-
- $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d AND `name` != '%s' AND NOT `self`",
- dbesc(notags(trim($new_name))),
- dbesc(datetime_convert()),
- intval($contact['uid']),
- intval($contact['id']),
- dbesc(notags(trim($new_name)))
- );
-
- // do our best to update the name on content items
-
- if(count($r) AND (notags(trim($new_name)) != $r[0]['name'])) {
- q("UPDATE `item` SET `author-name` = '%s' WHERE `author-name` = '%s' AND `author-link` = '%s' AND `uid` = %d AND `author-name` != '%s'",
- dbesc(notags(trim($new_name))),
- dbesc($r[0]['name']),
- dbesc($r[0]['url']),
- intval($contact['uid']),
- dbesc(notags(trim($new_name)))
- );
- }
- }
-
- if ($contact_updated AND $new_name AND $photo_url)
- poco_check($contact['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $contact['id'], $contact['uid']);
-
- if(strlen($birthday)) {
- if(substr($birthday,0,4) != $contact['bdyear']) {
- logger('consume_feed: updating birthday: ' . $birthday);
-
- /**
- *
- * Add new birthday event for this person
- *
- * $bdtext is just a readable placeholder in case the event is shared
- * with others. We will replace it during presentation to our $importer
- * to contain a sparkle link and perhaps a photo.
- *
- */
-
- $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
- $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
-
-
- $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
- VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
- intval($contact['uid']),
- intval($contact['id']),
- dbesc(datetime_convert()),
- dbesc(datetime_convert()),
- dbesc(datetime_convert('UTC','UTC', $birthday)),
- dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
- dbesc($bdtext),
- dbesc($bdtext2),
- dbesc('birthday')
- );
-
-
- // update bdyear
-
- q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d",
- dbesc(substr($birthday,0,4)),
- intval($contact['uid']),
- intval($contact['id'])
- );
-
- // This function is called twice without reloading the contact
- // Make sure we only create one event. This is why &$contact
- // is a reference var in this function
-
- $contact['bdyear'] = substr($birthday,0,4);
- }
- }
-
- $community_page = 0;
- $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
- if($rawtags) {
- $community_page = intval($rawtags[0]['data']);
- }
- if(is_array($contact) && intval($contact['forum']) != $community_page) {
- q("update contact set forum = %d where id = %d",
- intval($community_page),
- intval($contact['id'])
- );
- $contact['forum'] = (string) $community_page;
- }
-
-
- // process any deleted entries
-
- $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
- if(is_array($del_entries) && count($del_entries) && $pass != 2) {
- foreach($del_entries as $dentry) {
- $deleted = false;
- if(isset($dentry['attribs']['']['ref'])) {
- $uri = $dentry['attribs']['']['ref'];
- $deleted = true;
- if(isset($dentry['attribs']['']['when'])) {
- $when = $dentry['attribs']['']['when'];
- $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
- }
- else
- $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
- }
- if($deleted && is_array($contact)) {
- $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
- WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
- dbesc($uri),
- intval($importer['uid']),
- intval($contact['id'])
- );
- if(count($r)) {
- $item = $r[0];
-
- if(! $item['deleted'])
- logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
-
- if($item['object-type'] === ACTIVITY_OBJ_EVENT) {
- logger("Deleting event ".$item['event-id'], LOGGER_DEBUG);
- event_delete($item['event-id']);
- }
-
- if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
- $xo = parse_xml_string($item['object'],false);
- $xt = parse_xml_string($item['target'],false);
- if($xt->type === ACTIVITY_OBJ_NOTE) {
- $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
- dbesc($xt->id),
- intval($importer['importer_uid'])
- );
- if(count($i)) {
-
- // For tags, the owner cannot remove the tag on the author's copy of the post.
-
- $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
- $author_remove = (($item['origin'] && $item['self']) ? true : false);
- $author_copy = (($item['origin']) ? true : false);
-
- if($owner_remove && $author_copy)
- continue;
- if($author_remove || $owner_remove) {
- $tags = explode(',',$i[0]['tag']);
- $newtags = array();
- if(count($tags)) {
- foreach($tags as $tag)
- if(trim($tag) !== trim($xo->body))
- $newtags[] = trim($tag);
- }
- q("update item set tag = '%s' where id = %d",
- dbesc(implode(',',$newtags)),
- intval($i[0]['id'])
- );
- create_tags_from_item($i[0]['id']);
- }
- }
- }
- }
-
- if($item['uri'] == $item['parent-uri']) {
- $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
- `body` = '', `title` = ''
- WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc($when),
- dbesc(datetime_convert()),
- dbesc($item['uri']),
- intval($importer['uid'])
- );
- create_tags_from_itemuri($item['uri'], $importer['uid']);
- create_files_from_itemuri($item['uri'], $importer['uid']);
- update_thread_uri($item['uri'], $importer['uid']);
- }
- else {
- $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
- `body` = '', `title` = ''
- WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($when),
- dbesc(datetime_convert()),
- dbesc($uri),
- intval($importer['uid'])
- );
- create_tags_from_itemuri($uri, $importer['uid']);
- create_files_from_itemuri($uri, $importer['uid']);
- if($item['last-child']) {
- // ensure that last-child is set in case the comment that had it just got wiped.
- q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
- dbesc(datetime_convert()),
- dbesc($item['parent-uri']),
- intval($item['uid'])
- );
- // who is the last child now?
- $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
- ORDER BY `created` DESC LIMIT 1",
- dbesc($item['parent-uri']),
- intval($importer['uid'])
- );
- if(count($r)) {
- q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
- intval($r[0]['id'])
- );
- }
- }
- }
- }
- }
- }
- }
-
- // Now process the feed
-
- if($feed->get_item_quantity()) {
-
- logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
-
- // in inverse date order
- if ($datedir)
- $items = array_reverse($feed->get_items());
- else
- $items = $feed->get_items();
-
-
- foreach($items as $item) {
-
- $is_reply = false;
- $item_id = $item->get_id();
- $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
- if(isset($rawthread[0]['attribs']['']['ref'])) {
- $is_reply = true;
- $parent_uri = $rawthread[0]['attribs']['']['ref'];
- }
-
- if(($is_reply) && is_array($contact)) {
-
- if($pass == 1)
- continue;
-
- // not allowed to post
-
- if($contact['rel'] == CONTACT_IS_FOLLOWER)
- continue;
-
-
- // Have we seen it? If not, import it.
-
- $item_id = $item->get_id();
- $datarray = get_atom_elements($feed, $item, $contact);
-
- if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
- $datarray['author-name'] = $contact['name'];
- if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
- $datarray['author-link'] = $contact['url'];
- if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
- $datarray['author-avatar'] = $contact['thumb'];
-
- if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
- logger('consume_feed: no author information! ' . print_r($datarray,true));
- continue;
- }
-
- $force_parent = false;
- if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
- if($contact['network'] === NETWORK_OSTATUS)
- $force_parent = true;
- if(strlen($datarray['title']))
- unset($datarray['title']);
- $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc(datetime_convert()),
- dbesc($parent_uri),
- intval($importer['uid'])
- );
- $datarray['last-child'] = 1;
- update_thread_uri($parent_uri, $importer['uid']);
- }
-
-
- $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['uid'])
- );
-
- // Update content if 'updated' changes
-
- if(count($r)) {
- if (edited_timestamp_is_newer($r[0], $datarray)) {
-
- // do not accept (ignore) an earlier edit than one we currently have.
- if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
- continue;
-
- $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($datarray['title']),
- dbesc($datarray['body']),
- dbesc($datarray['tag']),
- dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['uid'])
- );
- create_tags_from_itemuri($item_id, $importer['uid']);
- update_thread_uri($item_id, $importer['uid']);
- }
-
- // update last-child if it changes
-
- $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
- if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
- $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc(datetime_convert()),
- dbesc($parent_uri),
- intval($importer['uid'])
- );
- $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- intval($allow[0]['data']),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['uid'])
- );
- update_thread_uri($item_id, $importer['uid']);
- }
- continue;
- }
-
-
- if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
- // one way feed - no remote comment ability
- $datarray['last-child'] = 0;
- }
- $datarray['parent-uri'] = $parent_uri;
- $datarray['uid'] = $importer['uid'];
- $datarray['contact-id'] = $contact['id'];
- if(($datarray['verb'] === ACTIVITY_LIKE)
- || ($datarray['verb'] === ACTIVITY_DISLIKE)
- || ($datarray['verb'] === ACTIVITY_ATTEND)
- || ($datarray['verb'] === ACTIVITY_ATTENDNO)
- || ($datarray['verb'] === ACTIVITY_ATTENDMAYBE)) {
- $datarray['type'] = 'activity';
- $datarray['gravity'] = GRAVITY_LIKE;
- // only one like or dislike per person
- // splitted into two queries for performance issues
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
- intval($datarray['uid']),
- dbesc($datarray['author-link']),
- dbesc($datarray['verb']),
- dbesc($datarray['parent-uri'])
- );
- if($r && count($r))
- continue;
-
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
- intval($datarray['uid']),
- dbesc($datarray['author-link']),
- dbesc($datarray['verb']),
- dbesc($datarray['parent-uri'])
- );
- if($r && count($r))
- continue;
- }
-
- if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
- $xo = parse_xml_string($datarray['object'],false);
- $xt = parse_xml_string($datarray['target'],false);
-
- if($xt->type == ACTIVITY_OBJ_NOTE) {
- $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
- dbesc($xt->id),
- intval($importer['importer_uid'])
- );
- if(! count($r))
- continue;
-
- // extract tag, if not duplicate, add to parent item
- if($xo->id && $xo->content) {
- $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
- if(! (stristr($r[0]['tag'],$newtag))) {
- q("UPDATE item SET tag = '%s' WHERE id = %d",
- dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
- intval($r[0]['id'])
- );
- create_tags_from_item($r[0]['id']);
- }
- }
- }
- }
-
- $r = item_store($datarray,$force_parent);
- continue;
- }
-
- else {
-
- // Head post of a conversation. Have we seen it? If not, import it.
-
- $item_id = $item->get_id();
-
- $datarray = get_atom_elements($feed, $item, $contact);
-
- if(is_array($contact)) {
- if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
- $datarray['author-name'] = $contact['name'];
- if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
- $datarray['author-link'] = $contact['url'];
- if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
- $datarray['author-avatar'] = $contact['thumb'];
- }
-
- if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
- logger('consume_feed: no author information! ' . print_r($datarray,true));
- continue;
- }
-
- // special handling for events
-
- if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
- $ev = bbtoevent($datarray['body']);
- if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
- $ev['uid'] = $importer['uid'];
- $ev['uri'] = $item_id;
- $ev['edited'] = $datarray['edited'];
- $ev['private'] = $datarray['private'];
- $ev['guid'] = $datarray['guid'];
-
- if(is_array($contact))
- $ev['cid'] = $contact['id'];
- $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['uid'])
- );
- if(count($r))
- $ev['id'] = $r[0]['id'];
- $xyz = event_store($ev);
- continue;
- }
- }
-
- if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
- if(strlen($datarray['title']))
- unset($datarray['title']);
- $datarray['last-child'] = 1;
- }
-
-
- $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['uid'])
- );
-
- // Update content if 'updated' changes
-
- if(count($r)) {
- if (edited_timestamp_is_newer($r[0], $datarray)) {
-
- // do not accept (ignore) an earlier edit than one we currently have.
- if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
- continue;
-
- $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($datarray['title']),
- dbesc($datarray['body']),
- dbesc($datarray['tag']),
- dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['uid'])
- );
- create_tags_from_itemuri($item_id, $importer['uid']);
- update_thread_uri($item_id, $importer['uid']);
- }
-
- // update last-child if it changes
-
- $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
- if($allow && $allow[0]['data'] != $r[0]['last-child']) {
- $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- intval($allow[0]['data']),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['uid'])
- );
- update_thread_uri($item_id, $importer['uid']);
- }
- continue;
- }
-
- if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
- logger('consume-feed: New follower');
- new_follower($importer,$contact,$datarray,$item);
- return;
- }
- if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
- lose_follower($importer,$contact,$datarray,$item);
- return;
- }
-
- if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
- logger('consume-feed: New friend request');
- new_follower($importer,$contact,$datarray,$item,true);
- return;
- }
- if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
- lose_sharer($importer,$contact,$datarray,$item);
- return;
- }
-
-
- if(! is_array($contact))
- return;
-
-
- if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
- // one way feed - no remote comment ability
- $datarray['last-child'] = 0;
- }
- if($contact['network'] === NETWORK_FEED)
- $datarray['private'] = 2;
-
- $datarray['parent-uri'] = $item_id;
- $datarray['uid'] = $importer['uid'];
- $datarray['contact-id'] = $contact['id'];
-
- if(! link_compare($datarray['owner-link'],$contact['url'])) {
- // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
- // but otherwise there's a possible data mixup on the sender's system.
- // the tgroup delivery code called from item_store will correct it if it's a forum,
- // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
- logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
- $datarray['owner-name'] = $contact['name'];
- $datarray['owner-link'] = $contact['url'];
- $datarray['owner-avatar'] = $contact['thumb'];
- }
-
- // We've allowed "followers" to reach this point so we can decide if they are
- // posting an @-tag delivery, which followers are allowed to do for certain
- // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
-
- if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
- continue;
-
- // This is my contact on another system, but it's really me.
- // Turn this into a wall post.
- $notify = item_is_remote_self($contact, $datarray);
-
- $r = item_store($datarray, false, $notify);
- logger('Stored - Contact '.$contact['url'].' Notify '.$notify.' return '.$r.' Item '.print_r($datarray, true), LOGGER_DEBUG);
- continue;
-
- }
+ if ($contact['network'] === NETWORK_DFRN) {
+ logger("Consume DFRN messages", LOGGER_DEBUG);
+
+ $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
+ `contact`.`pubkey` AS `cpubkey`,
+ `contact`.`prvkey` AS `cprvkey`,
+ `contact`.`thumb` AS `thumb`,
+ `contact`.`url` as `url`,
+ `contact`.`name` as `senderName`,
+ `user`.*
+ FROM `contact`
+ LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
+ WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
+ dbesc($contact["id"]), dbesc($importer["uid"])
+ );
+ if ($r) {
+ logger("Now import the DFRN feed");
+ dfrn::import($xml,$r[0], true);
+ return;
}
}
}
@@ -3039,1144 +1348,6 @@ function item_is_remote_self($contact, &$datarray) {
return true;
}
-function local_delivery($importer,$data) {
- $a = get_app();
-
- logger(__function__, LOGGER_TRACE);
-
- if($importer['readonly']) {
- // We aren't receiving stuff from this person. But we will quietly ignore them
- // rather than a blatant "go away" message.
- logger('local_delivery: ignoring');
- return 0;
- //NOTREACHED
- }
-
- // Consume notification feed. This may differ from consuming a public feed in several ways
- // - might contain email or friend suggestions
- // - might contain remote followup to our message
- // - in which case we need to accept it and then notify other conversants
- // - we may need to send various email notifications
-
- $feed = new SimplePie();
- $feed->set_raw_data($data);
- $feed->enable_order_by_date(false);
- $feed->init();
-
-
- if($feed->error())
- logger('local_delivery: Error parsing XML: ' . $feed->error());
-
-
- // Check at the feed level for updated contact name and/or photo
-
- $name_updated = '';
- $new_name = '';
- $photo_timestamp = '';
- $photo_url = '';
- $contact_updated = '';
-
-
- $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
-
-// Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
-// if(! $rawtags)
-// $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
-
- if($rawtags) {
- $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
- if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
- $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
- $new_name = $elems['name'][0]['data'];
-
- // Manually checking for changed contact names
- if (($new_name != $importer['name']) AND ($new_name != "") AND ($name_updated <= $importer['name-date'])) {
- $name_updated = date("c");
- $photo_timestamp = date("c");
- }
- }
- if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
- if ($photo_timestamp == "")
- $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
- $photo_url = $elems['link'][0]['attribs']['']['href'];
- }
- }
-
- if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
-
- $contact_updated = $photo_timestamp;
-
- logger('local_delivery: Updating photo for ' . $importer['name']);
- require_once("include/Photo.php");
-
- $photos = import_profile_photo($photo_url,$importer['importer_uid'],$importer['id']);
-
- q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
- WHERE `uid` = %d AND `id` = %d AND NOT `self`",
- dbesc(datetime_convert()),
- dbesc($photos[0]),
- dbesc($photos[1]),
- dbesc($photos[2]),
- intval($importer['importer_uid']),
- intval($importer['id'])
- );
- }
-
- if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
- if ($name_updated > $contact_updated)
- $contact_updated = $name_updated;
-
- $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
- intval($importer['importer_uid']),
- intval($importer['id'])
- );
-
- $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d AND `name` != '%s' AND NOT `self`",
- dbesc(notags(trim($new_name))),
- dbesc(datetime_convert()),
- intval($importer['importer_uid']),
- intval($importer['id']),
- dbesc(notags(trim($new_name)))
- );
-
- // do our best to update the name on content items
-
- if(count($r) AND (notags(trim($new_name)) != $r[0]['name'])) {
- q("UPDATE `item` SET `author-name` = '%s' WHERE `author-name` = '%s' AND `author-link` = '%s' AND `uid` = %d AND `author-name` != '%s'",
- dbesc(notags(trim($new_name))),
- dbesc($r[0]['name']),
- dbesc($r[0]['url']),
- intval($importer['importer_uid']),
- dbesc(notags(trim($new_name)))
- );
- }
- }
-
- if ($contact_updated AND $new_name AND $photo_url)
- poco_check($importer['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $importer['id'], $importer['importer_uid']);
-
- // Currently unsupported - needs a lot of work
- $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
- if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
- $base = $reloc[0]['child'][NAMESPACE_DFRN];
- $newloc = array();
- $newloc['uid'] = $importer['importer_uid'];
- $newloc['cid'] = $importer['id'];
- $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
- $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
- $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
- $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
- $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
- $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
- $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
- $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
- $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
- $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
- /** relocated user must have original key pair */
- /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
- $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
-
- logger("items:relocate contact ".print_r($newloc, true).print_r($importer, true), LOGGER_DEBUG);
-
- // update contact
- $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;",
- intval($importer['id']),
- intval($importer['importer_uid']));
- if ($r === false)
- return 1;
- $old = $r[0];
-
- $x = q("UPDATE contact SET
- name = '%s',
- photo = '%s',
- thumb = '%s',
- micro = '%s',
- url = '%s',
- nurl = '%s',
- request = '%s',
- confirm = '%s',
- notify = '%s',
- poll = '%s',
- `site-pubkey` = '%s'
- WHERE id=%d AND uid=%d;",
- dbesc($newloc['name']),
- dbesc($newloc['photo']),
- dbesc($newloc['thumb']),
- dbesc($newloc['micro']),
- dbesc($newloc['url']),
- dbesc(normalise_link($newloc['url'])),
- dbesc($newloc['request']),
- dbesc($newloc['confirm']),
- dbesc($newloc['notify']),
- dbesc($newloc['poll']),
- dbesc($newloc['sitepubkey']),
- intval($importer['id']),
- intval($importer['importer_uid']));
-
- if ($x === false)
- return 1;
- // update items
- $fields = array(
- 'owner-link' => array($old['url'], $newloc['url']),
- 'author-link' => array($old['url'], $newloc['url']),
- 'owner-avatar' => array($old['photo'], $newloc['photo']),
- 'author-avatar' => array($old['photo'], $newloc['photo']),
- );
- foreach ($fields as $n=>$f){
- $x = q("UPDATE `item` SET `%s`='%s' WHERE `%s`='%s' AND uid=%d",
- $n, dbesc($f[1]),
- $n, dbesc($f[0]),
- intval($importer['importer_uid']));
- if ($x === false)
- return 1;
- }
-
- /// @TODO
- /// merge with current record, current contents have priority
- /// update record, set url-updated
- /// update profile photos
- /// schedule a scan?
- return 0;
- }
-
-
- // handle friend suggestion notification
-
- $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
- if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
- $base = $sugg[0]['child'][NAMESPACE_DFRN];
- $fsugg = array();
- $fsugg['uid'] = $importer['importer_uid'];
- $fsugg['cid'] = $importer['id'];
- $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
- $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
- $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
- $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
- $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
-
- // Does our member already have a friend matching this description?
-
- $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($fsugg['name']),
- dbesc(normalise_link($fsugg['url'])),
- intval($fsugg['uid'])
- );
- if(count($r))
- return 0;
-
- // Do we already have an fcontact record for this person?
-
- $fid = 0;
- $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
- dbesc($fsugg['url']),
- dbesc($fsugg['name']),
- dbesc($fsugg['request'])
- );
- if(count($r)) {
- $fid = $r[0]['id'];
-
- // OK, we do. Do we already have an introduction for this person ?
- $r = q("select id from intro where uid = %d and fid = %d limit 1",
- intval($fsugg['uid']),
- intval($fid)
- );
- if(count($r))
- return 0;
- }
- if(! $fid)
- $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
- dbesc($fsugg['name']),
- dbesc($fsugg['url']),
- dbesc($fsugg['photo']),
- dbesc($fsugg['request'])
- );
- $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
- dbesc($fsugg['url']),
- dbesc($fsugg['name']),
- dbesc($fsugg['request'])
- );
- if(count($r)) {
- $fid = $r[0]['id'];
- }
- // database record did not get created. Quietly give up.
- else
- return 0;
-
-
- $hash = random_string();
-
- $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
- VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
- intval($fsugg['uid']),
- intval($fid),
- intval($fsugg['cid']),
- dbesc($fsugg['body']),
- dbesc($hash),
- dbesc(datetime_convert()),
- intval(0)
- );
-
- notification(array(
- 'type' => NOTIFY_SUGGEST,
- 'notify_flags' => $importer['notify-flags'],
- 'language' => $importer['language'],
- 'to_name' => $importer['username'],
- 'to_email' => $importer['email'],
- 'uid' => $importer['importer_uid'],
- 'item' => $fsugg,
- 'link' => $a->get_baseurl() . '/notifications/intros',
- 'source_name' => $importer['name'],
- 'source_link' => $importer['url'],
- 'source_photo' => $importer['photo'],
- 'verb' => ACTIVITY_REQ_FRIEND,
- 'otype' => 'intro'
- ));
-
- return 0;
- }
-
- $ismail = false;
-
- $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
- if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
-
- logger('local_delivery: private message received');
-
- $ismail = true;
- $base = $rawmail[0]['child'][NAMESPACE_DFRN];
-
- $msg = array();
- $msg['uid'] = $importer['importer_uid'];
- $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
- $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
- $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
- $msg['contact-id'] = $importer['id'];
- $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
- $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
- $msg['seen'] = 0;
- $msg['replied'] = 0;
- $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
- $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
- $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
-
- dbesc_array($msg);
-
- $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
- . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
-
- // send notifications.
-
- require_once('include/enotify.php');
-
- $notif_params = array(
- 'type' => NOTIFY_MAIL,
- 'notify_flags' => $importer['notify-flags'],
- 'language' => $importer['language'],
- 'to_name' => $importer['username'],
- 'to_email' => $importer['email'],
- 'uid' => $importer['importer_uid'],
- 'item' => $msg,
- 'source_name' => $msg['from-name'],
- 'source_link' => $importer['url'],
- 'source_photo' => $importer['thumb'],
- 'verb' => ACTIVITY_POST,
- 'otype' => 'mail'
- );
-
- notification($notif_params);
- return 0;
-
- // NOTREACHED
- }
-
- $community_page = 0;
- $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
- if($rawtags) {
- $community_page = intval($rawtags[0]['data']);
- }
- if(intval($importer['forum']) != $community_page) {
- q("update contact set forum = %d where id = %d",
- intval($community_page),
- intval($importer['id'])
- );
- $importer['forum'] = (string) $community_page;
- }
-
- logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
-
- // process any deleted entries
-
- $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
- if(is_array($del_entries) && count($del_entries)) {
- foreach($del_entries as $dentry) {
- $deleted = false;
- if(isset($dentry['attribs']['']['ref'])) {
- $uri = $dentry['attribs']['']['ref'];
- $deleted = true;
- if(isset($dentry['attribs']['']['when'])) {
- $when = $dentry['attribs']['']['when'];
- $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
- }
- else
- $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
- }
- if($deleted) {
-
- // check for relayed deletes to our conversation
-
- $is_reply = false;
- $r = q("select * from item where uri = '%s' and uid = %d limit 1",
- dbesc($uri),
- intval($importer['importer_uid'])
- );
- if(count($r)) {
- $parent_uri = $r[0]['parent-uri'];
- if($r[0]['id'] != $r[0]['parent'])
- $is_reply = true;
- }
-
- if($is_reply) {
- $community = false;
-
- if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
- $sql_extra = '';
- $community = true;
- logger('local_delivery: possible community delete');
- }
- else
- $sql_extra = " and contact.self = 1 and item.wall = 1 ";
-
- // was the top-level post for this reply written by somebody on this site?
- // Specifically, the recipient?
-
- $is_a_remote_delete = false;
-
- // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
- $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
- `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
- INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
- WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
- AND `item`.`uid` = %d
- $sql_extra
- LIMIT 1",
- dbesc($parent_uri),
- dbesc($parent_uri),
- dbesc($parent_uri),
- intval($importer['importer_uid'])
- );
- if($r && count($r))
- $is_a_remote_delete = true;
-
- // Does this have the characteristics of a community or private group comment?
- // If it's a reply to a wall post on a community/prvgroup page it's a
- // valid community comment. Also forum_mode makes it valid for sure.
- // If neither, it's not.
-
- if($is_a_remote_delete && $community) {
- if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
- $is_a_remote_delete = false;
- logger('local_delivery: not a community delete');
- }
- }
-
- if($is_a_remote_delete) {
- logger('local_delivery: received remote delete');
- }
- }
-
- $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN contact on `item`.`contact-id` = `contact`.`id`
- WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
- dbesc($uri),
- intval($importer['importer_uid']),
- intval($importer['id'])
- );
-
- if(count($r)) {
- $item = $r[0];
-
- if($item['deleted'])
- continue;
-
- logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
-
- if($item['object-type'] === ACTIVITY_OBJ_EVENT) {
- logger("Deleting event ".$item['event-id'], LOGGER_DEBUG);
- event_delete($item['event-id']);
- }
-
- if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
- $xo = parse_xml_string($item['object'],false);
- $xt = parse_xml_string($item['target'],false);
-
- if($xt->type === ACTIVITY_OBJ_NOTE) {
- $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
- dbesc($xt->id),
- intval($importer['importer_uid'])
- );
- if(count($i)) {
-
- // For tags, the owner cannot remove the tag on the author's copy of the post.
-
- $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
- $author_remove = (($item['origin'] && $item['self']) ? true : false);
- $author_copy = (($item['origin']) ? true : false);
-
- if($owner_remove && $author_copy)
- continue;
- if($author_remove || $owner_remove) {
- $tags = explode(',',$i[0]['tag']);
- $newtags = array();
- if(count($tags)) {
- foreach($tags as $tag)
- if(trim($tag) !== trim($xo->body))
- $newtags[] = trim($tag);
- }
- q("update item set tag = '%s' where id = %d",
- dbesc(implode(',',$newtags)),
- intval($i[0]['id'])
- );
- create_tags_from_item($i[0]['id']);
- }
- }
- }
- }
-
- if($item['uri'] == $item['parent-uri']) {
- $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
- `body` = '', `title` = ''
- WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc($when),
- dbesc(datetime_convert()),
- dbesc($item['uri']),
- intval($importer['importer_uid'])
- );
- create_tags_from_itemuri($item['uri'], $importer['importer_uid']);
- create_files_from_itemuri($item['uri'], $importer['importer_uid']);
- update_thread_uri($item['uri'], $importer['importer_uid']);
- }
- else {
- $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
- `body` = '', `title` = ''
- WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($when),
- dbesc(datetime_convert()),
- dbesc($uri),
- intval($importer['importer_uid'])
- );
- create_tags_from_itemuri($uri, $importer['importer_uid']);
- create_files_from_itemuri($uri, $importer['importer_uid']);
- update_thread_uri($uri, $importer['importer_uid']);
- if($item['last-child']) {
- // ensure that last-child is set in case the comment that had it just got wiped.
- q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
- dbesc(datetime_convert()),
- dbesc($item['parent-uri']),
- intval($item['uid'])
- );
- // who is the last child now?
- $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
- ORDER BY `created` DESC LIMIT 1",
- dbesc($item['parent-uri']),
- intval($importer['importer_uid'])
- );
- if(count($r)) {
- q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
- intval($r[0]['id'])
- );
- }
- }
- // if this is a relayed delete, propagate it to other recipients
-
- if($is_a_remote_delete)
- proc_run('php',"include/notifier.php","drop",$item['id']);
- }
- }
- }
- }
- }
-
-
- foreach($feed->get_items() as $item) {
-
- $is_reply = false;
- $item_id = $item->get_id();
- $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
- if(isset($rawthread[0]['attribs']['']['ref'])) {
- $is_reply = true;
- $parent_uri = $rawthread[0]['attribs']['']['ref'];
- }
-
- if($is_reply) {
- $community = false;
-
- if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
- $sql_extra = '';
- $community = true;
- logger('local_delivery: possible community reply');
- }
- else
- $sql_extra = " and contact.self = 1 and item.wall = 1 ";
-
- // was the top-level post for this reply written by somebody on this site?
- // Specifically, the recipient?
-
- $is_a_remote_comment = false;
- $top_uri = $parent_uri;
-
- $r = q("select `item`.`parent-uri` from `item`
- WHERE `item`.`uri` = '%s'
- LIMIT 1",
- dbesc($parent_uri)
- );
- if($r && count($r)) {
- $top_uri = $r[0]['parent-uri'];
-
- // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
- $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
- `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
- INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
- WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
- AND `item`.`uid` = %d
- $sql_extra
- LIMIT 1",
- dbesc($top_uri),
- dbesc($top_uri),
- dbesc($top_uri),
- intval($importer['importer_uid'])
- );
- if($r && count($r))
- $is_a_remote_comment = true;
- }
-
- // Does this have the characteristics of a community or private group comment?
- // If it's a reply to a wall post on a community/prvgroup page it's a
- // valid community comment. Also forum_mode makes it valid for sure.
- // If neither, it's not.
-
- if($is_a_remote_comment && $community) {
- if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
- $is_a_remote_comment = false;
- logger('local_delivery: not a community reply');
- }
- }
-
- if($is_a_remote_comment) {
- logger('local_delivery: received remote comment');
- $is_like = false;
- // remote reply to our post. Import and then notify everybody else.
-
- $datarray = get_atom_elements($feed, $item);
-
- $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
-
- // Update content if 'updated' changes
-
- if(count($r)) {
- $iid = $r[0]['id'];
- if (edited_timestamp_is_newer($r[0], $datarray)) {
-
- // do not accept (ignore) an earlier edit than one we currently have.
- if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
- continue;
-
- logger('received updated comment' , LOGGER_DEBUG);
- $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($datarray['title']),
- dbesc($datarray['body']),
- dbesc($datarray['tag']),
- dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
- create_tags_from_itemuri($item_id, $importer['importer_uid']);
-
- proc_run('php',"include/notifier.php","comment-import",$iid);
-
- }
-
- continue;
- }
-
-
-
- $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
- intval($importer['importer_uid'])
- );
-
-
- $datarray['type'] = 'remote-comment';
- $datarray['wall'] = 1;
- $datarray['parent-uri'] = $parent_uri;
- $datarray['uid'] = $importer['importer_uid'];
- $datarray['owner-name'] = $own[0]['name'];
- $datarray['owner-link'] = $own[0]['url'];
- $datarray['owner-avatar'] = $own[0]['thumb'];
- $datarray['contact-id'] = $importer['id'];
-
- if(($datarray['verb'] === ACTIVITY_LIKE)
- || ($datarray['verb'] === ACTIVITY_DISLIKE)
- || ($datarray['verb'] === ACTIVITY_ATTEND)
- || ($datarray['verb'] === ACTIVITY_ATTENDNO)
- || ($datarray['verb'] === ACTIVITY_ATTENDMAYBE)) {
- $is_like = true;
- $datarray['type'] = 'activity';
- $datarray['gravity'] = GRAVITY_LIKE;
- $datarray['last-child'] = 0;
- // only one like or dislike per person
- // splitted into two queries for performance issues
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
- intval($datarray['uid']),
- dbesc($datarray['author-link']),
- dbesc($datarray['verb']),
- dbesc($datarray['parent-uri'])
- );
- if($r && count($r))
- continue;
-
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
- intval($datarray['uid']),
- dbesc($datarray['author-link']),
- dbesc($datarray['verb']),
- dbesc($datarray['parent-uri'])
-
- );
- if($r && count($r))
- continue;
- }
-
- if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
-
- $xo = parse_xml_string($datarray['object'],false);
- $xt = parse_xml_string($datarray['target'],false);
-
- if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
-
- // fetch the parent item
-
- $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
- dbesc($xt->id),
- intval($importer['importer_uid'])
- );
- if(! count($tagp))
- continue;
-
- // extract tag, if not duplicate, and this user allows tags, add to parent item
-
- if($xo->id && $xo->content) {
- $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
- if(! (stristr($tagp[0]['tag'],$newtag))) {
- $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
- intval($importer['importer_uid'])
- );
- if(count($i) && ! intval($i[0]['blocktags'])) {
- q("UPDATE item SET tag = '%s', `edited` = '%s', `changed` = '%s' WHERE id = %d",
- dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
- intval($tagp[0]['id']),
- dbesc(datetime_convert()),
- dbesc(datetime_convert())
- );
- create_tags_from_item($tagp[0]['id']);
- }
- }
- }
- }
- }
-
-
- $posted_id = item_store($datarray);
- $parent = 0;
-
- if($posted_id) {
-
- $datarray["id"] = $posted_id;
-
- $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
- intval($posted_id),
- intval($importer['importer_uid'])
- );
- if(count($r)) {
- $parent = $r[0]['parent'];
- $parent_uri = $r[0]['parent-uri'];
- }
-
- if(! $is_like) {
- $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
- dbesc(datetime_convert()),
- intval($importer['importer_uid']),
- intval($r[0]['parent'])
- );
-
- $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
- dbesc(datetime_convert()),
- intval($importer['importer_uid']),
- intval($posted_id)
- );
- }
-
- if($posted_id && $parent) {
-
- proc_run('php',"include/notifier.php","comment-import","$posted_id");
-
- if((! $is_like) && (! $importer['self'])) {
-
- require_once('include/enotify.php');
-
- notification(array(
- 'type' => NOTIFY_COMMENT,
- 'notify_flags' => $importer['notify-flags'],
- 'language' => $importer['language'],
- 'to_name' => $importer['username'],
- 'to_email' => $importer['email'],
- 'uid' => $importer['importer_uid'],
- 'item' => $datarray,
- 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($posted_id)),
- 'source_name' => stripslashes($datarray['author-name']),
- 'source_link' => $datarray['author-link'],
- 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
- ? $importer['thumb'] : $datarray['author-avatar']),
- 'verb' => ACTIVITY_POST,
- 'otype' => 'item',
- 'parent' => $parent,
- 'parent_uri' => $parent_uri,
- ));
-
- }
- }
-
- return 0;
- // NOTREACHED
- }
- }
- else {
-
- // regular comment that is part of this total conversation. Have we seen it? If not, import it.
-
- $item_id = $item->get_id();
- $datarray = get_atom_elements($feed,$item);
-
- if($importer['rel'] == CONTACT_IS_FOLLOWER)
- continue;
-
- $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
-
- // Update content if 'updated' changes
-
- if(count($r)) {
- if (edited_timestamp_is_newer($r[0], $datarray)) {
-
- // do not accept (ignore) an earlier edit than one we currently have.
- if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
- continue;
-
- $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($datarray['title']),
- dbesc($datarray['body']),
- dbesc($datarray['tag']),
- dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
- create_tags_from_itemuri($item_id, $importer['importer_uid']);
- }
-
- // update last-child if it changes
-
- $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
- if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
- $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
- dbesc(datetime_convert()),
- dbesc($parent_uri),
- intval($importer['importer_uid'])
- );
- $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- intval($allow[0]['data']),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
- }
- continue;
- }
-
- $datarray['parent-uri'] = $parent_uri;
- $datarray['uid'] = $importer['importer_uid'];
- $datarray['contact-id'] = $importer['id'];
- if(($datarray['verb'] === ACTIVITY_LIKE)
- || ($datarray['verb'] === ACTIVITY_DISLIKE)
- || ($datarray['verb'] === ACTIVITY_ATTEND)
- || ($datarray['verb'] === ACTIVITY_ATTENDNO)
- || ($datarray['verb'] === ACTIVITY_ATTENDMAYBE)) {
- $datarray['type'] = 'activity';
- $datarray['gravity'] = GRAVITY_LIKE;
- // only one like or dislike per person
- // splitted into two queries for performance issues
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
- intval($datarray['uid']),
- dbesc($datarray['author-link']),
- dbesc($datarray['verb']),
- dbesc($datarray['parent-uri'])
- );
- if($r && count($r))
- continue;
-
- $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
- intval($datarray['uid']),
- dbesc($datarray['author-link']),
- dbesc($datarray['verb']),
- dbesc($datarray['parent-uri'])
- );
- if($r && count($r))
- continue;
-
- }
-
- if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
-
- $xo = parse_xml_string($datarray['object'],false);
- $xt = parse_xml_string($datarray['target'],false);
-
- if($xt->type == ACTIVITY_OBJ_NOTE) {
- $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
- dbesc($xt->id),
- intval($importer['importer_uid'])
- );
- if(! count($r))
- continue;
-
- // extract tag, if not duplicate, add to parent item
- if($xo->content) {
- if(! (stristr($r[0]['tag'],trim($xo->content)))) {
- q("UPDATE item SET tag = '%s' WHERE id = %d",
- dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
- intval($r[0]['id'])
- );
- create_tags_from_item($r[0]['id']);
- }
- }
- }
- }
-
- $posted_id = item_store($datarray);
-
- // find out if our user is involved in this conversation and wants to be notified.
-
- if(!x($datarray['type']) || $datarray['type'] != 'activity') {
-
- $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
- dbesc($top_uri),
- intval($importer['importer_uid'])
- );
-
- if(count($myconv)) {
- $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
-
- // first make sure this isn't our own post coming back to us from a wall-to-wall event
- if(! link_compare($datarray['author-link'],$importer_url)) {
-
-
- foreach($myconv as $conv) {
-
- // now if we find a match, it means we're in this conversation
-
- if(! link_compare($conv['author-link'],$importer_url))
- continue;
-
- require_once('include/enotify.php');
-
- $conv_parent = $conv['parent'];
-
- notification(array(
- 'type' => NOTIFY_COMMENT,
- 'notify_flags' => $importer['notify-flags'],
- 'language' => $importer['language'],
- 'to_name' => $importer['username'],
- 'to_email' => $importer['email'],
- 'uid' => $importer['importer_uid'],
- 'item' => $datarray,
- 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($posted_id)),
- 'source_name' => stripslashes($datarray['author-name']),
- 'source_link' => $datarray['author-link'],
- 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
- ? $importer['thumb'] : $datarray['author-avatar']),
- 'verb' => ACTIVITY_POST,
- 'otype' => 'item',
- 'parent' => $conv_parent,
- 'parent_uri' => $parent_uri
-
- ));
-
- // only send one notification
- break;
- }
- }
- }
- }
- continue;
- }
- }
-
- else {
-
- // Head post of a conversation. Have we seen it? If not, import it.
-
-
- $item_id = $item->get_id();
- $datarray = get_atom_elements($feed,$item);
-
- if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
- $ev = bbtoevent($datarray['body']);
- if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
- $ev['cid'] = $importer['id'];
- $ev['uid'] = $importer['uid'];
- $ev['uri'] = $item_id;
- $ev['edited'] = $datarray['edited'];
- $ev['private'] = $datarray['private'];
- $ev['guid'] = $datarray['guid'];
-
- $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['uid'])
- );
- if(count($r))
- $ev['id'] = $r[0]['id'];
- $xyz = event_store($ev);
- continue;
- }
- }
-
- $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
-
- // Update content if 'updated' changes
-
- if(count($r)) {
- if (edited_timestamp_is_newer($r[0], $datarray)) {
-
- // do not accept (ignore) an earlier edit than one we currently have.
- if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
- continue;
-
- $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- dbesc($datarray['title']),
- dbesc($datarray['body']),
- dbesc($datarray['tag']),
- dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
- create_tags_from_itemuri($item_id, $importer['importer_uid']);
- update_thread_uri($item_id, $importer['importer_uid']);
- }
-
- // update last-child if it changes
-
- $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
- if($allow && $allow[0]['data'] != $r[0]['last-child']) {
- $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
- intval($allow[0]['data']),
- dbesc(datetime_convert()),
- dbesc($item_id),
- intval($importer['importer_uid'])
- );
- }
- continue;
- }
-
- $datarray['parent-uri'] = $item_id;
- $datarray['uid'] = $importer['importer_uid'];
- $datarray['contact-id'] = $importer['id'];
-
-
- if(! link_compare($datarray['owner-link'],$importer['url'])) {
- // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
- // but otherwise there's a possible data mixup on the sender's system.
- // the tgroup delivery code called from item_store will correct it if it's a forum,
- // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
- logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
- $datarray['owner-name'] = $importer['senderName'];
- $datarray['owner-link'] = $importer['url'];
- $datarray['owner-avatar'] = $importer['thumb'];
- }
-
- if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
- continue;
-
- // This is my contact on another system, but it's really me.
- // Turn this into a wall post.
- $notify = item_is_remote_self($importer, $datarray);
-
- $posted_id = item_store($datarray, false, $notify);
-
- if(stristr($datarray['verb'],ACTIVITY_POKE)) {
- $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
- if(! $verb)
- continue;
- $xo = parse_xml_string($datarray['object'],false);
-
- if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
-
- // somebody was poked/prodded. Was it me?
-
- $links = parse_xml_string("".unxmlify($xo->link)."",false);
-
- foreach($links->link as $l) {
- $atts = $l->attributes();
- switch($atts['rel']) {
- case "alternate":
- $Blink = $atts['href'];
- break;
- default:
- break;
- }
- }
- if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
-
- // send a notification
- require_once('include/enotify.php');
-
- notification(array(
- 'type' => NOTIFY_POKE,
- 'notify_flags' => $importer['notify-flags'],
- 'language' => $importer['language'],
- 'to_name' => $importer['username'],
- 'to_email' => $importer['email'],
- 'uid' => $importer['importer_uid'],
- 'item' => $datarray,
- 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($posted_id)),
- 'source_name' => stripslashes($datarray['author-name']),
- 'source_link' => $datarray['author-link'],
- 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
- ? $importer['thumb'] : $datarray['author-avatar']),
- 'verb' => $datarray['verb'],
- 'otype' => 'person',
- 'activity' => $verb,
- 'parent' => $datarray['parent']
- ));
- }
- }
- }
-
- continue;
- }
- }
-
- return 0;
- // NOTREACHED
-
-}
-
-
function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
$url = notags(trim($datarray['author-link']));
$name = notags(trim($datarray['author-name']));
@@ -4287,7 +1458,7 @@ function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
}
}
-function lose_follower($importer,$contact,$datarray,$item) {
+function lose_follower($importer,$contact,$datarray = array(),$item = "") {
if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
@@ -4300,7 +1471,7 @@ function lose_follower($importer,$contact,$datarray,$item) {
}
}
-function lose_sharer($importer,$contact,$datarray,$item) {
+function lose_sharer($importer,$contact,$datarray = array(),$item = "") {
if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
@@ -4313,7 +1484,6 @@ function lose_sharer($importer,$contact,$datarray,$item) {
}
}
-
function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
$a = get_app();
@@ -4356,189 +1526,6 @@ function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
}
-
-function atom_author($tag,$name,$uri,$h,$w,$photo,$geo) {
- $o = '';
- if(! $tag)
- return $o;
- $name = xmlify($name);
- $uri = xmlify($uri);
- $h = intval($h);
- $w = intval($w);
- $photo = xmlify($photo);
-
-
- $o .= "<$tag>\r\n";
- $o .= "\t$name\r\n";
- $o .= "\t$uri\r\n";
- $o .= "\t".'' . "\r\n";
- $o .= "\t".'' . "\r\n";
-
- if ($tag == "author") {
-
- if($geo)
- $o .= ''.xmlify($geo).''."\r\n";
-
- $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
- `profile`.`name`, `profile`.`pub_keywords`, `profile`.`about`,
- `profile`.`homepage`,`contact`.`nick` FROM `profile`
- INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
- INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
- WHERE `profile`.`is-default` AND `contact`.`self` AND
- NOT `user`.`hidewall` AND `contact`.`nurl`='%s'",
- dbesc(normalise_link($uri)));
- if ($r) {
- $location = '';
- if($r[0]['locality'])
- $location .= $r[0]['locality'];
- if($r[0]['region']) {
- if($location)
- $location .= ', ';
- $location .= $r[0]['region'];
- }
- if($r[0]['country-name']) {
- if($location)
- $location .= ', ';
- $location .= $r[0]['country-name'];
- }
-
- $o .= "\t".xmlify($r[0]["nick"])."\r\n";
- $o .= "\t".xmlify($r[0]["name"])."\r\n";
- $o .= "\t".xmlify(bbcode($r[0]["about"]))."\r\n";
- $o .= "\t\r\n";
- $o .= "\t\t".xmlify($location)."\r\n";
- $o .= "\t\r\n";
- $o .= "\t\r\n";
- $o .= "\thomepage\r\n";
- $o .= "\t\t".xmlify($r[0]["homepage"])."\r\n";
- $o .= "\t\ttrue\r\n";
- $o .= "\t\r\n";
- }
- }
-
- call_hooks('atom_author', $o);
-
- $o .= "$tag>\r\n";
- return $o;
-}
-
-function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
-
- $a = get_app();
-
- if(! $item['parent'])
- return;
-
- if($item['deleted'])
- return '' . "\r\n";
-
-
- if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
- $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
- else
- $body = $item['body'];
-
-
- $o = "\r\n\r\n\r\n";
-
- if(is_array($author))
- $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb'], $item['coord']);
- else
- $o .= atom_author('author',(($item['author-name']) ? $item['author-name'] : $item['name']),(($item['author-link']) ? $item['author-link'] : $item['url']),80,80,(($item['author-avatar']) ? $item['author-avatar'] : $item['thumb']), $item['coord']);
- if(strlen($item['owner-name']))
- $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar'], $item['coord']);
-
- if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
- $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
- $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
- $o .= ''."\r\n";
- }
-
- $htmlbody = $body;
-
- if ($item['title'] != "")
- $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
-
- $htmlbody = bbcode($htmlbody, false, false, 7);
-
- $o .= '' . xmlify($item['uri']) . '' . "\r\n";
- $o .= '' . xmlify($item['title']) . '' . "\r\n";
- $o .= '' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '' . "\r\n";
- $o .= '' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '' . "\r\n";
- $o .= '' . base64url_encode($body, true) . '' . "\r\n";
- $o .= '' . xmlify((($type === 'html') ? $htmlbody : $body)) . '' . "\r\n";
- $o .= ''."\r\n";
-
- $o .= ''."\r\n";
-
- if($comment)
- $o .= '' . intval($item['last-child']) . '' . "\r\n";
-
- if($item['location']) {
- $o .= '' . xmlify($item['location']) . '' . "\r\n";
- $o .= '' . xmlify($item['location']) . '' . "\r\n";
- }
-
- if($item['coord'])
- $o .= '' . xmlify($item['coord']) . '' . "\r\n";
-
- if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
- $o .= '' . (($item['private']) ? $item['private'] : 1) . '' . "\r\n";
-
- if($item['extid'])
- $o .= '' . xmlify($item['extid']) . '' . "\r\n";
- if($item['bookmark'])
- $o .= 'true' . "\r\n";
-
- if($item['app'])
- $o .= '' . "\r\n";
-
- if($item['guid'])
- $o .= '' . $item['guid'] . '' . "\r\n";
-
- if($item['signed_text']) {
- $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
- $o .= '' . xmlify($sign) . '' . "\r\n";
- }
-
- $verb = construct_verb($item);
- $o .= '' . xmlify($verb) . '' . "\r\n";
- $actobj = construct_activity_object($item);
- if(strlen($actobj))
- $o .= $actobj;
- $actarg = construct_activity_target($item);
- if(strlen($actarg))
- $o .= $actarg;
-
- $tags = item_getfeedtags($item);
- if(count($tags)) {
- foreach($tags as $t)
- if (($type != 'html') OR ($t[0] != "@"))
- $o .= '' . "\r\n";
- }
-
- /// @TODO
- /// To support these elements, the API needs to be enhanced
- /// $o .= ''."\r\n";
- /// $o .= "\t".''."\r\n";
- /// $o .= "\t".''."\r\n";
-
- // Deactivated since it was meant only for OStatus
- //$o .= item_get_attachment($item);
-
- $o .= item_getfeedattach($item);
-
- $mentioned = get_mentions($item);
- if($mentioned)
- $o .= $mentioned;
-
- call_hooks('atom_entry', $o);
-
- $o .= '' . "\r\n";
-
- return $o;
-}
-
function fix_private_photos($s, $uid, $item = null, $cid = 0) {
if(get_config('system','disable_embedded'))
@@ -4642,7 +1629,6 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
return($new_body);
}
-
function has_permissions($obj) {
if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
return true;
@@ -4703,50 +1689,6 @@ function item_getfeedtags($item) {
return $ret;
}
-function item_get_attachment($item) {
- $o = "";
- $siteinfo = get_attached_data($item["body"]);
-
- switch($siteinfo["type"]) {
- case 'link':
- $o = ''."\r\n";
- break;
- case 'photo':
- $imgdata = get_photo_info($siteinfo["image"]);
- $o = ''."\r\n";
- break;
- case 'video':
- $o = ''."\r\n";
- break;
- default:
- break;
- }
-
- return $o;
-}
-
-function item_getfeedattach($item) {
- $ret = '';
- $arr = explode('[/attach],',$item['attach']);
- if(count($arr)) {
- foreach($arr as $r) {
- $matches = false;
- $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
- if($cnt) {
- $ret .= ' 0)) {
+ $r = q("SELECT prvkey FROM user WHERE uid = %d LIMIT 1",
+ intval($contact['uid'])
+ );
- if( $r)
- $authorsig = base64_encode(rsa_sign($signed_text,$r['prvkey'],'sha256'));
+ if($r)
+ $authorsig = base64_encode(rsa_sign($signed_text,$r[0]['prvkey'],'sha256'));
}
if(! isset($authorsig))
@@ -329,6 +338,10 @@ function store_diaspora_like_sig($activity, $post_type, $contact, $post_id) {
$contact_baseurl = substr($contact['url'], $contact_baseurl_start, $contact_baseurl_length);
$diaspora_handle = $contact['nick'] . '@' . $contact_baseurl;
+
+ // This code could never had worked (the return values form the queries were used in a wrong way.
+ // Additionally it is needlessly complicated. Either the contact is owner or not. And we have this data already.
+/*
// Get contact's private key if he's a user of the local Friendica server
$r = q("SELECT `contact`.`uid` FROM `contact` WHERE `url` = '%s' AND `self` = 1 LIMIT 1",
dbesc($contact['url'])
@@ -343,6 +356,17 @@ function store_diaspora_like_sig($activity, $post_type, $contact, $post_id) {
if( $r)
$contact_uprvkey = $r['prvkey'];
}
+*/
+
+ // Is the contact the owner? Then fetch the private key
+ if ($contact['self'] AND ($contact['uid'] > 0)) {
+ $r = q("SELECT prvkey FROM user WHERE uid = %d LIMIT 1",
+ intval($contact['uid'])
+ );
+
+ if($r)
+ $contact_uprvkey = $r[0]['prvkey'];
+ }
$r = q("SELECT guid, parent FROM `item` WHERE id = %d LIMIT 1",
intval($post_id)
@@ -353,7 +377,7 @@ function store_diaspora_like_sig($activity, $post_type, $contact, $post_id) {
intval($r[0]['parent'])
);
if( $p) {
- $signed_text = $r[0]['guid'] . ';Post;' . $p[0]['guid'] . ';true;' . $diaspora_handle;
+ $signed_text = 'true;'.$r[0]['guid'].';Post;'.$p[0]['guid'].';'.$diaspora_handle;
if(isset($contact_uprvkey))
$authorsig = base64_encode(rsa_sign($signed_text,$contact_uprvkey,'sha256'));
diff --git a/include/network.php b/include/network.php
index ac5191b25..c6379e407 100644
--- a/include/network.php
+++ b/include/network.php
@@ -42,6 +42,7 @@ if(!function_exists('z_fetch_url')){
* @return array an assoziative array with:
* * \e int \b return_code => HTTP return code or 0 if timeout or failure
* * \e boolean \b success => boolean true (if HTTP 2xx result) or false
+ * * \e string \b redirect_url => in case of redirect, content was finally retrieved from this URL
* * \e string \b header => HTTP headers
* * \e string \b body => fetched content
*/
@@ -116,6 +117,9 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
// if it throws any errors.
$s = @curl_exec($ch);
+ if (curl_errno($ch) !== CURLE_OK) {
+ logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
+ }
$base = $s;
$curl_info = @curl_getinfo($ch);
@@ -133,6 +137,10 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
$base = substr($base,strlen($chunk));
}
+ $a->set_curl_code($http_code);
+ $a->set_curl_content_type($curl_info['content_type']);
+ $a->set_curl_headers($header);
+
if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
$new_location_info = @parse_url($curl_info["redirect_url"]);
$old_location_info = @parse_url($curl_info["url"]);
@@ -160,13 +168,13 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
$a->set_curl_content_type($curl_info['content_type']);
$body = substr($s,strlen($header));
- $a->set_curl_headers($header);
$rc = intval($http_code);
$ret['return_code'] = $rc;
$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
+ $ret['redirect_url'] = $url;
if(! $ret['success']) {
$ret['error'] = curl_error($ch);
$ret['debug'] = $curl_info;
@@ -1246,6 +1254,9 @@ function original_url($url, $depth=1, $fetchbody = false) {
$a->save_timestamp($stamp1, "network");
+ if ($http_code == 0)
+ return($url);
+
if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
if ($curl_info['redirect_url'] != "")
diff --git a/include/notifier.php b/include/notifier.php
index 92e48c355..6c42f19c6 100644
--- a/include/notifier.php
+++ b/include/notifier.php
@@ -535,7 +535,7 @@ function notifier_run(&$argv, &$argc){
if($public_message) {
- if (!$followup)
+ if (!$followup AND $top_level)
$r0 = diaspora_fetch_relay();
else
$r0 = array();
diff --git a/include/oembed.php b/include/oembed.php
index c848a4580..b1770f689 100755
--- a/include/oembed.php
+++ b/include/oembed.php
@@ -13,7 +13,13 @@ function oembed_fetch_url($embedurl, $no_rich_type = false){
$a = get_app();
- $txt = Cache::get($a->videowidth . $embedurl);
+ $r = q("SELECT * FROM `oembed` WHERE `url` = '%s'",
+ dbesc(normalise_link($embedurl)));
+
+ if ($r)
+ $txt = $r[0]["content"];
+ else
+ $txt = Cache::get($a->videowidth . $embedurl);
// These media files should now be caught in bbcode.php
// left here as a fallback in case this is called from another source
@@ -66,8 +72,14 @@ function oembed_fetch_url($embedurl, $no_rich_type = false){
if ($txt[0]!="{")
$txt='{"type":"error"}';
- else //save in cache
+ else { //save in cache
+ $j = json_decode($txt);
+ if ($j->type != "error")
+ q("INSERT INTO `oembed` (`url`, `content`, `created`) VALUES ('%s', '%s', '%s')",
+ dbesc(normalise_link($embedurl)), dbesc($txt), dbesc(datetime_convert()));
+
Cache::set($a->videowidth . $embedurl,$txt, CACHE_DAY);
+ }
}
$j = json_decode($txt);
@@ -85,7 +97,7 @@ function oembed_fetch_url($embedurl, $no_rich_type = false){
// If fetching information doesn't work, then improve via internal functions
if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
require_once("mod/parse_url.php");
- $data = parseurl_getsiteinfo($embedurl, true, false);
+ $data = parseurl_getsiteinfo_cached($embedurl, true, false);
$j->type = $data["type"];
if ($j->type == "photo") {
diff --git a/include/onepoll.php b/include/onepoll.php
index 516f1dfd4..6fb191f73 100644
--- a/include/onepoll.php
+++ b/include/onepoll.php
@@ -27,7 +27,6 @@ function onepoll_run(&$argv, &$argc){
require_once('include/session.php');
require_once('include/datetime.php');
- require_once('library/simplepie/simplepie.inc');
require_once('include/items.php');
require_once('include/Contact.php');
require_once('include/email.php');
@@ -335,7 +334,9 @@ function onepoll_run(&$argv, &$argc){
if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
return;
- $xml = fetch_url($contact['poll']);
+ $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
+ $xml = fetch_url($contact['poll'], false, $redirects, 0, Null, $cookiejar);
+ unlink($cookiejar);
}
elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {
diff --git a/include/ostatus.php b/include/ostatus.php
index 1087596e2..00022f8c6 100644
--- a/include/ostatus.php
+++ b/include/ostatus.php
@@ -17,15 +17,6 @@ define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
define('OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS', 14400); // given in minutes
-define("NS_ATOM", "http://www.w3.org/2005/Atom");
-define("NS_THR", "http://purl.org/syndication/thread/1.0");
-define("NS_GEORSS", "http://www.georss.org/georss");
-define("NS_ACTIVITY", "http://activitystrea.ms/spec/1.0/");
-define("NS_MEDIA", "http://purl.org/syndication/atommedia");
-define("NS_POCO", "http://portablecontacts.net/spec/1.0");
-define("NS_OSTATUS", "http://ostatus.org/schema/1.0");
-define("NS_STATUSNET", "http://status.net/schema/api/1/");
-
function ostatus_check_follow_friends() {
$r = q("SELECT `uid`,`v` FROM `pconfig` WHERE `cat`='system' AND `k`='ostatus_legacy_contact' AND `v` != ''");
@@ -127,47 +118,57 @@ function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch)
$author["owner-link"] = $author["author-link"];
$author["owner-avatar"] = $author["author-avatar"];
- if ($r AND !$onlyfetch) {
+ // Only update the contacts if it is an OStatus contact
+ if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
// Update contact data
- $update_contact = ($r[0]['name-date'] < datetime_convert('','','now -12 hours'));
- if ($update_contact) {
+
+ $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
+ if ($value != "")
+ $contact["notify"] = $value;
+
+ $value = $xpath->evaluate('atom:author/uri/text()', $context)->item(0)->nodeValue;
+ if ($value != "")
+ $contact["alias"] = $value;
+
+ $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
+ if ($value != "")
+ $contact["name"] = $value;
+
+ $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
+ if ($value != "")
+ $contact["nick"] = $value;
+
+ $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
+ if ($value != "")
+ $contact["about"] = html2bbcode($value);
+
+ $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
+ if ($value != "")
+ $contact["location"] = $value;
+
+ if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["location"] != $r[0]["location"])) {
+
logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
- $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
- if ($value != "")
- $contact["name"] = $value;
-
- $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
- if ($value != "")
- $contact["nick"] = $value;
-
- $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
- if ($value != "")
- $contact["about"] = html2bbcode($value);
-
- $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
- if ($value != "")
- $contact["location"] = $value;
-
- q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d AND `network` = '%s'",
+ q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
- dbesc(datetime_convert()), intval($contact["id"]), dbesc(NETWORK_OSTATUS));
+ dbesc(datetime_convert()), intval($contact["id"]));
poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
- "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
+ "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
}
- $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
-
- if ($update_photo AND isset($author["author-avatar"])) {
+ if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
- $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
-
- q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d AND `network` = '%s'",
- dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
- dbesc(datetime_convert()), intval($contact["id"]), dbesc(NETWORK_OSTATUS));
+ update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
}
+
+
+ /// @todo Add the "addr" field
+ $contact["generation"] = 2;
+ $contact["photo"] = $author["author-avatar"];
+ update_gcontact($contact);
}
return($author);
@@ -183,14 +184,14 @@ function ostatus_salmon_author($xml, $importer) {
@$doc->loadXML($xml);
$xpath = new DomXPath($doc);
- $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
- $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
- $xpath->registerNamespace('georss', "http://www.georss.org/georss");
- $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
- $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
- $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
- $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
- $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
+ $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
+ $xpath->registerNamespace('thr', NAMESPACE_THREAD);
+ $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
+ $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
+ $xpath->registerNamespace('media', NAMESPACE_MEDIA);
+ $xpath->registerNamespace('poco', NAMESPACE_POCO);
+ $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
+ $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
$entries = $xpath->query('/atom:entry');
@@ -214,14 +215,14 @@ function ostatus_import($xml,$importer,&$contact, &$hub) {
@$doc->loadXML($xml);
$xpath = new DomXPath($doc);
- $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
- $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
- $xpath->registerNamespace('georss', "http://www.georss.org/georss");
- $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
- $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
- $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
- $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
- $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
+ $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
+ $xpath->registerNamespace('thr', NAMESPACE_THREAD);
+ $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
+ $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
+ $xpath->registerNamespace('media', NAMESPACE_MEDIA);
+ $xpath->registerNamespace('poco', NAMESPACE_POCO);
+ $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
+ $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
$gub = "";
$hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
@@ -546,29 +547,6 @@ function ostatus_import($xml,$importer,&$contact, &$hub) {
}
logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
- $item["id"] = $item_id;
-
- if ($mention) {
- $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
- $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
-
- notification(array(
- 'type' => NOTIFY_TAGSELF,
- 'notify_flags' => $u[0]["notify-flags"],
- 'language' => $u[0]["language"],
- 'to_name' => $u[0]["username"],
- 'to_email' => $u[0]["email"],
- 'uid' => $item["uid"],
- 'item' => $item,
- 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
- 'source_name' => $item["author-name"],
- 'source_link' => $item["author-link"],
- 'source_photo' => $item["author-avatar"],
- 'verb' => ACTIVITY_TAG,
- 'otype' => 'item',
- 'parent' => $r[0]["parent"]
- ));
- }
}
}
@@ -1013,28 +991,6 @@ function ostatus_completion($conversation_url, $uid, $item = array()) {
// Add the conversation entry (but don't fetch the whole conversation)
ostatus_store_conversation($newitem, $conversation_url);
- if ($mention) {
- $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
- $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
-
- notification(array(
- 'type' => NOTIFY_TAGSELF,
- 'notify_flags' => $u[0]["notify-flags"],
- 'language' => $u[0]["language"],
- 'to_name' => $u[0]["username"],
- 'to_email' => $u[0]["email"],
- 'uid' => $uid,
- 'item' => $arr,
- 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
- 'source_name' => $arr["author-name"],
- 'source_link' => $arr["author-link"],
- 'source_photo' => $arr["author-avatar"],
- 'verb' => ACTIVITY_TAG,
- 'otype' => 'item',
- 'parent' => $r[0]["parent"]
- ));
- }
-
// If the newly created item is the top item then change the parent settings of the thread
// This shouldn't happen anymore. This is supposed to be absolote.
if ($arr["uri"] == $first_id) {
@@ -1109,7 +1065,7 @@ function get_reshared_guid($item) {
return $guid;
}
-function xml_add_element($doc, $parent, $element, $value = "", $attributes = array()) {
+function xml_create_element($doc, $element, $value = "", $attributes = array()) {
$element = $doc->createElement($element, xmlify($value));
foreach ($attributes AS $key => $value) {
@@ -1117,7 +1073,11 @@ function xml_add_element($doc, $parent, $element, $value = "", $attributes = arr
$attribute->value = xmlify($value);
$element->appendChild($attribute);
}
+ return $element;
+}
+function xml_add_element($doc, $parent, $element, $value = "", $attributes = array()) {
+ $element = xml_create_element($doc, $element, $value, $attributes);
$parent->appendChild($element);
}
@@ -1151,16 +1111,16 @@ function ostatus_format_picture_post($body) {
function ostatus_add_header($doc, $owner) {
$a = get_app();
- $root = $doc->createElementNS(NS_ATOM, 'feed');
+ $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
$doc->appendChild($root);
- $root->setAttribute("xmlns:thr", NS_THR);
- $root->setAttribute("xmlns:georss", NS_GEORSS);
- $root->setAttribute("xmlns:activity", NS_ACTIVITY);
- $root->setAttribute("xmlns:media", NS_MEDIA);
- $root->setAttribute("xmlns:poco", NS_POCO);
- $root->setAttribute("xmlns:ostatus", NS_OSTATUS);
- $root->setAttribute("xmlns:statusnet", NS_STATUSNET);
+ $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
+ $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
+ $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
+ $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
+ $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
+ $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
+ $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
$attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
@@ -1352,6 +1312,10 @@ function ostatus_add_author($doc, $owner) {
function ostatus_entry($doc, $item, $owner, $toplevel = false, $repeat = false) {
$a = get_app();
+ if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
+ logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
+ }
+
$is_repeat = false;
/* if (!$repeat) {
@@ -1374,15 +1338,15 @@ function ostatus_entry($doc, $item, $owner, $toplevel = false, $repeat = false)
$entry = $doc->createElement("activity:object");
$title = sprintf("New note by %s", $owner["nick"]);
} else {
- $entry = $doc->createElementNS(NS_ATOM, "entry");
+ $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
- $entry->setAttribute("xmlns:thr", NS_THR);
- $entry->setAttribute("xmlns:georss", NS_GEORSS);
- $entry->setAttribute("xmlns:activity", NS_ACTIVITY);
- $entry->setAttribute("xmlns:media", NS_MEDIA);
- $entry->setAttribute("xmlns:poco", NS_POCO);
- $entry->setAttribute("xmlns:ostatus", NS_OSTATUS);
- $entry->setAttribute("xmlns:statusnet", NS_STATUSNET);
+ $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
+ $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
+ $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
+ $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
+ $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
+ $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
+ $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
$author = ostatus_add_author($doc, $owner);
$entry->appendChild($author);
@@ -1447,9 +1411,12 @@ function ostatus_entry($doc, $item, $owner, $toplevel = false, $repeat = false)
$repeated_owner["about"] = "";
$repeated_owner["uid"] = 0;
- $r =q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", normalise_link($repeated_item["author-link"]));
+ // Fetch the missing data from the global contacts
+ $r =q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($repeated_item["author-link"]));
if ($r) {
- $repeated_owner["nick"] = $r[0]["nick"];
+ if ($r[0]["nick"] != "")
+ $repeated_owner["nick"] = $r[0]["nick"];
+
$repeated_owner["location"] = $r[0]["location"];
$repeated_owner["about"] = $r[0]["about"];
}
diff --git a/include/plaintext.php b/include/plaintext.php
index cb56850d4..05431bee2 100644
--- a/include/plaintext.php
+++ b/include/plaintext.php
@@ -90,6 +90,14 @@ function get_attached_data($body) {
$post["text"] = $body;
}
}
+
+ if (preg_match_all("(\[url\]([$URLSearchString]*)\[\/url\])ism", $body, $links, PREG_SET_ORDER)) {
+ if (count($links) == 1) {
+ $post["type"] = "text";
+ $post["url"] = $links[0][1];
+ $post["text"] = $body;
+ }
+ }
if (!isset($post["type"])) {
$post["type"] = "text";
$post["text"] = trim($body);
@@ -129,9 +137,17 @@ function plaintext($a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2) {
require_once("include/html2plain.php");
require_once("include/network.php");
+ // Remove the hash tags
+ $URLSearchString = "^\[\]";
+ $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $b["body"]);
+
+ // Add an URL element if the text contains a raw link
+ $body = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url]$2[/url]', $body);
+
// At first look at data that is attached via "type-..." stuff
// This will hopefully replaced with a dedicated bbcode later
- $post = get_attached_data($b["body"]);
+ //$post = get_attached_data($b["body"]);
+ $post = get_attached_data($body);
if (($b["title"] != "") AND ($post["text"] != ""))
$post["text"] = trim($b["title"]."\n\n".$post["text"]);
@@ -146,6 +162,8 @@ function plaintext($a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2) {
if ($includedlinks) {
if ($post["type"] == "link")
$link = $post["url"];
+ elseif ($post["type"] == "text")
+ $link = $post["url"];
elseif ($post["type"] == "video")
$link = $post["url"];
elseif ($post["type"] == "photo")
@@ -161,8 +179,22 @@ function plaintext($a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2) {
// But: if the link is beyond the limit, then it has to be added.
if (($link != "") AND strstr($msg, $link)) {
$pos = strpos($msg, $link);
- if (($limit == 0) OR ($pos < $limit))
+
+ // Will the text be shortened in the link?
+ // Or is the link the last item in the post?
+ if (($limit > 0) AND ($pos < $limit) AND (($pos + 23 > $limit) OR ($pos + strlen($link) == strlen($msg))))
+ $msg = trim(str_replace($link, "", $msg));
+ elseif (($limit == 0) OR ($pos < $limit)) {
+ // The limit has to be increased since it will be shortened - but not now
+ // Only do it with Twitter (htmlmode = 8)
+ if (($limit > 0) AND (strlen($link) > 23) AND ($htmlmode == 8))
+ $limit = $limit - 23 + strlen($link);
+
$link = "";
+
+ if ($post["type"] == "text")
+ unset($post["url"]);
+ }
}
}
@@ -178,7 +210,9 @@ function plaintext($a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2) {
if (iconv_strlen($msg, "UTF-8") > $limit) {
- if (!isset($post["url"])) {
+ if (($post["type"] == "text") AND isset($post["url"]))
+ $post["url"] = $b["plink"];
+ elseif (!isset($post["url"])) {
$limit = $limit - 23;
$post["url"] = $b["plink"];
} elseif (strpos($b["body"], "[share") !== false)
diff --git a/include/poller.php b/include/poller.php
index c681bfb38..90e94ede9 100644
--- a/include/poller.php
+++ b/include/poller.php
@@ -26,6 +26,9 @@ function poller_run(&$argv, &$argc){
unset($db_host, $db_user, $db_pass, $db_data);
};
+ if (poller_max_connections_reached())
+ return;
+
$load = current_load();
if($load) {
$maxsysload = intval(get_config('system','maxloadavg'));
@@ -39,8 +42,10 @@ function poller_run(&$argv, &$argc){
}
// Checking the number of workers
- if (poller_too_much_workers(1))
+ if (poller_too_much_workers(1)) {
+ poller_kill_stale_workers();
return;
+ }
if(($argc <= 1) OR ($argv[1] != "no_cron")) {
// Run the cron job that calls all other jobs
@@ -50,16 +55,7 @@ function poller_run(&$argv, &$argc){
proc_run("php","include/cronhooks.php");
// Cleaning dead processes
- $r = q("SELECT DISTINCT(`pid`) FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
- foreach($r AS $pid)
- if (!posix_kill($pid["pid"], 0))
- q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
- intval($pid["pid"]));
- else {
- /// @TODO Kill long running processes
- /// But: Update processes (like the database update) mustn't be killed
- }
-
+ poller_kill_stale_workers();
} else
// Sleep four seconds before checking for running processes again to avoid having too many workers
sleep(4);
@@ -72,6 +68,10 @@ function poller_run(&$argv, &$argc){
while ($r = q("SELECT * FROM `workerqueue` WHERE `executed` = '0000-00-00 00:00:00' ORDER BY `created` LIMIT 1")) {
+ // Constantly check the number of available database connections to let the frontend be accessible at any time
+ if (poller_max_connections_reached())
+ return;
+
// Count active workers and compare them with a maximum value that depends on the load
if (poller_too_much_workers(3))
return;
@@ -124,6 +124,107 @@ function poller_run(&$argv, &$argc){
}
+/**
+ * @brief Checks if the number of database connections has reached a critical limit.
+ *
+ * @return bool Are more than 3/4 of the maximum connections used?
+ */
+function poller_max_connections_reached() {
+
+ // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
+ $max = get_config("system", "max_connections");
+
+ if ($max == 0) {
+ // the maximum number of possible user connections can be a system variable
+ $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
+ if ($r)
+ $max = $r[0]["Value"];
+
+ // Or it can be granted. This overrides the system variable
+ $r = q("SHOW GRANTS");
+ if ($r)
+ foreach ($r AS $grants) {
+ $grant = array_pop($grants);
+ if (stristr($grant, "GRANT USAGE ON"))
+ if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match))
+ $max = $match[1];
+ }
+ }
+
+ // If $max is set we will use the processlist to determine the current number of connections
+ // The processlist only shows entries of the current user
+ if ($max != 0) {
+ $r = q("SHOW PROCESSLIST");
+ if (!$r)
+ return false;
+
+ $used = count($r);
+
+ logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
+
+ $level = $used / $max;
+
+ if ($level >= (3/4)) {
+ logger("Maximum level (3/4) of user connections reached: ".$used."/".$max);
+ return true;
+ }
+ }
+
+ // We will now check for the system values.
+ // This limit could be reached although the user limits are fine.
+ $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
+ if (!$r)
+ return false;
+
+ $max = intval($r[0]["Value"]);
+ if ($max == 0)
+ return false;
+
+ $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
+ if (!$r)
+ return false;
+
+ $used = intval($r[0]["Value"]);
+ if ($used == 0)
+ return false;
+
+ logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
+
+ $level = $used / $max;
+
+ if ($level < (3/4))
+ return false;
+
+ logger("Maximum level (3/4) of system connections reached: ".$used."/".$max);
+ return true;
+}
+
+/**
+ * @brief fix the queue entry if the worker process died
+ *
+ */
+function poller_kill_stale_workers() {
+ $r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
+ foreach($r AS $pid)
+ if (!posix_kill($pid["pid"], 0))
+ q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
+ intval($pid["pid"]));
+ else {
+ // Kill long running processes
+ $duration = (time() - strtotime($pid["executed"])) / 60;
+ if ($duration > 180) {
+ logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
+ posix_kill($pid["pid"], SIGTERM);
+
+ // Question: If a process is stale: Should we remove it or should we reschedule it?
+ // By now we rescheduling it. It's maybe not the wisest decision?
+ q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
+ intval($pid["pid"]));
+ } else
+ logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
+ }
+}
+
function poller_too_much_workers($stage) {
$queues = get_config("system", "worker_queues");
diff --git a/include/profile_update.php b/include/profile_update.php
index 0fcf3617f..7cc72cc86 100644
--- a/include/profile_update.php
+++ b/include/profile_update.php
@@ -3,6 +3,7 @@
require_once('include/datetime.php');
require_once('include/diaspora.php');
require_once('include/queue_fn.php');
+require_once('include/Contact.php');
function profile_change() {
@@ -53,19 +54,7 @@ function profile_change() {
$about = xmlify($profile['about']);
require_once('include/bbcode.php');
$about = xmlify(strip_tags(bbcode($about)));
- $location = '';
- if($profile['locality'])
- $location .= $profile['locality'];
- if($profile['region']) {
- if($location)
- $location .= ', ';
- $location .= $profile['region'];
- }
- if($profile['country-name']) {
- if($location)
- $location .= ', ';
- $location .= $profile['country-name'];
- }
+ $location = formatted_location($profile);
$location = xmlify($location);
$tags = '';
if($profile['pub_keywords']) {
diff --git a/include/queue.php b/include/queue.php
index cb5fe28ad..1525ca3ab 100644
--- a/include/queue.php
+++ b/include/queue.php
@@ -1,6 +1,7 @@
UTC_TIMESTAMP() - INTERVAL 12 HOUR && `last` < UTC_TIMESTAMP() - INTERVAL 15 MINUTE ) OR ( `last` < UTC_TIMESTAMP() - INTERVAL 1 HOUR ))");
+ $r = q("SELECT `id` FROM `queue` WHERE ((`created` > UTC_TIMESTAMP() - INTERVAL 12 HOUR && `last` < UTC_TIMESTAMP() - INTERVAL 15 MINUTE) OR (`last` < UTC_TIMESTAMP() - INTERVAL 1 HOUR)) ORDER BY `cid`, `created`");
}
if(! $r){
return;
@@ -116,7 +119,7 @@ function queue_run(&$argv, &$argc){
// so check again if this entry still needs processing
if($queue_id) {
- $qi = q("select * from queue where `id` = %d limit 1",
+ $qi = q("SELECT * FROM `queue` WHERE `id` = %d LIMIT 1",
intval($queue_id)
);
}
@@ -142,8 +145,18 @@ function queue_run(&$argv, &$argc){
continue;
}
- if (!poco_reachable($c[0]['url'])) {
- logger('queue: skipping probably dead url: ' . $c[0]['url']);
+ $server = poco_detect_server($c[0]['url']);
+
+ if (($server != "") AND !in_array($server, $serverlist)) {
+ logger("Check server ".$server." (".$c[0]["network"].")");
+ if (!poco_check_server($server, $c[0]["network"], true))
+ $deadservers[] = $server;
+
+ $serverlist[] = $server;
+ }
+
+ if (($server != "") AND in_array($server, $deadservers)) {
+ logger('queue: skipping known dead server: '.$server);
update_queue_time($q_item['id']);
continue;
}
@@ -166,37 +179,39 @@ function queue_run(&$argv, &$argc){
switch($contact['network']) {
case NETWORK_DFRN:
- logger('queue: dfrndelivery: item ' . $q_item['id'] . ' for ' . $contact['name']);
- $deliver_status = dfrn_deliver($owner,$contact,$data);
+ logger('queue: dfrndelivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>');
+ $deliver_status = dfrn::deliver($owner,$contact,$data);
if($deliver_status == (-1)) {
update_queue_time($q_item['id']);
$deadguys[] = $contact['notify'];
- }
- else {
+ } else
remove_queue_item($q_item['id']);
- }
+
break;
case NETWORK_OSTATUS:
if($contact['notify']) {
- logger('queue: slapdelivery: item ' . $q_item['id'] . ' for ' . $contact['name']);
+ logger('queue: slapdelivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>');
$deliver_status = slapper($owner,$contact['notify'],$data);
- if($deliver_status == (-1))
+ if($deliver_status == (-1)) {
update_queue_time($q_item['id']);
- else
+ $deadguys[] = $contact['notify'];
+ } else
remove_queue_item($q_item['id']);
}
break;
case NETWORK_DIASPORA:
if($contact['notify']) {
- logger('queue: diaspora_delivery: item ' . $q_item['id'] . ' for ' . $contact['name']);
+ logger('queue: diaspora_delivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>');
$deliver_status = diaspora_transmit($owner,$contact,$data,$public,true);
- if($deliver_status == (-1))
+ if($deliver_status == (-1)) {
update_queue_time($q_item['id']);
- else
+ $deadguys[] = $contact['notify'];
+ } else
remove_queue_item($q_item['id']);
+
}
break;
@@ -212,6 +227,7 @@ function queue_run(&$argv, &$argc){
break;
}
+ logger('Deliver status '.$deliver_status.' for item '.$q_item['id'].' to '.$contact['name'].' <'.$contact['url'].'>');
}
return;
diff --git a/include/remoteupdate.php b/include/remoteupdate.php
deleted file mode 100644
index 9effc9b6e..000000000
--- a/include/remoteupdate.php
+++ /dev/null
@@ -1,261 +0,0 @@
-tags as $i=>$v){
- $i = (float)$i;
- if ($i>$tag) $tag=$i;
- }
-
- if ($tag==0.0) return false;
- $f = fetch_url("https://raw.github.com/".F9KREPO."/".$tag."/boot.php","r");
- preg_match("|'FRIENDICA_VERSION', *'([^']*)'|", $f, $m);
- $version = $m[1];
-
- $lv = explode(".", FRIENDICA_VERSION);
- $rv = explode(".",$version);
- foreach($lv as $i=>$v){
- if ((int)$lv[$i] < (int)$rv[$i]) {
- return array($tag, $version, "https://github.com/friendica/friendica/zipball/".$tag);
- break;
- }
- }
- return false;
-}
-function canWeWrite(){
- $bd = dirname(dirname(__file__));
- return is_writable( $bd."/boot.php" );
-}
-
-function out($txt){ echo "§".$txt."§"; ob_end_flush(); flush();}
-
-function up_count($path){
-
- $file_count = 0;
-
- $dir_handle = opendir($path);
-
- if (!$dir_handle) return -1;
-
- while ($file = readdir($dir_handle)) {
-
- if ($file == '.' || $file == '..') continue;
- $file_count++;
-
- if (is_dir($path . $file)){
- $file_count += up_count($path . $file . DIRECTORY_SEPARATOR);
- }
-
- }
-
- closedir($dir_handle);
-
- return $file_count;
-}
-
-
-
-function up_unzip($file, $folder="/tmp"){
- $folder.="/";
- $zip = zip_open($file);
- if ($zip) {
- while ($zip_entry = zip_read($zip)) {
- $zip_entry_name = zip_entry_name($zip_entry);
- if (substr($zip_entry_name,strlen($zip_entry_name)-1,1)=="/"){
- mkdir($folder.$zip_entry_name,0777, true);
- } else {
- $fp = fopen($folder.$zip_entry_name, "w");
- if (zip_entry_open($zip, $zip_entry, "r")) {
- $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
- fwrite($fp,"$buf");
- zip_entry_close($zip_entry);
- fclose($fp);
- }
- }
- }
- zip_close($zip);
- }
-}
-
-/**
- * Walk recoursively in a folder and call a callback function on every
- * dir entry.
- * args:
- * $dir string base dir to walk
- * $callback function callback function
- * $sort int 0: ascending, 1: descending
- * $cb_argv any extra value passed to callback
- *
- * callback signature:
- * function name($fn, $dir [, $argv])
- * $fn string full dir entry name
- * $dir string start dir path
- * $argv any user value to callback
- *
- */
-function up_walktree($dir, $callback=Null, $sort=0, $cb_argv=Null , $startdir=Null){
- if (is_null($callback)) return;
- if (is_null($startdir)) $startdir = $dir;
- $res = scandir($dir, $sort);
- foreach($res as $i=>$v){
- if ($v!="." && $v!=".."){
- $fn = $dir."/".$v;
- if ($sort==0) $callback($fn, $startdir, $cb_argv);
- if (is_dir($fn)) up_walktree($fn, $callback, $sort, $cb_argv, $startdir);
- if ($sort==1) $callback($fn, $startdir, $cb_argv);
- }
- }
-
-}
-
-function up_copy($fn, $dir){
- global $up_countfiles, $up_totalfiles, $up_lastp;
- $up_countfiles++; $prc=(int)(((float)$up_countfiles/(float)$up_totalfiles)*100);
-
- if (strpos($fn, ".gitignore")>-1 || strpos($fn, ".htaccess")>-1) return;
- $ddest = dirname(dirname(__file__));
- $fd = str_replace($dir, $ddest, $fn);
-
- if (is_dir($fn) && !is_dir($fd)) {
- $re=mkdir($fd,0777,true);
- }
- if (!is_dir($fn)){
- $re=copy($fn, $fd);
- }
-
- if ($re===false) {
- out("ERROR. Abort.");
- killme();
- }
- out("copy@Copy@$prc%");
-}
-
-function up_ftp($fn, $dir, $argv){
- global $up_countfiles, $up_totalfiles, $up_lastp;
- $up_countfiles++; $prc=(int)(((float)$up_countfiles/(float)$up_totalfiles)*100);
-
- if (strpos($fn, ".gitignore")>-1 || strpos($fn, ".htaccess")>-1) return;
-
- list($ddest, $conn_id) = $argv;
- $l = strlen($ddest)-1;
- if (substr($ddest,$l,1)=="/") $ddest = substr($ddest,0,$l);
- $fd = str_replace($dir, $ddest, $fn);
-
- if (is_dir($fn)){
- if (ftp_nlist($conn_id, $fd)===false) {
- $ret = ftp_mkdir($conn_id, $fd);
- } else {
- $ret=true;
- }
- } else {
- $ret = ftp_put($conn_id, $fd, $fn, FTP_BINARY);
- }
- if (!$ret) {
- out("ERROR. Abort.");
- killme();
- }
- out("copy@Copy@$prc%");
-}
-
-function up_rm($fn, $dir){
- if (is_dir($fn)){
- rmdir($fn);
- } else {
- unlink($fn);
- }
-}
-
-function up_dlfile($url, $file) {
- $in = fopen ($url, "r");
- $out = fopen ($file, "w");
-
- $fs = filesize($url);
-
-
- if (!$in || !$out) return false;
-
- $s=0; $count=0;
- while (!feof ($in)) {
- $line = fgets ($in, 1024);
- fwrite( $out, $line);
-
- $count++; $s += strlen($line);
- if ($count==50){
- $count=0;
- $sp=$s/1024.0; $ex="Kb";
- if ($sp>1024) { $sp=$sp/1024; $ex="Mb"; }
- if ($sp>1024) { $sp=$sp/1024; $ex="Gb"; }
- $sp = ((int)($sp*100))/100;
- out("dwl@Download@".$sp.$ex);
- }
- }
- fclose($in);
- return true;
-}
-
-function doUpdate($remotefile, $ftpdata=false){
- global $up_totalfiles;
-
-
- $localtmpfile = tempnam("/tmp", "fk");
- out("dwl@Download@starting...");
- $rt= up_dlfile($remotefile, $localtmpfile);
- if ($rt==false || filesize($localtmpfile)==0){
- out("dwl@Download@ERROR.");
- unlink($localtmpfile);
- return;
- }
- out("dwl@Download@Ok.");
-
- out("unzip@Unzip@");
- $tmpdirname = $localfile."ex";
- mkdir($tmpdirname);
- up_unzip($localtmpfile, $tmpdirname);
- $basedir = glob($tmpdirname."/*"); $basedir=$basedir[0];
- out ("unzip@Unzip@Ok.");
-
- $up_totalfiles = up_count($basedir."/");
-
- if (canWeWrite()){
- out("copy@Copy@");
- up_walktree($basedir, 'up_copy');
- }
- if ($ftpdata!==false && is_array($ftpdata) && $ftpdata['ftphost']!="" ){
- out("ftpcon@Connect to FTP@");
- $conn_id = ftp_connect($ftpdata['ftphost']);
- $login_result = ftp_login($conn_id, $ftpdata['ftpuser'], $ftpdata['ftppwd']);
-
- if ((!$conn_id) || (!$login_result)) {
- out("ftpcon@Connect to FTP@FAILED");
- up_clean($tmpdirname, $localtmpfile);
- return;
- } else {
- out("ftpcon@Connect to FTP@Ok.");
- }
- out("copy@Copy@");
- up_walktree($basedir, 'up_ftp', 0, array( $ftpdata['ftppath'], $conn_id));
-
- ftp_close($conn_id);
- }
-
- up_clean($tmpdirname, $localtmpfile);
-
-}
-
-function up_clean($tmpdirname, $localtmpfile){
- out("clean@Clean up@");
- unlink($localtmpfile);
- up_walktree($tmpdirname, 'up_rm', 1);
- rmdir($tmpdirname);
- out("clean@Clean up@Ok.");
-}
diff --git a/include/socgraph.php b/include/socgraph.php
index 89b09515e..3b8e9140f 100644
--- a/include/socgraph.php
+++ b/include/socgraph.php
@@ -139,15 +139,16 @@ function poco_load($cid,$uid = 0,$zcid = 0,$url = null) {
poco_check($profile_url, $name, $network, $profile_photo, $about, $location, $gender, $keywords, $connect_url, $updated, $generation, $cid, $uid, $zcid);
// Update the Friendica contacts. Diaspora is doing it via a message. (See include/diaspora.php)
- if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
- q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
- WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
- dbesc($location),
- dbesc($about),
- dbesc($keywords),
- dbesc($gender),
- dbesc(normalise_link($profile_url)),
- dbesc(NETWORK_DFRN));
+ // Deactivated because we now update Friendica contacts in dfrn.php
+ //if (($location != "") OR ($about != "") OR ($keywords != "") OR ($gender != ""))
+ // q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s'
+ // WHERE `nurl` = '%s' AND NOT `self` AND `network` = '%s'",
+ // dbesc($location),
+ // dbesc($about),
+ // dbesc($keywords),
+ // dbesc($gender),
+ // dbesc(normalise_link($profile_url)),
+ // dbesc(NETWORK_DFRN));
}
logger("poco_load: loaded $total entries",LOGGER_DEBUG);
@@ -227,6 +228,8 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
$server_url = $x[0]["server_url"];
$nick = $x[0]["nick"];
$addr = $x[0]["addr"];
+ $alias = $x[0]["alias"];
+ $notify = $x[0]["notify"];
} else {
$created = "0000-00-00 00:00:00";
$server_url = "";
@@ -234,6 +237,8 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
$urlparts = parse_url($profile_url);
$nick = end(explode("/", $urlparts["path"]));
$addr = "";
+ $alias = "";
+ $notify = "";
}
if ((($network == "") OR ($name == "") OR ($addr == "") OR ($profile_photo == "") OR ($server_url == "") OR $alternate)
@@ -246,6 +251,8 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
$name = $data["name"];
$nick = $data["nick"];
$addr = $data["addr"];
+ $alias = $data["alias"];
+ $notify = $data["notify"];
$profile_url = $data["url"];
$profile_photo = $data["photo"];
$server_url = $data["baseurl"];
@@ -283,76 +290,25 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
poco_check_server($server_url, $network);
- if(count($x)) {
- $gcid = $x[0]['id'];
+ $gcontact = array("url" => $profile_url,
+ "addr" => $addr,
+ "alias" => $alias,
+ "name" => $name,
+ "network" => $network,
+ "photo" => $profile_photo,
+ "about" => $about,
+ "location" => $location,
+ "gender" => $gender,
+ "keywords" => $keywords,
+ "server_url" => $server_url,
+ "connect" => $connect_url,
+ "notify" => $notify,
+ "updated" => $updated,
+ "generation" => $generation);
- if (($location == "") AND ($x[0]['location'] != ""))
- $location = $x[0]['location'];
+ $gcid = update_gcontact($gcontact);
- if (($about == "") AND ($x[0]['about'] != ""))
- $about = $x[0]['about'];
-
- if (($gender == "") AND ($x[0]['gender'] != ""))
- $gender = $x[0]['gender'];
-
- if (($keywords == "") AND ($x[0]['keywords'] != ""))
- $keywords = $x[0]['keywords'];
-
- if (($addr == "") AND ($x[0]['addr'] != ""))
- $addr = $x[0]['addr'];
-
- if (($generation == 0) AND ($x[0]['generation'] > 0))
- $generation = $x[0]['generation'];
-
- if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
- q("UPDATE `gcontact` SET `name` = '%s', `addr` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
- `updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d
- WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
- dbesc($name),
- dbesc($addr),
- dbesc($network),
- dbesc($profile_photo),
- dbesc($connect_url),
- dbesc($profile_url),
- dbesc($server_url),
- dbesc($updated),
- dbesc($location),
- dbesc($about),
- dbesc($keywords),
- dbesc($gender),
- intval($generation),
- intval($generation),
- dbesc(normalise_link($profile_url))
- );
- }
- } else {
- q("INSERT INTO `gcontact` (`name`, `nick`, `addr`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `generation`)
- VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
- dbesc($name),
- dbesc($nick),
- dbesc($addr),
- dbesc($network),
- dbesc($profile_url),
- dbesc(normalise_link($profile_url)),
- dbesc($profile_photo),
- dbesc($connect_url),
- dbesc($server_url),
- dbesc(datetime_convert()),
- dbesc($updated),
- dbesc($location),
- dbesc($about),
- dbesc($keywords),
- dbesc($gender),
- intval($generation)
- );
- $x = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
- dbesc(normalise_link($profile_url))
- );
- if(count($x))
- $gcid = $x[0]['id'];
- }
-
- if(! $gcid)
+ if(!$gcid)
return $gcid;
$r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
@@ -379,13 +335,6 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
);
}
- // For unknown reasons there are sometimes duplicates
- q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
- NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
- dbesc(normalise_link($profile_url)),
- intval($gcid)
- );
-
return $gcid;
}
@@ -698,6 +647,10 @@ function poco_to_boolean($val) {
function poco_check_server($server_url, $network = "", $force = false) {
+ // Unify the server address
+ $server_url = trim($server_url, "/");
+ $server_url = str_replace("/index.php", "", $server_url);
+
if ($server_url == "")
return false;
@@ -769,17 +722,23 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Test for Diaspora
$serverret = z_fetch_url($server_url);
- $lines = explode("\n",$serverret["header"]);
- if(count($lines))
- foreach($lines as $line) {
- $line = trim($line);
- if(stristr($line,'X-Diaspora-Version:')) {
- $platform = "Diaspora";
- $version = trim(str_replace("X-Diaspora-Version:", "", $line));
- $version = trim(str_replace("x-diaspora-version:", "", $version));
- $network = NETWORK_DIASPORA;
+ if (!$serverret["success"] OR ($serverret["body"] == ""))
+ $failure = true;
+ else {
+ $lines = explode("\n",$serverret["header"]);
+ if(count($lines))
+ foreach($lines as $line) {
+ $line = trim($line);
+ if(stristr($line,'X-Diaspora-Version:')) {
+ $platform = "Diaspora";
+ $version = trim(str_replace("X-Diaspora-Version:", "", $line));
+ $version = trim(str_replace("x-diaspora-version:", "", $version));
+ $network = NETWORK_DIASPORA;
+ $versionparts = explode("-", $version);
+ $version = $versionparts[0];
+ }
}
- }
+ }
}
if (!$failure) {
@@ -1290,18 +1249,30 @@ function poco_discover_federation() {
return;
}
+ // Discover Friendica, Hubzilla and Diaspora servers
$serverdata = fetch_url("http://the-federation.info/pods.json");
- if (!$serverdata)
- return;
+ if ($serverdata) {
+ $servers = json_decode($serverdata);
- $servers = json_decode($serverdata);
+ foreach($servers->pods AS $server)
+ poco_check_server("https://".$server->host);
+ }
- foreach($servers->pods AS $server)
- poco_check_server("https://".$server->host);
+ // Discover GNU Social Servers
+ if (!get_config('system','ostatus_disabled')) {
+ $serverdata = "http://gstools.org/api/get_open_instances/";
+
+ $result = z_fetch_url($serverdata);
+ if ($result["success"]) {
+ $servers = json_decode($result["body"]);
+
+ foreach($servers->data AS $server)
+ poco_check_server($server->instance_address);
+ }
+ }
set_config('poco','last_federation_discovery', time());
-
}
function poco_discover($complete = false) {
@@ -1481,4 +1452,214 @@ function poco_discover_server($data, $default_generation = 0) {
}
return $success;
}
+
+/**
+ * @brief Fetch the gcontact id, add an entry if not existed
+ *
+ * @param arr $contact contact array
+ * @return bool|int Returns false if not found, integer if contact was found
+ */
+function get_gcontact_id($contact) {
+
+ $gcontact_id = 0;
+
+ if ($contact["network"] == NETWORK_STATUSNET)
+ $contact["network"] = NETWORK_OSTATUS;
+
+ $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
+ dbesc(normalise_link($contact["url"])));
+
+ if ($r)
+ $gcontact_id = $r[0]["id"];
+ else {
+ q("INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `generation`)
+ VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
+ dbesc($contact["name"]),
+ dbesc($contact["nick"]),
+ dbesc($contact["addr"]),
+ dbesc($contact["network"]),
+ dbesc($contact["url"]),
+ dbesc(normalise_link($contact["url"])),
+ dbesc($contact["photo"]),
+ dbesc(datetime_convert()),
+ dbesc(datetime_convert()),
+ dbesc($contact["location"]),
+ dbesc($contact["about"]),
+ intval($contact["generation"])
+ );
+
+ $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
+ dbesc(normalise_link($contact["url"])));
+
+ if ($r)
+ $gcontact_id = $r[0]["id"];
+ }
+
+ if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
+ q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
+ dbesc(normalise_link($contact["url"])),
+ intval($gcontact_id));
+
+ return $gcontact_id;
+}
+
+/**
+ * @brief Updates the gcontact table from a given array
+ *
+ * @param arr $contact contact array
+ * @return bool|int Returns false if not found, integer if contact was found
+ */
+function update_gcontact($contact) {
+
+ /// @todo update contact table as well
+
+ $gcontact_id = get_gcontact_id($contact);
+
+ if (!$gcontact_id)
+ return false;
+
+ $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
+ `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
+ FROM `gcontact` WHERE `id` = %d LIMIT 1",
+ intval($gcontact_id));
+
+ // Get all field names
+ $fields = array();
+ foreach ($r[0] AS $field => $data)
+ $fields[$field] = $data;
+
+ unset($fields["url"]);
+ unset($fields["updated"]);
+
+ // assign all unassigned fields from the database entry
+ foreach ($fields AS $field => $data)
+ if (!isset($contact[$field]))
+ $contact[$field] = $r[0][$field];
+
+ if ($contact["network"] == NETWORK_STATUSNET)
+ $contact["network"] = NETWORK_OSTATUS;
+
+ if (!isset($contact["updated"]))
+ $contact["updated"] = datetime_convert();
+
+ // Check if any field changed
+ $update = false;
+ unset($fields["generation"]);
+
+ foreach ($fields AS $field => $data)
+ if ($contact[$field] != $r[0][$field])
+ $update = true;
+
+ if ($contact["generation"] < $r[0]["generation"])
+ $update = true;
+
+ if ($update) {
+ q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
+ `birthday` = '%s', `gender` = '%s', `keywords` = '%s', `hide` = %d, `nsfw` = %d,
+ `alias` = '%s', `notify` = '%s', `url` = '%s',
+ `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
+ `server_url` = '%s', `connect` = '%s'
+ WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
+ dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
+ dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
+ dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
+ intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
+ dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
+ intval($contact["generation"]), dbesc($contact["updated"]),
+ dbesc($contact["server_url"]), dbesc($contact["connect"]),
+ dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
+ }
+
+ return $gcontact_id;
+}
+
+/**
+ * @brief Updates the gcontact entry from probe
+ *
+ * @param str $url profile link
+ */
+function update_gcontact_from_probe($url) {
+ $data = probe_url($url);
+
+ if ($data["network"] != NETWORK_PHANTOM)
+ update_gcontact($data);
+}
+
+/**
+ * @brief Fetches users of given GNU Social server
+ *
+ * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
+ *
+ * @param str $server Server address
+ */
+function gs_fetch_users($server) {
+
+ logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
+
+ $a = get_app();
+
+ $url = $server."/main/statistics";
+
+ $result = z_fetch_url($url);
+ if (!$result["success"])
+ return false;
+
+ $statistics = json_decode($result["body"]);
+
+ if (is_object($statistics->config)) {
+ if ($statistics->config->instance_with_ssl)
+ $server = "https://";
+ else
+ $server = "http://";
+
+ $server .= $statistics->config->instance_address;
+
+ $hostname = $statistics->config->instance_address;
+ } else {
+ if ($statistics->instance_with_ssl)
+ $server = "https://";
+ else
+ $server = "http://";
+
+ $server .= $statistics->instance_address;
+
+ $hostname = $statistics->instance_address;
+ }
+
+ if (is_object($statistics->users))
+ foreach ($statistics->users AS $nick => $user) {
+ $profile_url = $server."/".$user->nickname;
+
+ $contact = array("url" => $profile_url,
+ "name" => $user->fullname,
+ "addr" => $user->nickname."@".$hostname,
+ "nick" => $user->nickname,
+ "about" => $user->bio,
+ "network" => NETWORK_OSTATUS,
+ "photo" => $a->get_baseurl()."/images/person-175.jpg");
+ get_gcontact_id($contact);
+ }
+}
+
+/**
+ * @brief Asking GNU Social server on a regular base for their user data
+ *
+ */
+function gs_discover() {
+
+ $requery_days = intval(get_config("system", "poco_requery_days"));
+
+ $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
+
+ $r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
+ dbesc(NETWORK_OSTATUS), dbesc($last_update));
+
+ if (!$r)
+ return;
+
+ foreach ($r AS $server) {
+ gs_fetch_users($server["url"]);
+ q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
+ }
+}
?>
diff --git a/include/text.php b/include/text.php
index 1b03c39d2..c7681a4d5 100644
--- a/include/text.php
+++ b/include/text.php
@@ -20,10 +20,10 @@ function replace_macros($s,$r) {
$stamp1 = microtime(true);
$a = get_app();
-
+
// pass $baseurl to all templates
- $r['$baseurl'] = z_root();
-
+ $r['$baseurl'] = $a->get_baseurl();
+
$t = $a->template_engine();
try {
@@ -829,35 +829,6 @@ function qp($s) {
return str_replace ("%","=",rawurlencode($s));
}}
-
-
-if(! function_exists('get_mentions')) {
-/**
- * @param array $item
- * @return string html for mentions #FIXME: remove html
- */
-function get_mentions($item) {
- $o = '';
- if(! strlen($item['tag']))
- return $o;
-
- $arr = explode(',',$item['tag']);
- foreach($arr as $x) {
- $matches = null;
- if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
- $o .= "\t\t" . '' . "\r\n";
- $o .= "\t\t" . '' . "\r\n";
- }
- }
-
- if (!$item['private']) {
- $o .= "\t\t".''."\r\n";
- $o .= "\t\t".''."\r\n";
- }
-
- return $o;
-}}
-
if(! function_exists('contact_block')) {
/**
* Get html for contact block.
@@ -895,9 +866,9 @@ function contact_block() {
$micropro = Null;
} else {
- $r = q("SELECT * FROM `contact`
- WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0
- AND `hidden` = 0 AND `archive` = 0
+ $r = q("SELECT `id`, `uid`, `addr`, `url`, `name`, `micro`, `network` FROM `contact`
+ WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending`
+ AND NOT `hidden` AND NOT `archive`
AND `network` IN ('%s', '%s', '%s') ORDER BY RAND() LIMIT %d",
intval($a->profile['uid']),
dbesc(NETWORK_DFRN),
@@ -1415,7 +1386,14 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$item['hashtags'] = $hashtags;
$item['mentions'] = $mentions;
- put_item_in_cache($item, true);
+ // Update the cached values if there is no "zrl=..." on the links
+ $update = (!local_user() and !remote_user() and ($item["uid"] == 0));
+
+ // Or update it if the current viewer is the intented viewer
+ if (($item["uid"] == local_user()) AND ($item["uid"] != 0))
+ $update = true;
+
+ put_item_in_cache($item, $update);
$s = $item["rendered-html"];
$prep_arr = array('item' => $item, 'html' => $s, 'preview' => $preview);
@@ -1526,7 +1504,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$pos = strpos($s, $spoilersearch);
$rnd = random_string(8);
- $spoilerreplace = ' '.sprintf(t('Click to open/close')).''.
+ $spoilerreplace = ' '.sprintf(t('Click to open/close')).''.
'
<%}%>'},initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx}),this.datasets=[],this.buildScale(t),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(e,n){var o;this.scale.animation||(o=this.scale.getPointPosition(n,this.scale.calculateCenterOffset(e))),s.points.push(new this.PointClass({value:e,label:t.labels[n],datasetLabel:i.label,x:this.options.animation?this.scale.xCenter:o.x,y:this.options.animation?this.scale.yCenter:o.y,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this)},this),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=e.getRelativePosition(t),s=e.getAngleFromPoint({x:this.scale.xCenter,y:this.scale.yCenter},i),n=2*Math.PI/this.scale.valuesCount,o=Math.round((s.angle-1.5*Math.PI)/n),a=[];return(o>=this.scale.valuesCount||0>o)&&(o=0),s.distance<=this.scale.drawingArea&&e.each(this.datasets,function(t){a.push(t.points[o])}),a},buildScale:function(t){this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,angleLineColor:this.options.angleLineColor,angleLineWidth:this.options.angleShowLineOut?this.options.angleLineWidth:0,pointLabelFontColor:this.options.pointLabelFontColor,pointLabelFontSize:this.options.pointLabelFontSize,pointLabelFontFamily:this.options.pointLabelFontFamily,pointLabelFontStyle:this.options.pointLabelFontStyle,height:this.chart.height,width:this.chart.width,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,labels:t.labels,valuesCount:t.datasets[0].data.length}),this.scale.setScaleSize(),this.updateScaleRange(t.datasets),this.scale.buildYLabels()},updateScaleRange:function(t){var i=function(){var i=[];return e.each(t,function(t){t.data?i=i.concat(t.data):e.each(t.points,function(t){i.push(t.value)})}),i}(),s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s)},addData:function(t,i){this.scale.valuesCount++,e.each(t,function(t,e){var s=this.scale.getPointPosition(this.scale.valuesCount,this.scale.calculateCenterOffset(t));this.datasets[e].points.push(new this.PointClass({value:t,label:i,x:s.x,y:s.y,strokeColor:this.datasets[e].pointStrokeColor,fillColor:this.datasets[e].pointColor}))},this),this.scale.labels.push(i),this.reflow(),this.update()},removeData:function(){this.scale.valuesCount--,this.scale.labels.shift(),e.each(this.datasets,function(t){t.points.shift()},this),this.reflow(),this.update()},update:function(){this.eachPoints(function(t){t.save()}),this.reflow(),this.render()},reflow:function(){e.extend(this.scale,{width:this.chart.width,height:this.chart.height,size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2}),this.updateScaleRange(this.datasets),this.scale.setScaleSize(),this.scale.buildYLabels()},draw:function(t){var i=t||1,s=this.chart.ctx;this.clear(),this.scale.draw(),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.hasValue()&&t.transition(this.scale.getPointPosition(e,this.scale.calculateCenterOffset(t.value)),i)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(t,i){0===i?s.moveTo(t.x,t.y):s.lineTo(t.x,t.y)},this),s.closePath(),s.stroke(),s.fillStyle=t.fillColor,s.fill(),e.each(t.points,function(t){t.hasValue()&&t.draw()})},this)}})}.call(this);
\ No newline at end of file
diff --git a/library/Chart.js-1.0.2/LICENSE.md b/library/Chart.js-1.0.2/LICENSE.md
new file mode 100644
index 000000000..e10bc0ff1
--- /dev/null
+++ b/library/Chart.js-1.0.2/LICENSE.md
@@ -0,0 +1,7 @@
+Copyright (c) 2013-2015 Nick Downie
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/library/Chart.js-1.0.2/README.md b/library/Chart.js-1.0.2/README.md
new file mode 100644
index 000000000..7c4fa8bf6
--- /dev/null
+++ b/library/Chart.js-1.0.2/README.md
@@ -0,0 +1,20 @@
+# Chart.js
+
+[![Build Status](https://travis-ci.org/nnnick/Chart.js.svg?branch=master)](https://travis-ci.org/nnnick/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)
+
+
+*Simple HTML5 Charts using the canvas element* [chartjs.org](http://www.chartjs.org)
+
+## Documentation
+
+You can find documentation at [chartjs.org/docs](http://www.chartjs.org/docs/). The markdown files that build the site are available under `/docs`. Please note - in some of the json examples of configuration you might notice some liquid tags - this is just for the generating the site html, please disregard.
+
+## Bugs, issues and contributing
+
+Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/nnnick/Chart.js/blob/master/CONTRIBUTING.md) first.
+
+For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chartjs).
+
+## License
+
+Chart.js is available under the [MIT license](http://opensource.org/licenses/MIT).
diff --git a/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php b/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php
deleted file mode 100644
index 292c040d4..000000000
--- a/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php
+++ /dev/null
@@ -1,21 +0,0 @@
- 1.0) $result = '1';
- return $result;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php b/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php
deleted file mode 100644
index 6599c5b2d..000000000
--- a/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php
+++ /dev/null
@@ -1,28 +0,0 @@
-def = $def;
- $this->element = $element;
- }
- /**
- * Checks if CurrentToken is set and equal to $this->element
- */
- public function validate($string, $config, $context) {
- $token = $context->get('CurrentToken', true);
- if ($token && $token->name == $this->element) return false;
- return $this->def->validate($string, $config, $context);
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/CSS/FontFamily.php b/library/HTMLPurifier/AttrDef/CSS/FontFamily.php
deleted file mode 100644
index 42c2054c2..000000000
--- a/library/HTMLPurifier/AttrDef/CSS/FontFamily.php
+++ /dev/null
@@ -1,72 +0,0 @@
- true,
- 'sans-serif' => true,
- 'monospace' => true,
- 'fantasy' => true,
- 'cursive' => true
- );
-
- // assume that no font names contain commas in them
- $fonts = explode(',', $string);
- $final = '';
- foreach($fonts as $font) {
- $font = trim($font);
- if ($font === '') continue;
- // match a generic name
- if (isset($generic_names[$font])) {
- $final .= $font . ', ';
- continue;
- }
- // match a quoted name
- if ($font[0] === '"' || $font[0] === "'") {
- $length = strlen($font);
- if ($length <= 2) continue;
- $quote = $font[0];
- if ($font[$length - 1] !== $quote) continue;
- $font = substr($font, 1, $length - 2);
- }
-
- $font = $this->expandCSSEscape($font);
-
- // $font is a pure representation of the font name
-
- if (ctype_alnum($font) && $font !== '') {
- // very simple font, allow it in unharmed
- $final .= $font . ', ';
- continue;
- }
-
- // bugger out on whitespace. form feed (0C) really
- // shouldn't show up regardless
- $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font);
-
- // These ugly transforms don't pose a security
- // risk (as \\ and \" might). We could try to be clever and
- // use single-quote wrapping when there is a double quote
- // present, but I have choosen not to implement that.
- // (warning: this code relies on the selection of quotation
- // mark below)
- $font = str_replace('\\', '\\5C ', $font);
- $font = str_replace('"', '\\22 ', $font);
-
- // complicated font, requires quoting
- $final .= "\"$font\", "; // note that this will later get turned into "
- }
- $final = rtrim($final, ', ');
- if ($final === '') return false;
- return $final;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/CSS/Length.php b/library/HTMLPurifier/AttrDef/CSS/Length.php
deleted file mode 100644
index a07ec5813..000000000
--- a/library/HTMLPurifier/AttrDef/CSS/Length.php
+++ /dev/null
@@ -1,47 +0,0 @@
-min = $min !== null ? HTMLPurifier_Length::make($min) : null;
- $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;
- }
-
- public function validate($string, $config, $context) {
- $string = $this->parseCDATA($string);
-
- // Optimizations
- if ($string === '') return false;
- if ($string === '0') return '0';
- if (strlen($string) === 1) return false;
-
- $length = HTMLPurifier_Length::make($string);
- if (!$length->isValid()) return false;
-
- if ($this->min) {
- $c = $length->compareTo($this->min);
- if ($c === false) return false;
- if ($c < 0) return false;
- }
- if ($this->max) {
- $c = $length->compareTo($this->max);
- if ($c === false) return false;
- if ($c > 0) return false;
- }
-
- return $length->toString();
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/CSS/ListStyle.php b/library/HTMLPurifier/AttrDef/CSS/ListStyle.php
deleted file mode 100644
index 4406868c0..000000000
--- a/library/HTMLPurifier/AttrDef/CSS/ListStyle.php
+++ /dev/null
@@ -1,78 +0,0 @@
-getCSSDefinition();
- $this->info['list-style-type'] = $def->info['list-style-type'];
- $this->info['list-style-position'] = $def->info['list-style-position'];
- $this->info['list-style-image'] = $def->info['list-style-image'];
- }
-
- public function validate($string, $config, $context) {
-
- // regular pre-processing
- $string = $this->parseCDATA($string);
- if ($string === '') return false;
-
- // assumes URI doesn't have spaces in it
- $bits = explode(' ', strtolower($string)); // bits to process
-
- $caught = array();
- $caught['type'] = false;
- $caught['position'] = false;
- $caught['image'] = false;
-
- $i = 0; // number of catches
- $none = false;
-
- foreach ($bits as $bit) {
- if ($i >= 3) return; // optimization bit
- if ($bit === '') continue;
- foreach ($caught as $key => $status) {
- if ($status !== false) continue;
- $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);
- if ($r === false) continue;
- if ($r === 'none') {
- if ($none) continue;
- else $none = true;
- if ($key == 'image') continue;
- }
- $caught[$key] = $r;
- $i++;
- break;
- }
- }
-
- if (!$i) return false;
-
- $ret = array();
-
- // construct type
- if ($caught['type']) $ret[] = $caught['type'];
-
- // construct image
- if ($caught['image']) $ret[] = $caught['image'];
-
- // construct position
- if ($caught['position']) $ret[] = $caught['position'];
-
- if (empty($ret)) return false;
- return implode(' ', $ret);
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/CSS/Percentage.php b/library/HTMLPurifier/AttrDef/CSS/Percentage.php
deleted file mode 100644
index c34b8fc3c..000000000
--- a/library/HTMLPurifier/AttrDef/CSS/Percentage.php
+++ /dev/null
@@ -1,40 +0,0 @@
-number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);
- }
-
- public function validate($string, $config, $context) {
-
- $string = $this->parseCDATA($string);
-
- if ($string === '') return false;
- $length = strlen($string);
- if ($length === 1) return false;
- if ($string[$length - 1] !== '%') return false;
-
- $number = substr($string, 0, $length - 1);
- $number = $this->number_def->validate($number, $config, $context);
-
- if ($number === false) return false;
- return "$number%";
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/HTML/Bool.php b/library/HTMLPurifier/AttrDef/HTML/Bool.php
deleted file mode 100644
index e06987eb8..000000000
--- a/library/HTMLPurifier/AttrDef/HTML/Bool.php
+++ /dev/null
@@ -1,28 +0,0 @@
-name = $name;}
-
- public function validate($string, $config, $context) {
- if (empty($string)) return false;
- return $this->name;
- }
-
- /**
- * @param $string Name of attribute
- */
- public function make($string) {
- return new HTMLPurifier_AttrDef_HTML_Bool($string);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/HTML/Color.php b/library/HTMLPurifier/AttrDef/HTML/Color.php
deleted file mode 100644
index d01e20454..000000000
--- a/library/HTMLPurifier/AttrDef/HTML/Color.php
+++ /dev/null
@@ -1,32 +0,0 @@
-get('Core.ColorKeywords');
-
- $string = trim($string);
-
- if (empty($string)) return false;
- if (isset($colors[$string])) return $colors[$string];
- if ($string[0] === '#') $hex = substr($string, 1);
- else $hex = $string;
-
- $length = strlen($hex);
- if ($length !== 3 && $length !== 6) return false;
- if (!ctype_xdigit($hex)) return false;
- if ($length === 3) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
-
- return "#$hex";
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php b/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php
deleted file mode 100644
index ae6ea7c01..000000000
--- a/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php
+++ /dev/null
@@ -1,21 +0,0 @@
-valid_values === false) $this->valid_values = $config->get('Attr.AllowedFrameTargets');
- return parent::validate($string, $config, $context);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/HTML/ID.php b/library/HTMLPurifier/AttrDef/HTML/ID.php
deleted file mode 100644
index 81d03762d..000000000
--- a/library/HTMLPurifier/AttrDef/HTML/ID.php
+++ /dev/null
@@ -1,70 +0,0 @@
-get('Attr.EnableID')) return false;
-
- $id = trim($id); // trim it first
-
- if ($id === '') return false;
-
- $prefix = $config->get('Attr.IDPrefix');
- if ($prefix !== '') {
- $prefix .= $config->get('Attr.IDPrefixLocal');
- // prevent re-appending the prefix
- if (strpos($id, $prefix) !== 0) $id = $prefix . $id;
- } elseif ($config->get('Attr.IDPrefixLocal') !== '') {
- trigger_error('%Attr.IDPrefixLocal cannot be used unless '.
- '%Attr.IDPrefix is set', E_USER_WARNING);
- }
-
- //if (!$this->ref) {
- $id_accumulator =& $context->get('IDAccumulator');
- if (isset($id_accumulator->ids[$id])) return false;
- //}
-
- // we purposely avoid using regex, hopefully this is faster
-
- if (ctype_alpha($id)) {
- $result = true;
- } else {
- if (!ctype_alpha(@$id[0])) return false;
- $trim = trim( // primitive style of regexps, I suppose
- $id,
- 'A..Za..z0..9:-._'
- );
- $result = ($trim === '');
- }
-
- $regexp = $config->get('Attr.IDBlacklistRegexp');
- if ($regexp && preg_match($regexp, $id)) {
- return false;
- }
-
- if (/*!$this->ref && */$result) $id_accumulator->add($id);
-
- // if no change was made to the ID, return the result
- // else, return the new id if stripping whitespace made it
- // valid, or return false.
- return $result ? $id : false;
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/HTML/Length.php b/library/HTMLPurifier/AttrDef/HTML/Length.php
deleted file mode 100644
index a242f9c23..000000000
--- a/library/HTMLPurifier/AttrDef/HTML/Length.php
+++ /dev/null
@@ -1,41 +0,0 @@
- 100) return '100%';
-
- return ((string) $points) . '%';
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/HTML/MultiLength.php b/library/HTMLPurifier/AttrDef/HTML/MultiLength.php
deleted file mode 100644
index c72fc76e4..000000000
--- a/library/HTMLPurifier/AttrDef/HTML/MultiLength.php
+++ /dev/null
@@ -1,41 +0,0 @@
-max = $max;
- }
-
- public function validate($string, $config, $context) {
-
- $string = trim($string);
- if ($string === '0') return $string;
- if ($string === '') return false;
- $length = strlen($string);
- if (substr($string, $length - 2) == 'px') {
- $string = substr($string, 0, $length - 2);
- }
- if (!is_numeric($string)) return false;
- $int = (int) $string;
-
- if ($int < 0) return '0';
-
- // upper-bound value, extremely high values can
- // crash operating systems, see
- // WARNING, above link WILL crash you if you're using Windows
-
- if ($this->max !== null && $int > $this->max) return (string) $this->max;
-
- return (string) $int;
-
- }
-
- public function make($string) {
- if ($string === '') $max = null;
- else $max = (int) $string;
- $class = get_class($this);
- return new $class($max);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/Text.php b/library/HTMLPurifier/AttrDef/Text.php
deleted file mode 100644
index c6216cc53..000000000
--- a/library/HTMLPurifier/AttrDef/Text.php
+++ /dev/null
@@ -1,15 +0,0 @@
-parseCDATA($string);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/URI/Host.php b/library/HTMLPurifier/AttrDef/URI/Host.php
deleted file mode 100644
index 2156c10c6..000000000
--- a/library/HTMLPurifier/AttrDef/URI/Host.php
+++ /dev/null
@@ -1,62 +0,0 @@
-ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();
- $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();
- }
-
- public function validate($string, $config, $context) {
- $length = strlen($string);
- if ($string === '') return '';
- if ($length > 1 && $string[0] === '[' && $string[$length-1] === ']') {
- //IPv6
- $ip = substr($string, 1, $length - 2);
- $valid = $this->ipv6->validate($ip, $config, $context);
- if ($valid === false) return false;
- return '['. $valid . ']';
- }
-
- // need to do checks on unusual encodings too
- $ipv4 = $this->ipv4->validate($string, $config, $context);
- if ($ipv4 !== false) return $ipv4;
-
- // A regular domain name.
-
- // This breaks I18N domain names, but we don't have proper IRI support,
- // so force users to insert Punycode. If there's complaining we'll
- // try to fix things into an international friendly form.
-
- // The productions describing this are:
- $a = '[a-z]'; // alpha
- $an = '[a-z0-9]'; // alphanum
- $and = '[a-z0-9-]'; // alphanum | "-"
- // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
- $domainlabel = "$an($and*$an)?";
- // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
- $toplabel = "$a($and*$an)?";
- // hostname = *( domainlabel "." ) toplabel [ "." ]
- $match = preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string);
- if (!$match) return false;
-
- return $string;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrDef/URI/IPv6.php b/library/HTMLPurifier/AttrDef/URI/IPv6.php
deleted file mode 100644
index 9454e9be5..000000000
--- a/library/HTMLPurifier/AttrDef/URI/IPv6.php
+++ /dev/null
@@ -1,99 +0,0 @@
-ip4) $this->_loadRegex();
-
- $original = $aIP;
-
- $hex = '[0-9a-fA-F]';
- $blk = '(?:' . $hex . '{1,4})';
- $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128
-
- // prefix check
- if (strpos($aIP, '/') !== false)
- {
- if (preg_match('#' . $pre . '$#s', $aIP, $find))
- {
- $aIP = substr($aIP, 0, 0-strlen($find[0]));
- unset($find);
- }
- else
- {
- return false;
- }
- }
-
- // IPv4-compatiblity check
- if (preg_match('#(?<=:'.')' . $this->ip4 . '$#s', $aIP, $find))
- {
- $aIP = substr($aIP, 0, 0-strlen($find[0]));
- $ip = explode('.', $find[0]);
- $ip = array_map('dechex', $ip);
- $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];
- unset($find, $ip);
- }
-
- // compression check
- $aIP = explode('::', $aIP);
- $c = count($aIP);
- if ($c > 2)
- {
- return false;
- }
- elseif ($c == 2)
- {
- list($first, $second) = $aIP;
- $first = explode(':', $first);
- $second = explode(':', $second);
-
- if (count($first) + count($second) > 8)
- {
- return false;
- }
-
- while(count($first) < 8)
- {
- array_push($first, '0');
- }
-
- array_splice($first, 8 - count($second), 8, $second);
- $aIP = $first;
- unset($first,$second);
- }
- else
- {
- $aIP = explode(':', $aIP[0]);
- }
- $c = count($aIP);
-
- if ($c != 8)
- {
- return false;
- }
-
- // All the pieces should be 16-bit hex strings. Are they?
- foreach ($aIP as $piece)
- {
- if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece)))
- {
- return false;
- }
- }
-
- return $original;
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrTransform/BoolToCSS.php b/library/HTMLPurifier/AttrTransform/BoolToCSS.php
deleted file mode 100644
index 51159b671..000000000
--- a/library/HTMLPurifier/AttrTransform/BoolToCSS.php
+++ /dev/null
@@ -1,36 +0,0 @@
-attr = $attr;
- $this->css = $css;
- }
-
- public function transform($attr, $config, $context) {
- if (!isset($attr[$this->attr])) return $attr;
- unset($attr[$this->attr]);
- $this->prependCSS($attr, $this->css);
- return $attr;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrTransform/EnumToCSS.php b/library/HTMLPurifier/AttrTransform/EnumToCSS.php
deleted file mode 100644
index 2a5b4514a..000000000
--- a/library/HTMLPurifier/AttrTransform/EnumToCSS.php
+++ /dev/null
@@ -1,58 +0,0 @@
-attr = $attr;
- $this->enumToCSS = $enum_to_css;
- $this->caseSensitive = (bool) $case_sensitive;
- }
-
- public function transform($attr, $config, $context) {
-
- if (!isset($attr[$this->attr])) return $attr;
-
- $value = trim($attr[$this->attr]);
- unset($attr[$this->attr]);
-
- if (!$this->caseSensitive) $value = strtolower($value);
-
- if (!isset($this->enumToCSS[$value])) {
- return $attr;
- }
-
- $this->prependCSS($attr, $this->enumToCSS[$value]);
-
- return $attr;
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrTransform/Length.php b/library/HTMLPurifier/AttrTransform/Length.php
deleted file mode 100644
index ea2f30473..000000000
--- a/library/HTMLPurifier/AttrTransform/Length.php
+++ /dev/null
@@ -1,27 +0,0 @@
-name = $name;
- $this->cssName = $css_name ? $css_name : $name;
- }
-
- public function transform($attr, $config, $context) {
- if (!isset($attr[$this->name])) return $attr;
- $length = $this->confiscateAttr($attr, $this->name);
- if(ctype_digit($length)) $length .= 'px';
- $this->prependCSS($attr, $this->cssName . ":$length;");
- return $attr;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrTransform/Name.php b/library/HTMLPurifier/AttrTransform/Name.php
deleted file mode 100644
index 15315bc73..000000000
--- a/library/HTMLPurifier/AttrTransform/Name.php
+++ /dev/null
@@ -1,21 +0,0 @@
-get('HTML.Attr.Name.UseCDATA')) return $attr;
- if (!isset($attr['name'])) return $attr;
- $id = $this->confiscateAttr($attr, 'name');
- if ( isset($attr['id'])) return $attr;
- $attr['id'] = $id;
- return $attr;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrTransform/NameSync.php b/library/HTMLPurifier/AttrTransform/NameSync.php
deleted file mode 100644
index a95638c14..000000000
--- a/library/HTMLPurifier/AttrTransform/NameSync.php
+++ /dev/null
@@ -1,27 +0,0 @@
-idDef = new HTMLPurifier_AttrDef_HTML_ID();
- }
-
- public function transform($attr, $config, $context) {
- if (!isset($attr['name'])) return $attr;
- $name = $attr['name'];
- if (isset($attr['id']) && $attr['id'] === $name) return $attr;
- $result = $this->idDef->validate($name, $config, $context);
- if ($result === false) unset($attr['name']);
- else $attr['name'] = $result;
- return $attr;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/AttrTransform/SafeObject.php b/library/HTMLPurifier/AttrTransform/SafeObject.php
deleted file mode 100644
index 1ed74898b..000000000
--- a/library/HTMLPurifier/AttrTransform/SafeObject.php
+++ /dev/null
@@ -1,16 +0,0 @@
-
- */
-class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform
-{
-
- public function transform($attr, $config, $context) {
- // Calculated from Firefox
- if (!isset($attr['cols'])) $attr['cols'] = '22';
- if (!isset($attr['rows'])) $attr['rows'] = '3';
- return $attr;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/Bootstrap.php b/library/HTMLPurifier/Bootstrap.php
deleted file mode 100644
index 559f61a23..000000000
--- a/library/HTMLPurifier/Bootstrap.php
+++ /dev/null
@@ -1,98 +0,0 @@
-
-if (!defined('PHP_EOL')) {
- switch (strtoupper(substr(PHP_OS, 0, 3))) {
- case 'WIN':
- define('PHP_EOL', "\r\n");
- break;
- case 'DAR':
- define('PHP_EOL', "\r");
- break;
- default:
- define('PHP_EOL', "\n");
- }
-}
-
-/**
- * Bootstrap class that contains meta-functionality for HTML Purifier such as
- * the autoload function.
- *
- * @note
- * This class may be used without any other files from HTML Purifier.
- */
-class HTMLPurifier_Bootstrap
-{
-
- /**
- * Autoload function for HTML Purifier
- * @param $class Class to load
- */
- public static function autoload($class) {
- $file = HTMLPurifier_Bootstrap::getPath($class);
- if (!$file) return false;
- require HTMLPURIFIER_PREFIX . '/' . $file;
- return true;
- }
-
- /**
- * Returns the path for a specific class.
- */
- public static function getPath($class) {
- if (strncmp('HTMLPurifier', $class, 12) !== 0) return false;
- // Custom implementations
- if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) {
- $code = str_replace('_', '-', substr($class, 22));
- $file = 'HTMLPurifier/Language/classes/' . $code . '.php';
- } else {
- $file = str_replace('_', '/', $class) . '.php';
- }
- if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) return false;
- return $file;
- }
-
- /**
- * "Pre-registers" our autoloader on the SPL stack.
- */
- public static function registerAutoload() {
- $autoload = array('HTMLPurifier_Bootstrap', 'autoload');
- if ( ($funcs = spl_autoload_functions()) === false ) {
- spl_autoload_register($autoload);
- } elseif (function_exists('spl_autoload_unregister')) {
- $compat = version_compare(PHP_VERSION, '5.1.2', '<=') &&
- version_compare(PHP_VERSION, '5.1.0', '>=');
- foreach ($funcs as $func) {
- if (is_array($func)) {
- // :TRICKY: There are some compatibility issues and some
- // places where we need to error out
- $reflector = new ReflectionMethod($func[0], $func[1]);
- if (!$reflector->isStatic()) {
- throw new Exception('
- HTML Purifier autoloader registrar is not compatible
- with non-static object methods due to PHP Bug #44144;
- Please do not use HTMLPurifier.autoload.php (or any
- file that includes this file); instead, place the code:
- spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\'))
- after your own autoloaders.
- ');
- }
- // Suprisingly, spl_autoload_register supports the
- // Class::staticMethod callback format, although call_user_func doesn't
- if ($compat) $func = implode('::', $func);
- }
- spl_autoload_unregister($func);
- }
- spl_autoload_register($autoload);
- foreach ($funcs as $func) spl_autoload_register($func);
- }
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/CSSDefinition.php b/library/HTMLPurifier/CSSDefinition.php
deleted file mode 100644
index 6a2e6f56d..000000000
--- a/library/HTMLPurifier/CSSDefinition.php
+++ /dev/null
@@ -1,292 +0,0 @@
-info['text-align'] = new HTMLPurifier_AttrDef_Enum(
- array('left', 'right', 'center', 'justify'), false);
-
- $border_style =
- $this->info['border-bottom-style'] =
- $this->info['border-right-style'] =
- $this->info['border-left-style'] =
- $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum(
- array('none', 'hidden', 'dotted', 'dashed', 'solid', 'double',
- 'groove', 'ridge', 'inset', 'outset'), false);
-
- $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style);
-
- $this->info['clear'] = new HTMLPurifier_AttrDef_Enum(
- array('none', 'left', 'right', 'both'), false);
- $this->info['float'] = new HTMLPurifier_AttrDef_Enum(
- array('none', 'left', 'right'), false);
- $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum(
- array('normal', 'italic', 'oblique'), false);
- $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum(
- array('normal', 'small-caps'), false);
-
- $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite(
- array(
- new HTMLPurifier_AttrDef_Enum(array('none')),
- new HTMLPurifier_AttrDef_CSS_URI()
- )
- );
-
- $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum(
- array('inside', 'outside'), false);
- $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum(
- array('disc', 'circle', 'square', 'decimal', 'lower-roman',
- 'upper-roman', 'lower-alpha', 'upper-alpha', 'none'), false);
- $this->info['list-style-image'] = $uri_or_none;
-
- $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config);
-
- $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum(
- array('capitalize', 'uppercase', 'lowercase', 'none'), false);
- $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color();
-
- $this->info['background-image'] = $uri_or_none;
- $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum(
- array('repeat', 'repeat-x', 'repeat-y', 'no-repeat')
- );
- $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum(
- array('scroll', 'fixed')
- );
- $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition();
-
- $border_color =
- $this->info['border-top-color'] =
- $this->info['border-bottom-color'] =
- $this->info['border-left-color'] =
- $this->info['border-right-color'] =
- $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('transparent')),
- new HTMLPurifier_AttrDef_CSS_Color()
- ));
-
- $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config);
-
- $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color);
-
- $border_width =
- $this->info['border-top-width'] =
- $this->info['border-bottom-width'] =
- $this->info['border-left-width'] =
- $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')),
- new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative
- ));
-
- $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width);
-
- $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('normal')),
- new HTMLPurifier_AttrDef_CSS_Length()
- ));
-
- $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('normal')),
- new HTMLPurifier_AttrDef_CSS_Length()
- ));
-
- $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('xx-small', 'x-small',
- 'small', 'medium', 'large', 'x-large', 'xx-large',
- 'larger', 'smaller')),
- new HTMLPurifier_AttrDef_CSS_Percentage(),
- new HTMLPurifier_AttrDef_CSS_Length()
- ));
-
- $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('normal')),
- new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives
- new HTMLPurifier_AttrDef_CSS_Length('0'),
- new HTMLPurifier_AttrDef_CSS_Percentage(true)
- ));
-
- $margin =
- $this->info['margin-top'] =
- $this->info['margin-bottom'] =
- $this->info['margin-left'] =
- $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_CSS_Length(),
- new HTMLPurifier_AttrDef_CSS_Percentage(),
- new HTMLPurifier_AttrDef_Enum(array('auto'))
- ));
-
- $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin);
-
- // non-negative
- $padding =
- $this->info['padding-top'] =
- $this->info['padding-bottom'] =
- $this->info['padding-left'] =
- $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_CSS_Length('0'),
- new HTMLPurifier_AttrDef_CSS_Percentage(true)
- ));
-
- $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding);
-
- $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_CSS_Length(),
- new HTMLPurifier_AttrDef_CSS_Percentage()
- ));
-
- $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_CSS_Length('0'),
- new HTMLPurifier_AttrDef_CSS_Percentage(true),
- new HTMLPurifier_AttrDef_Enum(array('auto'))
- ));
- $max = $config->get('CSS.MaxImgLength');
-
- $this->info['width'] =
- $this->info['height'] =
- $max === null ?
- $trusted_wh :
- new HTMLPurifier_AttrDef_Switch('img',
- // For img tags:
- new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_CSS_Length('0', $max),
- new HTMLPurifier_AttrDef_Enum(array('auto'))
- )),
- // For everyone else:
- $trusted_wh
- );
-
- $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration();
-
- $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily();
-
- // this could use specialized code
- $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum(
- array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300',
- '400', '500', '600', '700', '800', '900'), false);
-
- // MUST be called after other font properties, as it references
- // a CSSDefinition object
- $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config);
-
- // same here
- $this->info['border'] =
- $this->info['border-bottom'] =
- $this->info['border-top'] =
- $this->info['border-left'] =
- $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);
-
- $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(array(
- 'collapse', 'separate'));
-
- $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(array(
- 'top', 'bottom'));
-
- $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum(array(
- 'auto', 'fixed'));
-
- $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
- new HTMLPurifier_AttrDef_Enum(array('baseline', 'sub', 'super',
- 'top', 'text-top', 'middle', 'bottom', 'text-bottom')),
- new HTMLPurifier_AttrDef_CSS_Length(),
- new HTMLPurifier_AttrDef_CSS_Percentage()
- ));
-
- $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);
-
- // partial support
- $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(array('nowrap'));
-
- if ($config->get('CSS.Proprietary')) {
- $this->doSetupProprietary($config);
- }
-
- if ($config->get('CSS.AllowTricky')) {
- $this->doSetupTricky($config);
- }
-
- $allow_important = $config->get('CSS.AllowImportant');
- // wrap all attr-defs with decorator that handles !important
- foreach ($this->info as $k => $v) {
- $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);
- }
-
- $this->setupConfigStuff($config);
- }
-
- protected function doSetupProprietary($config) {
- // Internet Explorer only scrollbar colors
- $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
- $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color();
- $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
- $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color();
- $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color();
- $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
-
- // technically not proprietary, but CSS3, and no one supports it
- $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
- $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
- $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
-
- // only opacity, for now
- $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter();
-
- }
-
- protected function doSetupTricky($config) {
- $this->info['display'] = new HTMLPurifier_AttrDef_Enum(array(
- 'inline', 'block', 'list-item', 'run-in', 'compact',
- 'marker', 'table', 'inline-table', 'table-row-group',
- 'table-header-group', 'table-footer-group', 'table-row',
- 'table-column-group', 'table-column', 'table-cell', 'table-caption', 'none'
- ));
- $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(array(
- 'visible', 'hidden', 'collapse'
- ));
- $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));
- }
-
-
- /**
- * Performs extra config-based processing. Based off of
- * HTMLPurifier_HTMLDefinition.
- * @todo Refactor duplicate elements into common class (probably using
- * composition, not inheritance).
- */
- protected function setupConfigStuff($config) {
-
- // setup allowed elements
- $support = "(for information on implementing this, see the ".
- "support forums) ";
- $allowed_attributes = $config->get('CSS.AllowedProperties');
- if ($allowed_attributes !== null) {
- foreach ($this->info as $name => $d) {
- if(!isset($allowed_attributes[$name])) unset($this->info[$name]);
- unset($allowed_attributes[$name]);
- }
- // emit errors
- foreach ($allowed_attributes as $name => $d) {
- // :TODO: Is this htmlspecialchars() call really necessary?
- $name = htmlspecialchars($name);
- trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING);
- }
- }
-
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/ChildDef/Optional.php b/library/HTMLPurifier/ChildDef/Optional.php
deleted file mode 100644
index 32bcb9898..000000000
--- a/library/HTMLPurifier/ChildDef/Optional.php
+++ /dev/null
@@ -1,26 +0,0 @@
-whitespace) return $tokens_of_children;
- else return array();
- }
- return $result;
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/ChildDef/Required.php b/library/HTMLPurifier/ChildDef/Required.php
deleted file mode 100644
index 4889f249b..000000000
--- a/library/HTMLPurifier/ChildDef/Required.php
+++ /dev/null
@@ -1,117 +0,0 @@
- $x) {
- $elements[$i] = true;
- if (empty($i)) unset($elements[$i]); // remove blank
- }
- }
- $this->elements = $elements;
- }
- public $allow_empty = false;
- public $type = 'required';
- public function validateChildren($tokens_of_children, $config, $context) {
- // Flag for subclasses
- $this->whitespace = false;
-
- // if there are no tokens, delete parent node
- if (empty($tokens_of_children)) return false;
-
- // the new set of children
- $result = array();
-
- // current depth into the nest
- $nesting = 0;
-
- // whether or not we're deleting a node
- $is_deleting = false;
-
- // whether or not parsed character data is allowed
- // this controls whether or not we silently drop a tag
- // or generate escaped HTML from it
- $pcdata_allowed = isset($this->elements['#PCDATA']);
-
- // a little sanity check to make sure it's not ALL whitespace
- $all_whitespace = true;
-
- // some configuration
- $escape_invalid_children = $config->get('Core.EscapeInvalidChildren');
-
- // generator
- $gen = new HTMLPurifier_Generator($config, $context);
-
- foreach ($tokens_of_children as $token) {
- if (!empty($token->is_whitespace)) {
- $result[] = $token;
- continue;
- }
- $all_whitespace = false; // phew, we're not talking about whitespace
-
- $is_child = ($nesting == 0);
-
- if ($token instanceof HTMLPurifier_Token_Start) {
- $nesting++;
- } elseif ($token instanceof HTMLPurifier_Token_End) {
- $nesting--;
- }
-
- if ($is_child) {
- $is_deleting = false;
- if (!isset($this->elements[$token->name])) {
- $is_deleting = true;
- if ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text) {
- $result[] = $token;
- } elseif ($pcdata_allowed && $escape_invalid_children) {
- $result[] = new HTMLPurifier_Token_Text(
- $gen->generateFromToken($token)
- );
- }
- continue;
- }
- }
- if (!$is_deleting || ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text)) {
- $result[] = $token;
- } elseif ($pcdata_allowed && $escape_invalid_children) {
- $result[] =
- new HTMLPurifier_Token_Text(
- $gen->generateFromToken($token)
- );
- } else {
- // drop silently
- }
- }
- if (empty($result)) return false;
- if ($all_whitespace) {
- $this->whitespace = true;
- return false;
- }
- if ($tokens_of_children == $result) return true;
- return $result;
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/ChildDef/StrictBlockquote.php b/library/HTMLPurifier/ChildDef/StrictBlockquote.php
deleted file mode 100644
index dfae8a6e5..000000000
--- a/library/HTMLPurifier/ChildDef/StrictBlockquote.php
+++ /dev/null
@@ -1,88 +0,0 @@
-init($config);
- return $this->fake_elements;
- }
-
- public function validateChildren($tokens_of_children, $config, $context) {
-
- $this->init($config);
-
- // trick the parent class into thinking it allows more
- $this->elements = $this->fake_elements;
- $result = parent::validateChildren($tokens_of_children, $config, $context);
- $this->elements = $this->real_elements;
-
- if ($result === false) return array();
- if ($result === true) $result = $tokens_of_children;
-
- $def = $config->getHTMLDefinition();
- $block_wrap_start = new HTMLPurifier_Token_Start($def->info_block_wrapper);
- $block_wrap_end = new HTMLPurifier_Token_End( $def->info_block_wrapper);
- $is_inline = false;
- $depth = 0;
- $ret = array();
-
- // assuming that there are no comment tokens
- foreach ($result as $i => $token) {
- $token = $result[$i];
- // ifs are nested for readability
- if (!$is_inline) {
- if (!$depth) {
- if (
- ($token instanceof HTMLPurifier_Token_Text && !$token->is_whitespace) ||
- (!$token instanceof HTMLPurifier_Token_Text && !isset($this->elements[$token->name]))
- ) {
- $is_inline = true;
- $ret[] = $block_wrap_start;
- }
- }
- } else {
- if (!$depth) {
- // starting tokens have been inline text / empty
- if ($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) {
- if (isset($this->elements[$token->name])) {
- // ended
- $ret[] = $block_wrap_end;
- $is_inline = false;
- }
- }
- }
- }
- $ret[] = $token;
- if ($token instanceof HTMLPurifier_Token_Start) $depth++;
- if ($token instanceof HTMLPurifier_Token_End) $depth--;
- }
- if ($is_inline) $ret[] = $block_wrap_end;
- return $ret;
- }
-
- private function init($config) {
- if (!$this->init) {
- $def = $config->getHTMLDefinition();
- // allow all inline elements
- $this->real_elements = $this->elements;
- $this->fake_elements = $def->info_content_sets['Flow'];
- $this->fake_elements['#PCDATA'] = true;
- $this->init = true;
- }
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/ChildDef/Table.php b/library/HTMLPurifier/ChildDef/Table.php
deleted file mode 100644
index 34f0227dd..000000000
--- a/library/HTMLPurifier/ChildDef/Table.php
+++ /dev/null
@@ -1,142 +0,0 @@
- true, 'tbody' => true, 'thead' => true,
- 'tfoot' => true, 'caption' => true, 'colgroup' => true, 'col' => true);
- public function __construct() {}
- public function validateChildren($tokens_of_children, $config, $context) {
- if (empty($tokens_of_children)) return false;
-
- // this ensures that the loop gets run one last time before closing
- // up. It's a little bit of a hack, but it works! Just make sure you
- // get rid of the token later.
- $tokens_of_children[] = false;
-
- // only one of these elements is allowed in a table
- $caption = false;
- $thead = false;
- $tfoot = false;
-
- // as many of these as you want
- $cols = array();
- $content = array();
-
- $nesting = 0; // current depth so we can determine nodes
- $is_collecting = false; // are we globbing together tokens to package
- // into one of the collectors?
- $collection = array(); // collected nodes
- $tag_index = 0; // the first node might be whitespace,
- // so this tells us where the start tag is
-
- foreach ($tokens_of_children as $token) {
- $is_child = ($nesting == 0);
-
- if ($token === false) {
- // terminating sequence started
- } elseif ($token instanceof HTMLPurifier_Token_Start) {
- $nesting++;
- } elseif ($token instanceof HTMLPurifier_Token_End) {
- $nesting--;
- }
-
- // handle node collection
- if ($is_collecting) {
- if ($is_child) {
- // okay, let's stash the tokens away
- // first token tells us the type of the collection
- switch ($collection[$tag_index]->name) {
- case 'tr':
- case 'tbody':
- $content[] = $collection;
- break;
- case 'caption':
- if ($caption !== false) break;
- $caption = $collection;
- break;
- case 'thead':
- case 'tfoot':
- // access the appropriate variable, $thead or $tfoot
- $var = $collection[$tag_index]->name;
- if ($$var === false) {
- $$var = $collection;
- } else {
- // transmutate the first and less entries into
- // tbody tags, and then put into content
- $collection[$tag_index]->name = 'tbody';
- $collection[count($collection)-1]->name = 'tbody';
- $content[] = $collection;
- }
- break;
- case 'colgroup':
- $cols[] = $collection;
- break;
- }
- $collection = array();
- $is_collecting = false;
- $tag_index = 0;
- } else {
- // add the node to the collection
- $collection[] = $token;
- }
- }
-
- // terminate
- if ($token === false) break;
-
- if ($is_child) {
- // determine what we're dealing with
- if ($token->name == 'col') {
- // the only empty tag in the possie, we can handle it
- // immediately
- $cols[] = array_merge($collection, array($token));
- $collection = array();
- $tag_index = 0;
- continue;
- }
- switch($token->name) {
- case 'caption':
- case 'colgroup':
- case 'thead':
- case 'tfoot':
- case 'tbody':
- case 'tr':
- $is_collecting = true;
- $collection[] = $token;
- continue;
- default:
- if (!empty($token->is_whitespace)) {
- $collection[] = $token;
- $tag_index++;
- }
- continue;
- }
- }
- }
-
- if (empty($content)) return false;
-
- $ret = array();
- if ($caption !== false) $ret = array_merge($ret, $caption);
- if ($cols !== false) foreach ($cols as $token_array) $ret = array_merge($ret, $token_array);
- if ($thead !== false) $ret = array_merge($ret, $thead);
- if ($tfoot !== false) $ret = array_merge($ret, $tfoot);
- foreach ($content as $token_array) $ret = array_merge($ret, $token_array);
- if (!empty($collection) && $is_collecting == false){
- // grab the trailing space
- $ret = array_merge($ret, $collection);
- }
-
- array_pop($tokens_of_children); // remove phantom token
-
- return ($ret === $tokens_of_children) ? true : $ret;
-
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/Config.php b/library/HTMLPurifier/Config.php
deleted file mode 100644
index 2a334b0d8..000000000
--- a/library/HTMLPurifier/Config.php
+++ /dev/null
@@ -1,580 +0,0 @@
-defaultPlist;
- $this->plist = new HTMLPurifier_PropertyList($parent);
- $this->def = $definition; // keep a copy around for checking
- $this->parser = new HTMLPurifier_VarParser_Flexible();
- }
-
- /**
- * Convenience constructor that creates a config object based on a mixed var
- * @param mixed $config Variable that defines the state of the config
- * object. Can be: a HTMLPurifier_Config() object,
- * an array of directives based on loadArray(),
- * or a string filename of an ini file.
- * @param HTMLPurifier_ConfigSchema Schema object
- * @return Configured HTMLPurifier_Config object
- */
- public static function create($config, $schema = null) {
- if ($config instanceof HTMLPurifier_Config) {
- // pass-through
- return $config;
- }
- if (!$schema) {
- $ret = HTMLPurifier_Config::createDefault();
- } else {
- $ret = new HTMLPurifier_Config($schema);
- }
- if (is_string($config)) $ret->loadIni($config);
- elseif (is_array($config)) $ret->loadArray($config);
- return $ret;
- }
-
- /**
- * Creates a new config object that inherits from a previous one.
- * @param HTMLPurifier_Config $config Configuration object to inherit
- * from.
- * @return HTMLPurifier_Config object with $config as its parent.
- */
- public static function inherit(HTMLPurifier_Config $config) {
- return new HTMLPurifier_Config($config->def, $config->plist);
- }
-
- /**
- * Convenience constructor that creates a default configuration object.
- * @return Default HTMLPurifier_Config object.
- */
- public static function createDefault() {
- $definition = HTMLPurifier_ConfigSchema::instance();
- $config = new HTMLPurifier_Config($definition);
- return $config;
- }
-
- /**
- * Retreives a value from the configuration.
- * @param $key String key
- */
- public function get($key, $a = null) {
- if ($a !== null) {
- $this->triggerError("Using deprecated API: use \$config->get('$key.$a') instead", E_USER_WARNING);
- $key = "$key.$a";
- }
- if (!$this->finalized) $this->autoFinalize();
- if (!isset($this->def->info[$key])) {
- // can't add % due to SimpleTest bug
- $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
- E_USER_WARNING);
- return;
- }
- if (isset($this->def->info[$key]->isAlias)) {
- $d = $this->def->info[$key];
- $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,
- E_USER_ERROR);
- return;
- }
- if ($this->lock) {
- list($ns) = explode('.', $key);
- if ($ns !== $this->lock) {
- $this->triggerError('Cannot get value of namespace ' . $ns . ' when lock for ' . $this->lock . ' is active, this probably indicates a Definition setup method is accessing directives that are not within its namespace', E_USER_ERROR);
- return;
- }
- }
- return $this->plist->get($key);
- }
-
- /**
- * Retreives an array of directives to values from a given namespace
- * @param $namespace String namespace
- */
- public function getBatch($namespace) {
- if (!$this->finalized) $this->autoFinalize();
- $full = $this->getAll();
- if (!isset($full[$namespace])) {
- $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
- E_USER_WARNING);
- return;
- }
- return $full[$namespace];
- }
-
- /**
- * Returns a md5 signature of a segment of the configuration object
- * that uniquely identifies that particular configuration
- * @note Revision is handled specially and is removed from the batch
- * before processing!
- * @param $namespace Namespace to get serial for
- */
- public function getBatchSerial($namespace) {
- if (empty($this->serials[$namespace])) {
- $batch = $this->getBatch($namespace);
- unset($batch['DefinitionRev']);
- $this->serials[$namespace] = md5(serialize($batch));
- }
- return $this->serials[$namespace];
- }
-
- /**
- * Returns a md5 signature for the entire configuration object
- * that uniquely identifies that particular configuration
- */
- public function getSerial() {
- if (empty($this->serial)) {
- $this->serial = md5(serialize($this->getAll()));
- }
- return $this->serial;
- }
-
- /**
- * Retrieves all directives, organized by namespace
- * @warning This is a pretty inefficient function, avoid if you can
- */
- public function getAll() {
- if (!$this->finalized) $this->autoFinalize();
- $ret = array();
- foreach ($this->plist->squash() as $name => $value) {
- list($ns, $key) = explode('.', $name, 2);
- $ret[$ns][$key] = $value;
- }
- return $ret;
- }
-
- /**
- * Sets a value to configuration.
- * @param $key String key
- * @param $value Mixed value
- */
- public function set($key, $value, $a = null) {
- if (strpos($key, '.') === false) {
- $namespace = $key;
- $directive = $value;
- $value = $a;
- $key = "$key.$directive";
- $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
- } else {
- list($namespace) = explode('.', $key);
- }
- if ($this->isFinalized('Cannot set directive after finalization')) return;
- if (!isset($this->def->info[$key])) {
- $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
- E_USER_WARNING);
- return;
- }
- $def = $this->def->info[$key];
-
- if (isset($def->isAlias)) {
- if ($this->aliasMode) {
- $this->triggerError('Double-aliases not allowed, please fix '.
- 'ConfigSchema bug with' . $key, E_USER_ERROR);
- return;
- }
- $this->aliasMode = true;
- $this->set($def->key, $value);
- $this->aliasMode = false;
- $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
- return;
- }
-
- // Raw type might be negative when using the fully optimized form
- // of stdclass, which indicates allow_null == true
- $rtype = is_int($def) ? $def : $def->type;
- if ($rtype < 0) {
- $type = -$rtype;
- $allow_null = true;
- } else {
- $type = $rtype;
- $allow_null = isset($def->allow_null);
- }
-
- try {
- $value = $this->parser->parse($value, $type, $allow_null);
- } catch (HTMLPurifier_VarParserException $e) {
- $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
- return;
- }
- if (is_string($value) && is_object($def)) {
- // resolve value alias if defined
- if (isset($def->aliases[$value])) {
- $value = $def->aliases[$value];
- }
- // check to see if the value is allowed
- if (isset($def->allowed) && !isset($def->allowed[$value])) {
- $this->triggerError('Value not supported, valid values are: ' .
- $this->_listify($def->allowed), E_USER_WARNING);
- return;
- }
- }
- $this->plist->set($key, $value);
-
- // reset definitions if the directives they depend on changed
- // this is a very costly process, so it's discouraged
- // with finalization
- if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {
- $this->definitions[$namespace] = null;
- }
-
- $this->serials[$namespace] = false;
- }
-
- /**
- * Convenience function for error reporting
- */
- private function _listify($lookup) {
- $list = array();
- foreach ($lookup as $name => $b) $list[] = $name;
- return implode(', ', $list);
- }
-
- /**
- * Retrieves object reference to the HTML definition.
- * @param $raw Return a copy that has not been setup yet. Must be
- * called before it's been setup, otherwise won't work.
- */
- public function getHTMLDefinition($raw = false) {
- return $this->getDefinition('HTML', $raw);
- }
-
- /**
- * Retrieves object reference to the CSS definition
- * @param $raw Return a copy that has not been setup yet. Must be
- * called before it's been setup, otherwise won't work.
- */
- public function getCSSDefinition($raw = false) {
- return $this->getDefinition('CSS', $raw);
- }
-
- /**
- * Retrieves a definition
- * @param $type Type of definition: HTML, CSS, etc
- * @param $raw Whether or not definition should be returned raw
- */
- public function getDefinition($type, $raw = false) {
- if (!$this->finalized) $this->autoFinalize();
- // temporarily suspend locks, so we can handle recursive definition calls
- $lock = $this->lock;
- $this->lock = null;
- $factory = HTMLPurifier_DefinitionCacheFactory::instance();
- $cache = $factory->create($type, $this);
- $this->lock = $lock;
- if (!$raw) {
- // see if we can quickly supply a definition
- if (!empty($this->definitions[$type])) {
- if (!$this->definitions[$type]->setup) {
- $this->definitions[$type]->setup($this);
- $cache->set($this->definitions[$type], $this);
- }
- return $this->definitions[$type];
- }
- // memory check missed, try cache
- $this->definitions[$type] = $cache->get($this);
- if ($this->definitions[$type]) {
- // definition in cache, return it
- return $this->definitions[$type];
- }
- } elseif (
- !empty($this->definitions[$type]) &&
- !$this->definitions[$type]->setup
- ) {
- // raw requested, raw in memory, quick return
- return $this->definitions[$type];
- }
- // quick checks failed, let's create the object
- if ($type == 'HTML') {
- $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();
- } elseif ($type == 'CSS') {
- $this->definitions[$type] = new HTMLPurifier_CSSDefinition();
- } elseif ($type == 'URI') {
- $this->definitions[$type] = new HTMLPurifier_URIDefinition();
- } else {
- throw new HTMLPurifier_Exception("Definition of $type type not supported");
- }
- // quick abort if raw
- if ($raw) {
- if (is_null($this->get($type . '.DefinitionID'))) {
- // fatally error out if definition ID not set
- throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
- }
- return $this->definitions[$type];
- }
- // set it up
- $this->lock = $type;
- $this->definitions[$type]->setup($this);
- $this->lock = null;
- // save in cache
- $cache->set($this->definitions[$type], $this);
- return $this->definitions[$type];
- }
-
- /**
- * Loads configuration values from an array with the following structure:
- * Namespace.Directive => Value
- * @param $config_array Configuration associative array
- */
- public function loadArray($config_array) {
- if ($this->isFinalized('Cannot load directives after finalization')) return;
- foreach ($config_array as $key => $value) {
- $key = str_replace('_', '.', $key);
- if (strpos($key, '.') !== false) {
- $this->set($key, $value);
- } else {
- $namespace = $key;
- $namespace_values = $value;
- foreach ($namespace_values as $directive => $value) {
- $this->set($namespace .'.'. $directive, $value);
- }
- }
- }
- }
-
- /**
- * Returns a list of array(namespace, directive) for all directives
- * that are allowed in a web-form context as per an allowed
- * namespaces/directives list.
- * @param $allowed List of allowed namespaces/directives
- */
- public static function getAllowedDirectivesForForm($allowed, $schema = null) {
- if (!$schema) {
- $schema = HTMLPurifier_ConfigSchema::instance();
- }
- if ($allowed !== true) {
- if (is_string($allowed)) $allowed = array($allowed);
- $allowed_ns = array();
- $allowed_directives = array();
- $blacklisted_directives = array();
- foreach ($allowed as $ns_or_directive) {
- if (strpos($ns_or_directive, '.') !== false) {
- // directive
- if ($ns_or_directive[0] == '-') {
- $blacklisted_directives[substr($ns_or_directive, 1)] = true;
- } else {
- $allowed_directives[$ns_or_directive] = true;
- }
- } else {
- // namespace
- $allowed_ns[$ns_or_directive] = true;
- }
- }
- }
- $ret = array();
- foreach ($schema->info as $key => $def) {
- list($ns, $directive) = explode('.', $key, 2);
- if ($allowed !== true) {
- if (isset($blacklisted_directives["$ns.$directive"])) continue;
- if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
- }
- if (isset($def->isAlias)) continue;
- if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
- $ret[] = array($ns, $directive);
- }
- return $ret;
- }
-
- /**
- * Loads configuration values from $_GET/$_POST that were posted
- * via ConfigForm
- * @param $array $_GET or $_POST array to import
- * @param $index Index/name that the config variables are in
- * @param $allowed List of allowed namespaces/directives
- * @param $mq_fix Boolean whether or not to enable magic quotes fix
- * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
- */
- public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
- $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
- $config = HTMLPurifier_Config::create($ret, $schema);
- return $config;
- }
-
- /**
- * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
- * @note Same parameters as loadArrayFromForm
- */
- public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
- $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
- $this->loadArray($ret);
- }
-
- /**
- * Prepares an array from a form into something usable for the more
- * strict parts of HTMLPurifier_Config
- */
- public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
- if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
- $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
-
- $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
- $ret = array();
- foreach ($allowed as $key) {
- list($ns, $directive) = $key;
- $skey = "$ns.$directive";
- if (!empty($array["Null_$skey"])) {
- $ret[$ns][$directive] = null;
- continue;
- }
- if (!isset($array[$skey])) continue;
- $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
- $ret[$ns][$directive] = $value;
- }
- return $ret;
- }
-
- /**
- * Loads configuration values from an ini file
- * @param $filename Name of ini file
- */
- public function loadIni($filename) {
- if ($this->isFinalized('Cannot load directives after finalization')) return;
- $array = parse_ini_file($filename, true);
- $this->loadArray($array);
- }
-
- /**
- * Checks whether or not the configuration object is finalized.
- * @param $error String error message, or false for no error
- */
- public function isFinalized($error = false) {
- if ($this->finalized && $error) {
- $this->triggerError($error, E_USER_ERROR);
- }
- return $this->finalized;
- }
-
- /**
- * Finalizes configuration only if auto finalize is on and not
- * already finalized
- */
- public function autoFinalize() {
- if ($this->autoFinalize) {
- $this->finalize();
- } else {
- $this->plist->squash(true);
- }
- }
-
- /**
- * Finalizes a configuration object, prohibiting further change
- */
- public function finalize() {
- $this->finalized = true;
- unset($this->parser);
- }
-
- /**
- * Produces a nicely formatted error message by supplying the
- * stack frame information from two levels up and OUTSIDE of
- * HTMLPurifier_Config.
- */
- protected function triggerError($msg, $no) {
- // determine previous stack frame
- $backtrace = debug_backtrace();
- if ($this->chatty && isset($backtrace[1])) {
- $frame = $backtrace[1];
- $extra = " on line {$frame['line']} in file {$frame['file']}";
- } else {
- $extra = '';
- }
- trigger_error($msg . $extra, $no);
- }
-
- /**
- * Returns a serialized form of the configuration object that can
- * be reconstituted.
- */
- public function serialize() {
- $this->getDefinition('HTML');
- $this->getDefinition('CSS');
- $this->getDefinition('URI');
- return serialize($this);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php b/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php
deleted file mode 100644
index b95aea18c..000000000
--- a/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php
+++ /dev/null
@@ -1,66 +0,0 @@
-context = $context;
- $this->obj = $obj;
- $this->member = $member;
- $this->contents =& $obj->$member;
- }
-
- public function assertIsString() {
- if (!is_string($this->contents)) $this->error('must be a string');
- return $this;
- }
-
- public function assertIsBool() {
- if (!is_bool($this->contents)) $this->error('must be a boolean');
- return $this;
- }
-
- public function assertIsArray() {
- if (!is_array($this->contents)) $this->error('must be an array');
- return $this;
- }
-
- public function assertNotNull() {
- if ($this->contents === null) $this->error('must not be null');
- return $this;
- }
-
- public function assertAlnum() {
- $this->assertIsString();
- if (!ctype_alnum($this->contents)) $this->error('must be alphanumeric');
- return $this;
- }
-
- public function assertNotEmpty() {
- if (empty($this->contents)) $this->error('must not be empty');
- return $this;
- }
-
- public function assertIsLookup() {
- $this->assertIsArray();
- foreach ($this->contents as $v) {
- if ($v !== true) $this->error('must be a lookup array');
- }
- return $this;
- }
-
- protected function error($msg) {
- throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/ConfigSchema/schema.ser b/library/HTMLPurifier/ConfigSchema/schema.ser
deleted file mode 100644
index 22b8d54a5..000000000
Binary files a/library/HTMLPurifier/ConfigSchema/schema.ser and /dev/null differ
diff --git a/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt b/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt
deleted file mode 100644
index 888d55819..000000000
--- a/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-HTML.AllowedElements
-TYPE: lookup/null
-VERSION: 1.3.0
-DEFAULT: NULL
---DESCRIPTION--
-
- If HTML Purifier's tag set is unsatisfactory for your needs, you
- can overload it with your own list of tags to allow. Note that this
- method is subtractive: it does its job by taking away from HTML Purifier
- usual feature set, so you cannot add a tag that HTML Purifier never
- supported in the first place (like embed, form or head). If you
- change this, you probably also want to change %HTML.AllowedAttributes.
-
-
- Warning: If another directive conflicts with the
- elements here, that directive will win and override.
-
- , $tokens);
- return $tokens;
- }
-
-}
-
-/*
-
-Copyright 2007 Jeroen van der Meer
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-*/
-
-class HTML5 {
- private $data;
- private $char;
- private $EOF;
- private $state;
- private $tree;
- private $token;
- private $content_model;
- private $escape = false;
- private $entities = array('AElig;','AElig','AMP;','AMP','Aacute;','Aacute',
- 'Acirc;','Acirc','Agrave;','Agrave','Alpha;','Aring;','Aring','Atilde;',
- 'Atilde','Auml;','Auml','Beta;','COPY;','COPY','Ccedil;','Ccedil','Chi;',
- 'Dagger;','Delta;','ETH;','ETH','Eacute;','Eacute','Ecirc;','Ecirc','Egrave;',
- 'Egrave','Epsilon;','Eta;','Euml;','Euml','GT;','GT','Gamma;','Iacute;',
- 'Iacute','Icirc;','Icirc','Igrave;','Igrave','Iota;','Iuml;','Iuml','Kappa;',
- 'LT;','LT','Lambda;','Mu;','Ntilde;','Ntilde','Nu;','OElig;','Oacute;',
- 'Oacute','Ocirc;','Ocirc','Ograve;','Ograve','Omega;','Omicron;','Oslash;',
- 'Oslash','Otilde;','Otilde','Ouml;','Ouml','Phi;','Pi;','Prime;','Psi;',
- 'QUOT;','QUOT','REG;','REG','Rho;','Scaron;','Sigma;','THORN;','THORN',
- 'TRADE;','Tau;','Theta;','Uacute;','Uacute','Ucirc;','Ucirc','Ugrave;',
- 'Ugrave','Upsilon;','Uuml;','Uuml','Xi;','Yacute;','Yacute','Yuml;','Zeta;',
- 'aacute;','aacute','acirc;','acirc','acute;','acute','aelig;','aelig',
- 'agrave;','agrave','alefsym;','alpha;','amp;','amp','and;','ang;','apos;',
- 'aring;','aring','asymp;','atilde;','atilde','auml;','auml','bdquo;','beta;',
- 'brvbar;','brvbar','bull;','cap;','ccedil;','ccedil','cedil;','cedil',
- 'cent;','cent','chi;','circ;','clubs;','cong;','copy;','copy','crarr;',
- 'cup;','curren;','curren','dArr;','dagger;','darr;','deg;','deg','delta;',
- 'diams;','divide;','divide','eacute;','eacute','ecirc;','ecirc','egrave;',
- 'egrave','empty;','emsp;','ensp;','epsilon;','equiv;','eta;','eth;','eth',
- 'euml;','euml','euro;','exist;','fnof;','forall;','frac12;','frac12',
- 'frac14;','frac14','frac34;','frac34','frasl;','gamma;','ge;','gt;','gt',
- 'hArr;','harr;','hearts;','hellip;','iacute;','iacute','icirc;','icirc',
- 'iexcl;','iexcl','igrave;','igrave','image;','infin;','int;','iota;',
- 'iquest;','iquest','isin;','iuml;','iuml','kappa;','lArr;','lambda;','lang;',
- 'laquo;','laquo','larr;','lceil;','ldquo;','le;','lfloor;','lowast;','loz;',
- 'lrm;','lsaquo;','lsquo;','lt;','lt','macr;','macr','mdash;','micro;','micro',
- 'middot;','middot','minus;','mu;','nabla;','nbsp;','nbsp','ndash;','ne;',
- 'ni;','not;','not','notin;','nsub;','ntilde;','ntilde','nu;','oacute;',
- 'oacute','ocirc;','ocirc','oelig;','ograve;','ograve','oline;','omega;',
- 'omicron;','oplus;','or;','ordf;','ordf','ordm;','ordm','oslash;','oslash',
- 'otilde;','otilde','otimes;','ouml;','ouml','para;','para','part;','permil;',
- 'perp;','phi;','pi;','piv;','plusmn;','plusmn','pound;','pound','prime;',
- 'prod;','prop;','psi;','quot;','quot','rArr;','radic;','rang;','raquo;',
- 'raquo','rarr;','rceil;','rdquo;','real;','reg;','reg','rfloor;','rho;',
- 'rlm;','rsaquo;','rsquo;','sbquo;','scaron;','sdot;','sect;','sect','shy;',
- 'shy','sigma;','sigmaf;','sim;','spades;','sub;','sube;','sum;','sup1;',
- 'sup1','sup2;','sup2','sup3;','sup3','sup;','supe;','szlig;','szlig','tau;',
- 'there4;','theta;','thetasym;','thinsp;','thorn;','thorn','tilde;','times;',
- 'times','trade;','uArr;','uacute;','uacute','uarr;','ucirc;','ucirc',
- 'ugrave;','ugrave','uml;','uml','upsih;','upsilon;','uuml;','uuml','weierp;',
- 'xi;','yacute;','yacute','yen;','yen','yuml;','yuml','zeta;','zwj;','zwnj;');
-
- const PCDATA = 0;
- const RCDATA = 1;
- const CDATA = 2;
- const PLAINTEXT = 3;
-
- const DOCTYPE = 0;
- const STARTTAG = 1;
- const ENDTAG = 2;
- const COMMENT = 3;
- const CHARACTR = 4;
- const EOF = 5;
-
- public function __construct($data) {
- $data = str_replace("\r\n", "\n", $data);
- $data = str_replace("\r", null, $data);
-
- $this->data = $data;
- $this->char = -1;
- $this->EOF = strlen($data);
- $this->tree = new HTML5TreeConstructer;
- $this->content_model = self::PCDATA;
-
- $this->state = 'data';
-
- while($this->state !== null) {
- $this->{$this->state.'State'}();
- }
- }
-
- public function save() {
- return $this->tree->save();
- }
-
- private function char() {
- return ($this->char < $this->EOF)
- ? $this->data[$this->char]
- : false;
- }
-
- private function character($s, $l = 0) {
- if($s + $l < $this->EOF) {
- if($l === 0) {
- return $this->data[$s];
- } else {
- return substr($this->data, $s, $l);
- }
- }
- }
-
- private function characters($char_class, $start) {
- return preg_replace('#^(['.$char_class.']+).*#s', '\\1', substr($this->data, $start));
- }
-
- private function dataState() {
- // Consume the next input character
- $this->char++;
- $char = $this->char();
-
- if($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) {
- /* U+0026 AMPERSAND (&)
- When the content model flag is set to one of the PCDATA or RCDATA
- states: switch to the entity data state. Otherwise: treat it as per
- the "anything else" entry below. */
- $this->state = 'entityData';
-
- } elseif($char === '-') {
- /* If the content model flag is set to either the RCDATA state or
- the CDATA state, and the escape flag is false, and there are at
- least three characters before this one in the input stream, and the
- last four characters in the input stream, including this one, are
- U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS,
- and U+002D HYPHEN-MINUS (""),
- set the escape flag to false. */
- if(($this->content_model === self::RCDATA ||
- $this->content_model === self::CDATA) && $this->escape === true &&
- $this->character($this->char, 3) === '-->') {
- $this->escape = false;
- }
-
- /* In any case, emit the input character as a character token.
- Stay in the data state. */
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => $char
- ));
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Emit an end-of-file token. */
- $this->EOF();
-
- } elseif($this->content_model === self::PLAINTEXT) {
- /* When the content model flag is set to the PLAINTEXT state
- THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of
- the text and emit it as a character token. */
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => substr($this->data, $this->char)
- ));
-
- $this->EOF();
-
- } else {
- /* Anything else
- THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that
- otherwise would also be treated as a character token and emit it
- as a single character token. Stay in the data state. */
- $len = strcspn($this->data, '<&', $this->char);
- $char = substr($this->data, $this->char, $len);
- $this->char += $len - 1;
-
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => $char
- ));
-
- $this->state = 'data';
- }
- }
-
- private function entityDataState() {
- // Attempt to consume an entity.
- $entity = $this->entity();
-
- // If nothing is returned, emit a U+0026 AMPERSAND character token.
- // Otherwise, emit the character token that was returned.
- $char = (!$entity) ? '&' : $entity;
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => $char
- ));
-
- // Finally, switch to the data state.
- $this->state = 'data';
- }
-
- private function tagOpenState() {
- switch($this->content_model) {
- case self::RCDATA:
- case self::CDATA:
- /* If the next input character is a U+002F SOLIDUS (/) character,
- consume it and switch to the close tag open state. If the next
- input character is not a U+002F SOLIDUS (/) character, emit a
- U+003C LESS-THAN SIGN character token and switch to the data
- state to process the next input character. */
- if($this->character($this->char + 1) === '/') {
- $this->char++;
- $this->state = 'closeTagOpen';
-
- } else {
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => '<'
- ));
-
- $this->state = 'data';
- }
- break;
-
- case self::PCDATA:
- // If the content model flag is set to the PCDATA state
- // Consume the next input character:
- $this->char++;
- $char = $this->char();
-
- if($char === '!') {
- /* U+0021 EXCLAMATION MARK (!)
- Switch to the markup declaration open state. */
- $this->state = 'markupDeclarationOpen';
-
- } elseif($char === '/') {
- /* U+002F SOLIDUS (/)
- Switch to the close tag open state. */
- $this->state = 'closeTagOpen';
-
- } elseif(preg_match('/^[A-Za-z]$/', $char)) {
- /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
- Create a new start tag token, set its tag name to the lowercase
- version of the input character (add 0x0020 to the character's code
- point), then switch to the tag name state. (Don't emit the token
- yet; further details will be filled in before it is emitted.) */
- $this->token = array(
- 'name' => strtolower($char),
- 'type' => self::STARTTAG,
- 'attr' => array()
- );
-
- $this->state = 'tagName';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Parse error. Emit a U+003C LESS-THAN SIGN character token and a
- U+003E GREATER-THAN SIGN character token. Switch to the data state. */
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => '<>'
- ));
-
- $this->state = 'data';
-
- } elseif($char === '?') {
- /* U+003F QUESTION MARK (?)
- Parse error. Switch to the bogus comment state. */
- $this->state = 'bogusComment';
-
- } else {
- /* Anything else
- Parse error. Emit a U+003C LESS-THAN SIGN character token and
- reconsume the current input character in the data state. */
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => '<'
- ));
-
- $this->char--;
- $this->state = 'data';
- }
- break;
- }
- }
-
- private function closeTagOpenState() {
- $next_node = strtolower($this->characters('A-Za-z', $this->char + 1));
- $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName;
-
- if(($this->content_model === self::RCDATA || $this->content_model === self::CDATA) &&
- (!$the_same || ($the_same && (!preg_match('/[\t\n\x0b\x0c >\/]/',
- $this->character($this->char + 1 + strlen($next_node))) || $this->EOF === $this->char)))) {
- /* If the content model flag is set to the RCDATA or CDATA states then
- examine the next few characters. If they do not match the tag name of
- the last start tag token emitted (case insensitively), or if they do but
- they are not immediately followed by one of the following characters:
- * U+0009 CHARACTER TABULATION
- * U+000A LINE FEED (LF)
- * U+000B LINE TABULATION
- * U+000C FORM FEED (FF)
- * U+0020 SPACE
- * U+003E GREATER-THAN SIGN (>)
- * U+002F SOLIDUS (/)
- * EOF
- ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character
- token, a U+002F SOLIDUS character token, and switch to the data state
- to process the next input character. */
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => ''
- ));
-
- $this->state = 'data';
-
- } else {
- /* Otherwise, if the content model flag is set to the PCDATA state,
- or if the next few characters do match that tag name, consume the
- next input character: */
- $this->char++;
- $char = $this->char();
-
- if(preg_match('/^[A-Za-z]$/', $char)) {
- /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
- Create a new end tag token, set its tag name to the lowercase version
- of the input character (add 0x0020 to the character's code point), then
- switch to the tag name state. (Don't emit the token yet; further details
- will be filled in before it is emitted.) */
- $this->token = array(
- 'name' => strtolower($char),
- 'type' => self::ENDTAG
- );
-
- $this->state = 'tagName';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Parse error. Switch to the data state. */
- $this->state = 'data';
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F
- SOLIDUS character token. Reconsume the EOF character in the data state. */
- $this->emitToken(array(
- 'type' => self::CHARACTR,
- 'data' => ''
- ));
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- /* Parse error. Switch to the bogus comment state. */
- $this->state = 'bogusComment';
- }
- }
- }
-
- private function tagNameState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- /* U+0009 CHARACTER TABULATION
- U+000A LINE FEED (LF)
- U+000B LINE TABULATION
- U+000C FORM FEED (FF)
- U+0020 SPACE
- Switch to the before attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Emit the current tag token. Switch to the data state. */
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit the current tag token. Reconsume the EOF
- character in the data state. */
- $this->emitToken($this->token);
-
- $this->char--;
- $this->state = 'data';
-
- } elseif($char === '/') {
- /* U+002F SOLIDUS (/)
- Parse error unless this is a permitted slash. Switch to the before
- attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } else {
- /* Anything else
- Append the current input character to the current tag token's tag name.
- Stay in the tag name state. */
- $this->token['name'] .= strtolower($char);
- $this->state = 'tagName';
- }
- }
-
- private function beforeAttributeNameState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- /* U+0009 CHARACTER TABULATION
- U+000A LINE FEED (LF)
- U+000B LINE TABULATION
- U+000C FORM FEED (FF)
- U+0020 SPACE
- Stay in the before attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Emit the current tag token. Switch to the data state. */
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($char === '/') {
- /* U+002F SOLIDUS (/)
- Parse error unless this is a permitted slash. Stay in the before
- attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit the current tag token. Reconsume the EOF
- character in the data state. */
- $this->emitToken($this->token);
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- /* Anything else
- Start a new attribute in the current tag token. Set that attribute's
- name to the current input character, and its value to the empty string.
- Switch to the attribute name state. */
- $this->token['attr'][] = array(
- 'name' => strtolower($char),
- 'value' => null
- );
-
- $this->state = 'attributeName';
- }
- }
-
- private function attributeNameState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- /* U+0009 CHARACTER TABULATION
- U+000A LINE FEED (LF)
- U+000B LINE TABULATION
- U+000C FORM FEED (FF)
- U+0020 SPACE
- Stay in the before attribute name state. */
- $this->state = 'afterAttributeName';
-
- } elseif($char === '=') {
- /* U+003D EQUALS SIGN (=)
- Switch to the before attribute value state. */
- $this->state = 'beforeAttributeValue';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Emit the current tag token. Switch to the data state. */
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
- /* U+002F SOLIDUS (/)
- Parse error unless this is a permitted slash. Switch to the before
- attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit the current tag token. Reconsume the EOF
- character in the data state. */
- $this->emitToken($this->token);
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- /* Anything else
- Append the current input character to the current attribute's name.
- Stay in the attribute name state. */
- $last = count($this->token['attr']) - 1;
- $this->token['attr'][$last]['name'] .= strtolower($char);
-
- $this->state = 'attributeName';
- }
- }
-
- private function afterAttributeNameState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- /* U+0009 CHARACTER TABULATION
- U+000A LINE FEED (LF)
- U+000B LINE TABULATION
- U+000C FORM FEED (FF)
- U+0020 SPACE
- Stay in the after attribute name state. */
- $this->state = 'afterAttributeName';
-
- } elseif($char === '=') {
- /* U+003D EQUALS SIGN (=)
- Switch to the before attribute value state. */
- $this->state = 'beforeAttributeValue';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Emit the current tag token. Switch to the data state. */
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
- /* U+002F SOLIDUS (/)
- Parse error unless this is a permitted slash. Switch to the
- before attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit the current tag token. Reconsume the EOF
- character in the data state. */
- $this->emitToken($this->token);
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- /* Anything else
- Start a new attribute in the current tag token. Set that attribute's
- name to the current input character, and its value to the empty string.
- Switch to the attribute name state. */
- $this->token['attr'][] = array(
- 'name' => strtolower($char),
- 'value' => null
- );
-
- $this->state = 'attributeName';
- }
- }
-
- private function beforeAttributeValueState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- /* U+0009 CHARACTER TABULATION
- U+000A LINE FEED (LF)
- U+000B LINE TABULATION
- U+000C FORM FEED (FF)
- U+0020 SPACE
- Stay in the before attribute value state. */
- $this->state = 'beforeAttributeValue';
-
- } elseif($char === '"') {
- /* U+0022 QUOTATION MARK (")
- Switch to the attribute value (double-quoted) state. */
- $this->state = 'attributeValueDoubleQuoted';
-
- } elseif($char === '&') {
- /* U+0026 AMPERSAND (&)
- Switch to the attribute value (unquoted) state and reconsume
- this input character. */
- $this->char--;
- $this->state = 'attributeValueUnquoted';
-
- } elseif($char === '\'') {
- /* U+0027 APOSTROPHE (')
- Switch to the attribute value (single-quoted) state. */
- $this->state = 'attributeValueSingleQuoted';
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Emit the current tag token. Switch to the data state. */
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } else {
- /* Anything else
- Append the current input character to the current attribute's value.
- Switch to the attribute value (unquoted) state. */
- $last = count($this->token['attr']) - 1;
- $this->token['attr'][$last]['value'] .= $char;
-
- $this->state = 'attributeValueUnquoted';
- }
- }
-
- private function attributeValueDoubleQuotedState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if($char === '"') {
- /* U+0022 QUOTATION MARK (")
- Switch to the before attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($char === '&') {
- /* U+0026 AMPERSAND (&)
- Switch to the entity in attribute value state. */
- $this->entityInAttributeValueState('double');
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit the current tag token. Reconsume the character
- in the data state. */
- $this->emitToken($this->token);
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- /* Anything else
- Append the current input character to the current attribute's value.
- Stay in the attribute value (double-quoted) state. */
- $last = count($this->token['attr']) - 1;
- $this->token['attr'][$last]['value'] .= $char;
-
- $this->state = 'attributeValueDoubleQuoted';
- }
- }
-
- private function attributeValueSingleQuotedState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if($char === '\'') {
- /* U+0022 QUOTATION MARK (')
- Switch to the before attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($char === '&') {
- /* U+0026 AMPERSAND (&)
- Switch to the entity in attribute value state. */
- $this->entityInAttributeValueState('single');
-
- } elseif($this->char === $this->EOF) {
- /* EOF
- Parse error. Emit the current tag token. Reconsume the character
- in the data state. */
- $this->emitToken($this->token);
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- /* Anything else
- Append the current input character to the current attribute's value.
- Stay in the attribute value (single-quoted) state. */
- $last = count($this->token['attr']) - 1;
- $this->token['attr'][$last]['value'] .= $char;
-
- $this->state = 'attributeValueSingleQuoted';
- }
- }
-
- private function attributeValueUnquotedState() {
- // Consume the next input character:
- $this->char++;
- $char = $this->character($this->char);
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- /* U+0009 CHARACTER TABULATION
- U+000A LINE FEED (LF)
- U+000B LINE TABULATION
- U+000C FORM FEED (FF)
- U+0020 SPACE
- Switch to the before attribute name state. */
- $this->state = 'beforeAttributeName';
-
- } elseif($char === '&') {
- /* U+0026 AMPERSAND (&)
- Switch to the entity in attribute value state. */
- $this->entityInAttributeValueState();
-
- } elseif($char === '>') {
- /* U+003E GREATER-THAN SIGN (>)
- Emit the current tag token. Switch to the data state. */
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } else {
- /* Anything else
- Append the current input character to the current attribute's value.
- Stay in the attribute value (unquoted) state. */
- $last = count($this->token['attr']) - 1;
- $this->token['attr'][$last]['value'] .= $char;
-
- $this->state = 'attributeValueUnquoted';
- }
- }
-
- private function entityInAttributeValueState() {
- // Attempt to consume an entity.
- $entity = $this->entity();
-
- // If nothing is returned, append a U+0026 AMPERSAND character to the
- // current attribute's value. Otherwise, emit the character token that
- // was returned.
- $char = (!$entity)
- ? '&'
- : $entity;
-
- $last = count($this->token['attr']) - 1;
- $this->token['attr'][$last]['value'] .= $char;
- }
-
- private function bogusCommentState() {
- /* Consume every character up to the first U+003E GREATER-THAN SIGN
- character (>) or the end of the file (EOF), whichever comes first. Emit
- a comment token whose data is the concatenation of all the characters
- starting from and including the character that caused the state machine
- to switch into the bogus comment state, up to and including the last
- consumed character before the U+003E character, if any, or up to the
- end of the file otherwise. (If the comment was started by the end of
- the file (EOF), the token is empty.) */
- $data = $this->characters('^>', $this->char);
- $this->emitToken(array(
- 'data' => $data,
- 'type' => self::COMMENT
- ));
-
- $this->char += strlen($data);
-
- /* Switch to the data state. */
- $this->state = 'data';
-
- /* If the end of the file was reached, reconsume the EOF character. */
- if($this->char === $this->EOF) {
- $this->char = $this->EOF - 1;
- }
- }
-
- private function markupDeclarationOpenState() {
- /* If the next two characters are both U+002D HYPHEN-MINUS (-)
- characters, consume those two characters, create a comment token whose
- data is the empty string, and switch to the comment state. */
- if($this->character($this->char + 1, 2) === '--') {
- $this->char += 2;
- $this->state = 'comment';
- $this->token = array(
- 'data' => null,
- 'type' => self::COMMENT
- );
-
- /* Otherwise if the next seven chacacters are a case-insensitive match
- for the word "DOCTYPE", then consume those characters and switch to the
- DOCTYPE state. */
- } elseif(strtolower($this->character($this->char + 1, 7)) === 'doctype') {
- $this->char += 7;
- $this->state = 'doctype';
-
- /* Otherwise, is is a parse error. Switch to the bogus comment state.
- The next character that is consumed, if any, is the first character
- that will be in the comment. */
- } else {
- $this->char++;
- $this->state = 'bogusComment';
- }
- }
-
- private function commentState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- /* U+002D HYPHEN-MINUS (-) */
- if($char === '-') {
- /* Switch to the comment dash state */
- $this->state = 'commentDash';
-
- /* EOF */
- } elseif($this->char === $this->EOF) {
- /* Parse error. Emit the comment token. Reconsume the EOF character
- in the data state. */
- $this->emitToken($this->token);
- $this->char--;
- $this->state = 'data';
-
- /* Anything else */
- } else {
- /* Append the input character to the comment token's data. Stay in
- the comment state. */
- $this->token['data'] .= $char;
- }
- }
-
- private function commentDashState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- /* U+002D HYPHEN-MINUS (-) */
- if($char === '-') {
- /* Switch to the comment end state */
- $this->state = 'commentEnd';
-
- /* EOF */
- } elseif($this->char === $this->EOF) {
- /* Parse error. Emit the comment token. Reconsume the EOF character
- in the data state. */
- $this->emitToken($this->token);
- $this->char--;
- $this->state = 'data';
-
- /* Anything else */
- } else {
- /* Append a U+002D HYPHEN-MINUS (-) character and the input
- character to the comment token's data. Switch to the comment state. */
- $this->token['data'] .= '-'.$char;
- $this->state = 'comment';
- }
- }
-
- private function commentEndState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- if($char === '>') {
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($char === '-') {
- $this->token['data'] .= '-';
-
- } elseif($this->char === $this->EOF) {
- $this->emitToken($this->token);
- $this->char--;
- $this->state = 'data';
-
- } else {
- $this->token['data'] .= '--'.$char;
- $this->state = 'comment';
- }
- }
-
- private function doctypeState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- $this->state = 'beforeDoctypeName';
-
- } else {
- $this->char--;
- $this->state = 'beforeDoctypeName';
- }
- }
-
- private function beforeDoctypeNameState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- // Stay in the before DOCTYPE name state.
-
- } elseif(preg_match('/^[a-z]$/', $char)) {
- $this->token = array(
- 'name' => strtoupper($char),
- 'type' => self::DOCTYPE,
- 'error' => true
- );
-
- $this->state = 'doctypeName';
-
- } elseif($char === '>') {
- $this->emitToken(array(
- 'name' => null,
- 'type' => self::DOCTYPE,
- 'error' => true
- ));
-
- $this->state = 'data';
-
- } elseif($this->char === $this->EOF) {
- $this->emitToken(array(
- 'name' => null,
- 'type' => self::DOCTYPE,
- 'error' => true
- ));
-
- $this->char--;
- $this->state = 'data';
-
- } else {
- $this->token = array(
- 'name' => $char,
- 'type' => self::DOCTYPE,
- 'error' => true
- );
-
- $this->state = 'doctypeName';
- }
- }
-
- private function doctypeNameState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- $this->state = 'AfterDoctypeName';
-
- } elseif($char === '>') {
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif(preg_match('/^[a-z]$/', $char)) {
- $this->token['name'] .= strtoupper($char);
-
- } elseif($this->char === $this->EOF) {
- $this->emitToken($this->token);
- $this->char--;
- $this->state = 'data';
-
- } else {
- $this->token['name'] .= $char;
- }
-
- $this->token['error'] = ($this->token['name'] === 'HTML')
- ? false
- : true;
- }
-
- private function afterDoctypeNameState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
- // Stay in the DOCTYPE name state.
-
- } elseif($char === '>') {
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($this->char === $this->EOF) {
- $this->emitToken($this->token);
- $this->char--;
- $this->state = 'data';
-
- } else {
- $this->token['error'] = true;
- $this->state = 'bogusDoctype';
- }
- }
-
- private function bogusDoctypeState() {
- /* Consume the next input character: */
- $this->char++;
- $char = $this->char();
-
- if($char === '>') {
- $this->emitToken($this->token);
- $this->state = 'data';
-
- } elseif($this->char === $this->EOF) {
- $this->emitToken($this->token);
- $this->char--;
- $this->state = 'data';
-
- } else {
- // Stay in the bogus DOCTYPE state.
- }
- }
-
- private function entity() {
- $start = $this->char;
-
- // This section defines how to consume an entity. This definition is
- // used when parsing entities in text and in attributes.
-
- // The behaviour depends on the identity of the next character (the
- // one immediately after the U+0026 AMPERSAND character):
-
- switch($this->character($this->char + 1)) {
- // U+0023 NUMBER SIGN (#)
- case '#':
-
- // The behaviour further depends on the character after the
- // U+0023 NUMBER SIGN:
- switch($this->character($this->char + 1)) {
- // U+0078 LATIN SMALL LETTER X
- // U+0058 LATIN CAPITAL LETTER X
- case 'x':
- case 'X':
- // Follow the steps below, but using the range of
- // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
- // NINE, U+0061 LATIN SMALL LETTER A through to U+0066
- // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER
- // A, through to U+0046 LATIN CAPITAL LETTER F (in other
- // words, 0-9, A-F, a-f).
- $char = 1;
- $char_class = '0-9A-Fa-f';
- break;
-
- // Anything else
- default:
- // Follow the steps below, but using the range of
- // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
- // NINE (i.e. just 0-9).
- $char = 0;
- $char_class = '0-9';
- break;
- }
-
- // Consume as many characters as match the range of characters
- // given above.
- $this->char++;
- $e_name = $this->characters($char_class, $this->char + $char + 1);
- $entity = $this->character($start, $this->char);
- $cond = strlen($e_name) > 0;
-
- // The rest of the parsing happens bellow.
- break;
-
- // Anything else
- default:
- // Consume the maximum number of characters possible, with the
- // consumed characters case-sensitively matching one of the
- // identifiers in the first column of the entities table.
- $e_name = $this->characters('0-9A-Za-z;', $this->char + 1);
- $len = strlen($e_name);
-
- for($c = 1; $c <= $len; $c++) {
- $id = substr($e_name, 0, $c);
- $this->char++;
-
- if(in_array($id, $this->entities)) {
- if ($e_name[$c-1] !== ';') {
- if ($c < $len && $e_name[$c] == ';') {
- $this->char++; // consume extra semicolon
- }
- }
- $entity = $id;
- break;
- }
- }
-
- $cond = isset($entity);
- // The rest of the parsing happens bellow.
- break;
- }
-
- if(!$cond) {
- // If no match can be made, then this is a parse error. No
- // characters are consumed, and nothing is returned.
- $this->char = $start;
- return false;
- }
-
- // Return a character token for the character corresponding to the
- // entity name (as given by the second column of the entities table).
- return html_entity_decode('&'.$entity.';', ENT_QUOTES, 'UTF-8');
- }
-
- private function emitToken($token) {
- $emit = $this->tree->emitToken($token);
-
- if(is_int($emit)) {
- $this->content_model = $emit;
-
- } elseif($token['type'] === self::ENDTAG) {
- $this->content_model = self::PCDATA;
- }
- }
-
- private function EOF() {
- $this->state = null;
- $this->tree->emitToken(array(
- 'type' => self::EOF
- ));
- }
-}
-
-class HTML5TreeConstructer {
- public $stack = array();
-
- private $phase;
- private $mode;
- private $dom;
- private $foster_parent = null;
- private $a_formatting = array();
-
- private $head_pointer = null;
- private $form_pointer = null;
-
- private $scoping = array('button','caption','html','marquee','object','table','td','th');
- private $formatting = array('a','b','big','em','font','i','nobr','s','small','strike','strong','tt','u');
- private $special = array('address','area','base','basefont','bgsound',
- 'blockquote','body','br','center','col','colgroup','dd','dir','div','dl',
- 'dt','embed','fieldset','form','frame','frameset','h1','h2','h3','h4','h5',
- 'h6','head','hr','iframe','image','img','input','isindex','li','link',
- 'listing','menu','meta','noembed','noframes','noscript','ol','optgroup',
- 'option','p','param','plaintext','pre','script','select','spacer','style',
- 'tbody','textarea','tfoot','thead','title','tr','ul','wbr');
-
- // The different phases.
- const INIT_PHASE = 0;
- const ROOT_PHASE = 1;
- const MAIN_PHASE = 2;
- const END_PHASE = 3;
-
- // The different insertion modes for the main phase.
- const BEFOR_HEAD = 0;
- const IN_HEAD = 1;
- const AFTER_HEAD = 2;
- const IN_BODY = 3;
- const IN_TABLE = 4;
- const IN_CAPTION = 5;
- const IN_CGROUP = 6;
- const IN_TBODY = 7;
- const IN_ROW = 8;
- const IN_CELL = 9;
- const IN_SELECT = 10;
- const AFTER_BODY = 11;
- const IN_FRAME = 12;
- const AFTR_FRAME = 13;
-
- // The different types of elements.
- const SPECIAL = 0;
- const SCOPING = 1;
- const FORMATTING = 2;
- const PHRASING = 3;
-
- const MARKER = 0;
-
- public function __construct() {
- $this->phase = self::INIT_PHASE;
- $this->mode = self::BEFOR_HEAD;
- $this->dom = new DOMDocument;
-
- $this->dom->encoding = 'UTF-8';
- $this->dom->preserveWhiteSpace = true;
- $this->dom->substituteEntities = true;
- $this->dom->strictErrorChecking = false;
- }
-
- // Process tag tokens
- public function emitToken($token) {
- switch($this->phase) {
- case self::INIT_PHASE: return $this->initPhase($token); break;
- case self::ROOT_PHASE: return $this->rootElementPhase($token); break;
- case self::MAIN_PHASE: return $this->mainPhase($token); break;
- case self::END_PHASE : return $this->trailingEndPhase($token); break;
- }
- }
-
- private function initPhase($token) {
- /* Initially, the tree construction stage must handle each token
- emitted from the tokenisation stage as follows: */
-
- /* A DOCTYPE token that is marked as being in error
- A comment token
- A start tag token
- An end tag token
- A character token that is not one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE
- An end-of-file token */
- if((isset($token['error']) && $token['error']) ||
- $token['type'] === HTML5::COMMENT ||
- $token['type'] === HTML5::STARTTAG ||
- $token['type'] === HTML5::ENDTAG ||
- $token['type'] === HTML5::EOF ||
- ($token['type'] === HTML5::CHARACTR && isset($token['data']) &&
- !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']))) {
- /* This specification does not define how to handle this case. In
- particular, user agents may ignore the entirety of this specification
- altogether for such documents, and instead invoke special parse modes
- with a greater emphasis on backwards compatibility. */
-
- $this->phase = self::ROOT_PHASE;
- return $this->rootElementPhase($token);
-
- /* A DOCTYPE token marked as being correct */
- } elseif(isset($token['error']) && !$token['error']) {
- /* Append a DocumentType node to the Document node, with the name
- attribute set to the name given in the DOCTYPE token (which will be
- "HTML"), and the other attributes specific to DocumentType objects
- set to null, empty lists, or the empty string as appropriate. */
- $doctype = new DOMDocumentType(null, null, 'HTML');
-
- /* Then, switch to the root element phase of the tree construction
- stage. */
- $this->phase = self::ROOT_PHASE;
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- } elseif(isset($token['data']) && preg_match('/^[\t\n\x0b\x0c ]+$/',
- $token['data'])) {
- /* Append that character to the Document node. */
- $text = $this->dom->createTextNode($token['data']);
- $this->dom->appendChild($text);
- }
- }
-
- private function rootElementPhase($token) {
- /* After the initial phase, as each token is emitted from the tokenisation
- stage, it must be processed as described in this section. */
-
- /* A DOCTYPE token */
- if($token['type'] === HTML5::DOCTYPE) {
- // Parse error. Ignore the token.
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the Document object with the data
- attribute set to the data given in the comment token. */
- $comment = $this->dom->createComment($token['data']);
- $this->dom->appendChild($comment);
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- } elseif($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append that character to the Document node. */
- $text = $this->dom->createTextNode($token['data']);
- $this->dom->appendChild($text);
-
- /* A character token that is not one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED
- (FF), or U+0020 SPACE
- A start tag token
- An end tag token
- An end-of-file token */
- } elseif(($token['type'] === HTML5::CHARACTR &&
- !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
- $token['type'] === HTML5::STARTTAG ||
- $token['type'] === HTML5::ENDTAG ||
- $token['type'] === HTML5::EOF) {
- /* Create an HTMLElement node with the tag name html, in the HTML
- namespace. Append it to the Document object. Switch to the main
- phase and reprocess the current token. */
- $html = $this->dom->createElement('html');
- $this->dom->appendChild($html);
- $this->stack[] = $html;
-
- $this->phase = self::MAIN_PHASE;
- return $this->mainPhase($token);
- }
- }
-
- private function mainPhase($token) {
- /* Tokens in the main phase must be handled as follows: */
-
- /* A DOCTYPE token */
- if($token['type'] === HTML5::DOCTYPE) {
- // Parse error. Ignore the token.
-
- /* A start tag token with the tag name "html" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') {
- /* If this start tag token was not the first start tag token, then
- it is a parse error. */
-
- /* For each attribute on the token, check to see if the attribute
- is already present on the top element of the stack of open elements.
- If it is not, add the attribute and its corresponding value to that
- element. */
- foreach($token['attr'] as $attr) {
- if(!$this->stack[0]->hasAttribute($attr['name'])) {
- $this->stack[0]->setAttribute($attr['name'], $attr['value']);
- }
- }
-
- /* An end-of-file token */
- } elseif($token['type'] === HTML5::EOF) {
- /* Generate implied end tags. */
- $this->generateImpliedEndTags();
-
- /* Anything else. */
- } else {
- /* Depends on the insertion mode: */
- switch($this->mode) {
- case self::BEFOR_HEAD: return $this->beforeHead($token); break;
- case self::IN_HEAD: return $this->inHead($token); break;
- case self::AFTER_HEAD: return $this->afterHead($token); break;
- case self::IN_BODY: return $this->inBody($token); break;
- case self::IN_TABLE: return $this->inTable($token); break;
- case self::IN_CAPTION: return $this->inCaption($token); break;
- case self::IN_CGROUP: return $this->inColumnGroup($token); break;
- case self::IN_TBODY: return $this->inTableBody($token); break;
- case self::IN_ROW: return $this->inRow($token); break;
- case self::IN_CELL: return $this->inCell($token); break;
- case self::IN_SELECT: return $this->inSelect($token); break;
- case self::AFTER_BODY: return $this->afterBody($token); break;
- case self::IN_FRAME: return $this->inFrameset($token); break;
- case self::AFTR_FRAME: return $this->afterFrameset($token); break;
- case self::END_PHASE: return $this->trailingEndPhase($token); break;
- }
- }
- }
-
- private function beforeHead($token) {
- /* Handle the token as follows: */
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append the character to the current node. */
- $this->insertText($token['data']);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data attribute
- set to the data given in the comment token. */
- $this->insertComment($token['data']);
-
- /* A start tag token with the tag name "head" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') {
- /* Create an element for the token, append the new element to the
- current node and push it onto the stack of open elements. */
- $element = $this->insertElement($token);
-
- /* Set the head element pointer to this new element node. */
- $this->head_pointer = $element;
-
- /* Change the insertion mode to "in head". */
- $this->mode = self::IN_HEAD;
-
- /* A start tag token whose tag name is one of: "base", "link", "meta",
- "script", "style", "title". Or an end tag with the tag name "html".
- Or a character token that is not one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE. Or any other start tag token */
- } elseif($token['type'] === HTML5::STARTTAG ||
- ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') ||
- ($token['type'] === HTML5::CHARACTR && !preg_match('/^[\t\n\x0b\x0c ]$/',
- $token['data']))) {
- /* Act as if a start tag token with the tag name "head" and no
- attributes had been seen, then reprocess the current token. */
- $this->beforeHead(array(
- 'name' => 'head',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- return $this->inHead($token);
-
- /* Any other end tag */
- } elseif($token['type'] === HTML5::ENDTAG) {
- /* Parse error. Ignore the token. */
- }
- }
-
- private function inHead($token) {
- /* Handle the token as follows: */
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE.
-
- THIS DIFFERS FROM THE SPEC: If the current node is either a title, style
- or script element, append the character to the current node regardless
- of its content. */
- if(($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || (
- $token['type'] === HTML5::CHARACTR && in_array(end($this->stack)->nodeName,
- array('title', 'style', 'script')))) {
- /* Append the character to the current node. */
- $this->insertText($token['data']);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data attribute
- set to the data given in the comment token. */
- $this->insertComment($token['data']);
-
- } elseif($token['type'] === HTML5::ENDTAG &&
- in_array($token['name'], array('title', 'style', 'script'))) {
- array_pop($this->stack);
- return HTML5::PCDATA;
-
- /* A start tag with the tag name "title" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') {
- /* Create an element for the token and append the new element to the
- node pointed to by the head element pointer, or, if that is null
- (innerHTML case), to the current node. */
- if($this->head_pointer !== null) {
- $element = $this->insertElement($token, false);
- $this->head_pointer->appendChild($element);
-
- } else {
- $element = $this->insertElement($token);
- }
-
- /* Switch the tokeniser's content model flag to the RCDATA state. */
- return HTML5::RCDATA;
-
- /* A start tag with the tag name "style" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') {
- /* Create an element for the token and append the new element to the
- node pointed to by the head element pointer, or, if that is null
- (innerHTML case), to the current node. */
- if($this->head_pointer !== null) {
- $element = $this->insertElement($token, false);
- $this->head_pointer->appendChild($element);
-
- } else {
- $this->insertElement($token);
- }
-
- /* Switch the tokeniser's content model flag to the CDATA state. */
- return HTML5::CDATA;
-
- /* A start tag with the tag name "script" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') {
- /* Create an element for the token. */
- $element = $this->insertElement($token, false);
- $this->head_pointer->appendChild($element);
-
- /* Switch the tokeniser's content model flag to the CDATA state. */
- return HTML5::CDATA;
-
- /* A start tag with the tag name "base", "link", or "meta" */
- } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('base', 'link', 'meta'))) {
- /* Create an element for the token and append the new element to the
- node pointed to by the head element pointer, or, if that is null
- (innerHTML case), to the current node. */
- if($this->head_pointer !== null) {
- $element = $this->insertElement($token, false);
- $this->head_pointer->appendChild($element);
- array_pop($this->stack);
-
- } else {
- $this->insertElement($token);
- }
-
- /* An end tag with the tag name "head" */
- } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') {
- /* If the current node is a head element, pop the current node off
- the stack of open elements. */
- if($this->head_pointer->isSameNode(end($this->stack))) {
- array_pop($this->stack);
-
- /* Otherwise, this is a parse error. */
- } else {
- // k
- }
-
- /* Change the insertion mode to "after head". */
- $this->mode = self::AFTER_HEAD;
-
- /* A start tag with the tag name "head" or an end tag except "html". */
- } elseif(($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') ||
- ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html')) {
- // Parse error. Ignore the token.
-
- /* Anything else */
- } else {
- /* If the current node is a head element, act as if an end tag
- token with the tag name "head" had been seen. */
- if($this->head_pointer->isSameNode(end($this->stack))) {
- $this->inHead(array(
- 'name' => 'head',
- 'type' => HTML5::ENDTAG
- ));
-
- /* Otherwise, change the insertion mode to "after head". */
- } else {
- $this->mode = self::AFTER_HEAD;
- }
-
- /* Then, reprocess the current token. */
- return $this->afterHead($token);
- }
- }
-
- private function afterHead($token) {
- /* Handle the token as follows: */
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append the character to the current node. */
- $this->insertText($token['data']);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data attribute
- set to the data given in the comment token. */
- $this->insertComment($token['data']);
-
- /* A start tag token with the tag name "body" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') {
- /* Insert a body element for the token. */
- $this->insertElement($token);
-
- /* Change the insertion mode to "in body". */
- $this->mode = self::IN_BODY;
-
- /* A start tag token with the tag name "frameset" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') {
- /* Insert a frameset element for the token. */
- $this->insertElement($token);
-
- /* Change the insertion mode to "in frameset". */
- $this->mode = self::IN_FRAME;
-
- /* A start tag token whose tag name is one of: "base", "link", "meta",
- "script", "style", "title" */
- } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('base', 'link', 'meta', 'script', 'style', 'title'))) {
- /* Parse error. Switch the insertion mode back to "in head" and
- reprocess the token. */
- $this->mode = self::IN_HEAD;
- return $this->inHead($token);
-
- /* Anything else */
- } else {
- /* Act as if a start tag token with the tag name "body" and no
- attributes had been seen, and then reprocess the current token. */
- $this->afterHead(array(
- 'name' => 'body',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- return $this->inBody($token);
- }
- }
-
- private function inBody($token) {
- /* Handle the token as follows: */
-
- switch($token['type']) {
- /* A character token */
- case HTML5::CHARACTR:
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Append the token's character to the current node. */
- $this->insertText($token['data']);
- break;
-
- /* A comment token */
- case HTML5::COMMENT:
- /* Append a Comment node to the current node with the data
- attribute set to the data given in the comment token. */
- $this->insertComment($token['data']);
- break;
-
- case HTML5::STARTTAG:
- switch($token['name']) {
- /* A start tag token whose tag name is one of: "script",
- "style" */
- case 'script': case 'style':
- /* Process the token as if the insertion mode had been "in
- head". */
- return $this->inHead($token);
- break;
-
- /* A start tag token whose tag name is one of: "base", "link",
- "meta", "title" */
- case 'base': case 'link': case 'meta': case 'title':
- /* Parse error. Process the token as if the insertion mode
- had been "in head". */
- return $this->inHead($token);
- break;
-
- /* A start tag token with the tag name "body" */
- case 'body':
- /* Parse error. If the second element on the stack of open
- elements is not a body element, or, if the stack of open
- elements has only one node on it, then ignore the token.
- (innerHTML case) */
- if(count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') {
- // Ignore
-
- /* Otherwise, for each attribute on the token, check to see
- if the attribute is already present on the body element (the
- second element) on the stack of open elements. If it is not,
- add the attribute and its corresponding value to that
- element. */
- } else {
- foreach($token['attr'] as $attr) {
- if(!$this->stack[1]->hasAttribute($attr['name'])) {
- $this->stack[1]->setAttribute($attr['name'], $attr['value']);
- }
- }
- }
- break;
-
- /* A start tag whose tag name is one of: "address",
- "blockquote", "center", "dir", "div", "dl", "fieldset",
- "listing", "menu", "ol", "p", "ul" */
- case 'address': case 'blockquote': case 'center': case 'dir':
- case 'div': case 'dl': case 'fieldset': case 'listing':
- case 'menu': case 'ol': case 'p': case 'ul':
- /* If the stack of open elements has a p element in scope,
- then act as if an end tag with the tag name p had been
- seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
- break;
-
- /* A start tag whose tag name is "form" */
- case 'form':
- /* If the form element pointer is not null, ignore the
- token with a parse error. */
- if($this->form_pointer !== null) {
- // Ignore.
-
- /* Otherwise: */
- } else {
- /* If the stack of open elements has a p element in
- scope, then act as if an end tag with the tag name p
- had been seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token, and set the
- form element pointer to point to the element created. */
- $element = $this->insertElement($token);
- $this->form_pointer = $element;
- }
- break;
-
- /* A start tag whose tag name is "li", "dd" or "dt" */
- case 'li': case 'dd': case 'dt':
- /* If the stack of open elements has a p element in scope,
- then act as if an end tag with the tag name p had been
- seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- $stack_length = count($this->stack) - 1;
-
- for($n = $stack_length; 0 <= $n; $n--) {
- /* 1. Initialise node to be the current node (the
- bottommost node of the stack). */
- $stop = false;
- $node = $this->stack[$n];
- $cat = $this->getElementCategory($node->tagName);
-
- /* 2. If node is an li, dd or dt element, then pop all
- the nodes from the current node up to node, including
- node, then stop this algorithm. */
- if($token['name'] === $node->tagName || ($token['name'] !== 'li'
- && ($node->tagName === 'dd' || $node->tagName === 'dt'))) {
- for($x = $stack_length; $x >= $n ; $x--) {
- array_pop($this->stack);
- }
-
- break;
- }
-
- /* 3. If node is not in the formatting category, and is
- not in the phrasing category, and is not an address or
- div element, then stop this algorithm. */
- if($cat !== self::FORMATTING && $cat !== self::PHRASING &&
- $node->tagName !== 'address' && $node->tagName !== 'div') {
- break;
- }
- }
-
- /* Finally, insert an HTML element with the same tag
- name as the token's. */
- $this->insertElement($token);
- break;
-
- /* A start tag token whose tag name is "plaintext" */
- case 'plaintext':
- /* If the stack of open elements has a p element in scope,
- then act as if an end tag with the tag name p had been
- seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- return HTML5::PLAINTEXT;
- break;
-
- /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4",
- "h5", "h6" */
- case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
- /* If the stack of open elements has a p element in scope,
- then act as if an end tag with the tag name p had been seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* If the stack of open elements has in scope an element whose
- tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
- this is a parse error; pop elements from the stack until an
- element with one of those tag names has been popped from the
- stack. */
- while($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) {
- array_pop($this->stack);
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
- break;
-
- /* A start tag whose tag name is "a" */
- case 'a':
- /* If the list of active formatting elements contains
- an element whose tag name is "a" between the end of the
- list and the last marker on the list (or the start of
- the list if there is no marker on the list), then this
- is a parse error; act as if an end tag with the tag name
- "a" had been seen, then remove that element from the list
- of active formatting elements and the stack of open
- elements if the end tag didn't already remove it (it
- might not have if the element is not in table scope). */
- $leng = count($this->a_formatting);
-
- for($n = $leng - 1; $n >= 0; $n--) {
- if($this->a_formatting[$n] === self::MARKER) {
- break;
-
- } elseif($this->a_formatting[$n]->nodeName === 'a') {
- $this->emitToken(array(
- 'name' => 'a',
- 'type' => HTML5::ENDTAG
- ));
- break;
- }
- }
-
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $el = $this->insertElement($token);
-
- /* Add that element to the list of active formatting
- elements. */
- $this->a_formatting[] = $el;
- break;
-
- /* A start tag whose tag name is one of: "b", "big", "em", "font",
- "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
- case 'b': case 'big': case 'em': case 'font': case 'i':
- case 'nobr': case 's': case 'small': case 'strike':
- case 'strong': case 'tt': case 'u':
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $el = $this->insertElement($token);
-
- /* Add that element to the list of active formatting
- elements. */
- $this->a_formatting[] = $el;
- break;
-
- /* A start tag token whose tag name is "button" */
- case 'button':
- /* If the stack of open elements has a button element in scope,
- then this is a parse error; act as if an end tag with the tag
- name "button" had been seen, then reprocess the token. (We don't
- do that. Unnecessary.) */
- if($this->elementInScope('button')) {
- $this->inBody(array(
- 'name' => 'button',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Insert a marker at the end of the list of active
- formatting elements. */
- $this->a_formatting[] = self::MARKER;
- break;
-
- /* A start tag token whose tag name is one of: "marquee", "object" */
- case 'marquee': case 'object':
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Insert a marker at the end of the list of active
- formatting elements. */
- $this->a_formatting[] = self::MARKER;
- break;
-
- /* A start tag token whose tag name is "xmp" */
- case 'xmp':
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Switch the content model flag to the CDATA state. */
- return HTML5::CDATA;
- break;
-
- /* A start tag whose tag name is "table" */
- case 'table':
- /* If the stack of open elements has a p element in scope,
- then act as if an end tag with the tag name p had been seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Change the insertion mode to "in table". */
- $this->mode = self::IN_TABLE;
- break;
-
- /* A start tag whose tag name is one of: "area", "basefont",
- "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */
- case 'area': case 'basefont': case 'bgsound': case 'br':
- case 'embed': case 'img': case 'param': case 'spacer':
- case 'wbr':
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Immediately pop the current node off the stack of open elements. */
- array_pop($this->stack);
- break;
-
- /* A start tag whose tag name is "hr" */
- case 'hr':
- /* If the stack of open elements has a p element in scope,
- then act as if an end tag with the tag name p had been seen. */
- if($this->elementInScope('p')) {
- $this->emitToken(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Immediately pop the current node off the stack of open elements. */
- array_pop($this->stack);
- break;
-
- /* A start tag whose tag name is "image" */
- case 'image':
- /* Parse error. Change the token's tag name to "img" and
- reprocess it. (Don't ask.) */
- $token['name'] = 'img';
- return $this->inBody($token);
- break;
-
- /* A start tag whose tag name is "input" */
- case 'input':
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an input element for the token. */
- $element = $this->insertElement($token, false);
-
- /* If the form element pointer is not null, then associate the
- input element with the form element pointed to by the form
- element pointer. */
- $this->form_pointer !== null
- ? $this->form_pointer->appendChild($element)
- : end($this->stack)->appendChild($element);
-
- /* Pop that input element off the stack of open elements. */
- array_pop($this->stack);
- break;
-
- /* A start tag whose tag name is "isindex" */
- case 'isindex':
- /* Parse error. */
- // w/e
-
- /* If the form element pointer is not null,
- then ignore the token. */
- if($this->form_pointer === null) {
- /* Act as if a start tag token with the tag name "form" had
- been seen. */
- $this->inBody(array(
- 'name' => 'body',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- /* Act as if a start tag token with the tag name "hr" had
- been seen. */
- $this->inBody(array(
- 'name' => 'hr',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- /* Act as if a start tag token with the tag name "p" had
- been seen. */
- $this->inBody(array(
- 'name' => 'p',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- /* Act as if a start tag token with the tag name "label"
- had been seen. */
- $this->inBody(array(
- 'name' => 'label',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- /* Act as if a stream of character tokens had been seen. */
- $this->insertText('This is a searchable index. '.
- 'Insert your search keywords here: ');
-
- /* Act as if a start tag token with the tag name "input"
- had been seen, with all the attributes from the "isindex"
- token, except with the "name" attribute set to the value
- "isindex" (ignoring any explicit "name" attribute). */
- $attr = $token['attr'];
- $attr[] = array('name' => 'name', 'value' => 'isindex');
-
- $this->inBody(array(
- 'name' => 'input',
- 'type' => HTML5::STARTTAG,
- 'attr' => $attr
- ));
-
- /* Act as if a stream of character tokens had been seen
- (see below for what they should say). */
- $this->insertText('This is a searchable index. '.
- 'Insert your search keywords here: ');
-
- /* Act as if an end tag token with the tag name "label"
- had been seen. */
- $this->inBody(array(
- 'name' => 'label',
- 'type' => HTML5::ENDTAG
- ));
-
- /* Act as if an end tag token with the tag name "p" had
- been seen. */
- $this->inBody(array(
- 'name' => 'p',
- 'type' => HTML5::ENDTAG
- ));
-
- /* Act as if a start tag token with the tag name "hr" had
- been seen. */
- $this->inBody(array(
- 'name' => 'hr',
- 'type' => HTML5::ENDTAG
- ));
-
- /* Act as if an end tag token with the tag name "form" had
- been seen. */
- $this->inBody(array(
- 'name' => 'form',
- 'type' => HTML5::ENDTAG
- ));
- }
- break;
-
- /* A start tag whose tag name is "textarea" */
- case 'textarea':
- $this->insertElement($token);
-
- /* Switch the tokeniser's content model flag to the
- RCDATA state. */
- return HTML5::RCDATA;
- break;
-
- /* A start tag whose tag name is one of: "iframe", "noembed",
- "noframes" */
- case 'iframe': case 'noembed': case 'noframes':
- $this->insertElement($token);
-
- /* Switch the tokeniser's content model flag to the CDATA state. */
- return HTML5::CDATA;
- break;
-
- /* A start tag whose tag name is "select" */
- case 'select':
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Change the insertion mode to "in select". */
- $this->mode = self::IN_SELECT;
- break;
-
- /* A start or end tag whose tag name is one of: "caption", "col",
- "colgroup", "frame", "frameset", "head", "option", "optgroup",
- "tbody", "td", "tfoot", "th", "thead", "tr". */
- case 'caption': case 'col': case 'colgroup': case 'frame':
- case 'frameset': case 'head': case 'option': case 'optgroup':
- case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead':
- case 'tr':
- // Parse error. Ignore the token.
- break;
-
- /* A start or end tag whose tag name is one of: "event-source",
- "section", "nav", "article", "aside", "header", "footer",
- "datagrid", "command" */
- case 'event-source': case 'section': case 'nav': case 'article':
- case 'aside': case 'header': case 'footer': case 'datagrid':
- case 'command':
- // Work in progress!
- break;
-
- /* A start tag token not covered by the previous entries */
- default:
- /* Reconstruct the active formatting elements, if any. */
- $this->reconstructActiveFormattingElements();
-
- $this->insertElement($token, true, true);
- break;
- }
- break;
-
- case HTML5::ENDTAG:
- switch($token['name']) {
- /* An end tag with the tag name "body" */
- case 'body':
- /* If the second element in the stack of open elements is
- not a body element, this is a parse error. Ignore the token.
- (innerHTML case) */
- if(count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') {
- // Ignore.
-
- /* If the current node is not the body element, then this
- is a parse error. */
- } elseif(end($this->stack)->nodeName !== 'body') {
- // Parse error.
- }
-
- /* Change the insertion mode to "after body". */
- $this->mode = self::AFTER_BODY;
- break;
-
- /* An end tag with the tag name "html" */
- case 'html':
- /* Act as if an end tag with tag name "body" had been seen,
- then, if that token wasn't ignored, reprocess the current
- token. */
- $this->inBody(array(
- 'name' => 'body',
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->afterBody($token);
- break;
-
- /* An end tag whose tag name is one of: "address", "blockquote",
- "center", "dir", "div", "dl", "fieldset", "listing", "menu",
- "ol", "pre", "ul" */
- case 'address': case 'blockquote': case 'center': case 'dir':
- case 'div': case 'dl': case 'fieldset': case 'listing':
- case 'menu': case 'ol': case 'pre': case 'ul':
- /* If the stack of open elements has an element in scope
- with the same tag name as that of the token, then generate
- implied end tags. */
- if($this->elementInScope($token['name'])) {
- $this->generateImpliedEndTags();
-
- /* Now, if the current node is not an element with
- the same tag name as that of the token, then this
- is a parse error. */
- // w/e
-
- /* If the stack of open elements has an element in
- scope with the same tag name as that of the token,
- then pop elements from this stack until an element
- with that tag name has been popped from the stack. */
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- if($this->stack[$n]->nodeName === $token['name']) {
- $n = -1;
- }
-
- array_pop($this->stack);
- }
- }
- break;
-
- /* An end tag whose tag name is "form" */
- case 'form':
- /* If the stack of open elements has an element in scope
- with the same tag name as that of the token, then generate
- implied end tags. */
- if($this->elementInScope($token['name'])) {
- $this->generateImpliedEndTags();
-
- }
-
- if(end($this->stack)->nodeName !== $token['name']) {
- /* Now, if the current node is not an element with the
- same tag name as that of the token, then this is a parse
- error. */
- // w/e
-
- } else {
- /* Otherwise, if the current node is an element with
- the same tag name as that of the token pop that element
- from the stack. */
- array_pop($this->stack);
- }
-
- /* In any case, set the form element pointer to null. */
- $this->form_pointer = null;
- break;
-
- /* An end tag whose tag name is "p" */
- case 'p':
- /* If the stack of open elements has a p element in scope,
- then generate implied end tags, except for p elements. */
- if($this->elementInScope('p')) {
- $this->generateImpliedEndTags(array('p'));
-
- /* If the current node is not a p element, then this is
- a parse error. */
- // k
-
- /* If the stack of open elements has a p element in
- scope, then pop elements from this stack until the stack
- no longer has a p element in scope. */
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- if($this->elementInScope('p')) {
- array_pop($this->stack);
-
- } else {
- break;
- }
- }
- }
- break;
-
- /* An end tag whose tag name is "dd", "dt", or "li" */
- case 'dd': case 'dt': case 'li':
- /* If the stack of open elements has an element in scope
- whose tag name matches the tag name of the token, then
- generate implied end tags, except for elements with the
- same tag name as the token. */
- if($this->elementInScope($token['name'])) {
- $this->generateImpliedEndTags(array($token['name']));
-
- /* If the current node is not an element with the same
- tag name as the token, then this is a parse error. */
- // w/e
-
- /* If the stack of open elements has an element in scope
- whose tag name matches the tag name of the token, then
- pop elements from this stack until an element with that
- tag name has been popped from the stack. */
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- if($this->stack[$n]->nodeName === $token['name']) {
- $n = -1;
- }
-
- array_pop($this->stack);
- }
- }
- break;
-
- /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4",
- "h5", "h6" */
- case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
- $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
-
- /* If the stack of open elements has in scope an element whose
- tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
- generate implied end tags. */
- if($this->elementInScope($elements)) {
- $this->generateImpliedEndTags();
-
- /* Now, if the current node is not an element with the same
- tag name as that of the token, then this is a parse error. */
- // w/e
-
- /* If the stack of open elements has in scope an element
- whose tag name is one of "h1", "h2", "h3", "h4", "h5", or
- "h6", then pop elements from the stack until an element
- with one of those tag names has been popped from the stack. */
- while($this->elementInScope($elements)) {
- array_pop($this->stack);
- }
- }
- break;
-
- /* An end tag whose tag name is one of: "a", "b", "big", "em",
- "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
- case 'a': case 'b': case 'big': case 'em': case 'font':
- case 'i': case 'nobr': case 's': case 'small': case 'strike':
- case 'strong': case 'tt': case 'u':
- /* 1. Let the formatting element be the last element in
- the list of active formatting elements that:
- * is between the end of the list and the last scope
- marker in the list, if any, or the start of the list
- otherwise, and
- * has the same tag name as the token.
- */
- while(true) {
- for($a = count($this->a_formatting) - 1; $a >= 0; $a--) {
- if($this->a_formatting[$a] === self::MARKER) {
- break;
-
- } elseif($this->a_formatting[$a]->tagName === $token['name']) {
- $formatting_element = $this->a_formatting[$a];
- $in_stack = in_array($formatting_element, $this->stack, true);
- $fe_af_pos = $a;
- break;
- }
- }
-
- /* If there is no such node, or, if that node is
- also in the stack of open elements but the element
- is not in scope, then this is a parse error. Abort
- these steps. The token is ignored. */
- if(!isset($formatting_element) || ($in_stack &&
- !$this->elementInScope($token['name']))) {
- break;
-
- /* Otherwise, if there is such a node, but that node
- is not in the stack of open elements, then this is a
- parse error; remove the element from the list, and
- abort these steps. */
- } elseif(isset($formatting_element) && !$in_stack) {
- unset($this->a_formatting[$fe_af_pos]);
- $this->a_formatting = array_merge($this->a_formatting);
- break;
- }
-
- /* 2. Let the furthest block be the topmost node in the
- stack of open elements that is lower in the stack
- than the formatting element, and is not an element in
- the phrasing or formatting categories. There might
- not be one. */
- $fe_s_pos = array_search($formatting_element, $this->stack, true);
- $length = count($this->stack);
-
- for($s = $fe_s_pos + 1; $s < $length; $s++) {
- $category = $this->getElementCategory($this->stack[$s]->nodeName);
-
- if($category !== self::PHRASING && $category !== self::FORMATTING) {
- $furthest_block = $this->stack[$s];
- }
- }
-
- /* 3. If there is no furthest block, then the UA must
- skip the subsequent steps and instead just pop all
- the nodes from the bottom of the stack of open
- elements, from the current node up to the formatting
- element, and remove the formatting element from the
- list of active formatting elements. */
- if(!isset($furthest_block)) {
- for($n = $length - 1; $n >= $fe_s_pos; $n--) {
- array_pop($this->stack);
- }
-
- unset($this->a_formatting[$fe_af_pos]);
- $this->a_formatting = array_merge($this->a_formatting);
- break;
- }
-
- /* 4. Let the common ancestor be the element
- immediately above the formatting element in the stack
- of open elements. */
- $common_ancestor = $this->stack[$fe_s_pos - 1];
-
- /* 5. If the furthest block has a parent node, then
- remove the furthest block from its parent node. */
- if($furthest_block->parentNode !== null) {
- $furthest_block->parentNode->removeChild($furthest_block);
- }
-
- /* 6. Let a bookmark note the position of the
- formatting element in the list of active formatting
- elements relative to the elements on either side
- of it in the list. */
- $bookmark = $fe_af_pos;
-
- /* 7. Let node and last node be the furthest block.
- Follow these steps: */
- $node = $furthest_block;
- $last_node = $furthest_block;
-
- while(true) {
- for($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) {
- /* 7.1 Let node be the element immediately
- prior to node in the stack of open elements. */
- $node = $this->stack[$n];
-
- /* 7.2 If node is not in the list of active
- formatting elements, then remove node from
- the stack of open elements and then go back
- to step 1. */
- if(!in_array($node, $this->a_formatting, true)) {
- unset($this->stack[$n]);
- $this->stack = array_merge($this->stack);
-
- } else {
- break;
- }
- }
-
- /* 7.3 Otherwise, if node is the formatting
- element, then go to the next step in the overall
- algorithm. */
- if($node === $formatting_element) {
- break;
-
- /* 7.4 Otherwise, if last node is the furthest
- block, then move the aforementioned bookmark to
- be immediately after the node in the list of
- active formatting elements. */
- } elseif($last_node === $furthest_block) {
- $bookmark = array_search($node, $this->a_formatting, true) + 1;
- }
-
- /* 7.5 If node has any children, perform a
- shallow clone of node, replace the entry for
- node in the list of active formatting elements
- with an entry for the clone, replace the entry
- for node in the stack of open elements with an
- entry for the clone, and let node be the clone. */
- if($node->hasChildNodes()) {
- $clone = $node->cloneNode();
- $s_pos = array_search($node, $this->stack, true);
- $a_pos = array_search($node, $this->a_formatting, true);
-
- $this->stack[$s_pos] = $clone;
- $this->a_formatting[$a_pos] = $clone;
- $node = $clone;
- }
-
- /* 7.6 Insert last node into node, first removing
- it from its previous parent node if any. */
- if($last_node->parentNode !== null) {
- $last_node->parentNode->removeChild($last_node);
- }
-
- $node->appendChild($last_node);
-
- /* 7.7 Let last node be node. */
- $last_node = $node;
- }
-
- /* 8. Insert whatever last node ended up being in
- the previous step into the common ancestor node,
- first removing it from its previous parent node if
- any. */
- if($last_node->parentNode !== null) {
- $last_node->parentNode->removeChild($last_node);
- }
-
- $common_ancestor->appendChild($last_node);
-
- /* 9. Perform a shallow clone of the formatting
- element. */
- $clone = $formatting_element->cloneNode();
-
- /* 10. Take all of the child nodes of the furthest
- block and append them to the clone created in the
- last step. */
- while($furthest_block->hasChildNodes()) {
- $child = $furthest_block->firstChild;
- $furthest_block->removeChild($child);
- $clone->appendChild($child);
- }
-
- /* 11. Append that clone to the furthest block. */
- $furthest_block->appendChild($clone);
-
- /* 12. Remove the formatting element from the list
- of active formatting elements, and insert the clone
- into the list of active formatting elements at the
- position of the aforementioned bookmark. */
- $fe_af_pos = array_search($formatting_element, $this->a_formatting, true);
- unset($this->a_formatting[$fe_af_pos]);
- $this->a_formatting = array_merge($this->a_formatting);
-
- $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1);
- $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting));
- $this->a_formatting = array_merge($af_part1, array($clone), $af_part2);
-
- /* 13. Remove the formatting element from the stack
- of open elements, and insert the clone into the stack
- of open elements immediately after (i.e. in a more
- deeply nested position than) the position of the
- furthest block in that stack. */
- $fe_s_pos = array_search($formatting_element, $this->stack, true);
- $fb_s_pos = array_search($furthest_block, $this->stack, true);
- unset($this->stack[$fe_s_pos]);
-
- $s_part1 = array_slice($this->stack, 0, $fb_s_pos);
- $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack));
- $this->stack = array_merge($s_part1, array($clone), $s_part2);
-
- /* 14. Jump back to step 1 in this series of steps. */
- unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block);
- }
- break;
-
- /* An end tag token whose tag name is one of: "button",
- "marquee", "object" */
- case 'button': case 'marquee': case 'object':
- /* If the stack of open elements has an element in scope whose
- tag name matches the tag name of the token, then generate implied
- tags. */
- if($this->elementInScope($token['name'])) {
- $this->generateImpliedEndTags();
-
- /* Now, if the current node is not an element with the same
- tag name as the token, then this is a parse error. */
- // k
-
- /* Now, if the stack of open elements has an element in scope
- whose tag name matches the tag name of the token, then pop
- elements from the stack until that element has been popped from
- the stack, and clear the list of active formatting elements up
- to the last marker. */
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- if($this->stack[$n]->nodeName === $token['name']) {
- $n = -1;
- }
-
- array_pop($this->stack);
- }
-
- $marker = end(array_keys($this->a_formatting, self::MARKER, true));
-
- for($n = count($this->a_formatting) - 1; $n > $marker; $n--) {
- array_pop($this->a_formatting);
- }
- }
- break;
-
- /* Or an end tag whose tag name is one of: "area", "basefont",
- "bgsound", "br", "embed", "hr", "iframe", "image", "img",
- "input", "isindex", "noembed", "noframes", "param", "select",
- "spacer", "table", "textarea", "wbr" */
- case 'area': case 'basefont': case 'bgsound': case 'br':
- case 'embed': case 'hr': case 'iframe': case 'image':
- case 'img': case 'input': case 'isindex': case 'noembed':
- case 'noframes': case 'param': case 'select': case 'spacer':
- case 'table': case 'textarea': case 'wbr':
- // Parse error. Ignore the token.
- break;
-
- /* An end tag token not covered by the previous entries */
- default:
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- /* Initialise node to be the current node (the bottommost
- node of the stack). */
- $node = end($this->stack);
-
- /* If node has the same tag name as the end tag token,
- then: */
- if($token['name'] === $node->nodeName) {
- /* Generate implied end tags. */
- $this->generateImpliedEndTags();
-
- /* If the tag name of the end tag token does not
- match the tag name of the current node, this is a
- parse error. */
- // k
-
- /* Pop all the nodes from the current node up to
- node, including node, then stop this algorithm. */
- for($x = count($this->stack) - $n; $x >= $n; $x--) {
- array_pop($this->stack);
- }
-
- } else {
- $category = $this->getElementCategory($node);
-
- if($category !== self::SPECIAL && $category !== self::SCOPING) {
- /* Otherwise, if node is in neither the formatting
- category nor the phrasing category, then this is a
- parse error. Stop this algorithm. The end tag token
- is ignored. */
- return false;
- }
- }
- }
- break;
- }
- break;
- }
- }
-
- private function inTable($token) {
- $clear = array('html', 'table');
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append the character to the current node. */
- $text = $this->dom->createTextNode($token['data']);
- end($this->stack)->appendChild($text);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data
- attribute set to the data given in the comment token. */
- $comment = $this->dom->createComment($token['data']);
- end($this->stack)->appendChild($comment);
-
- /* A start tag whose tag name is "caption" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- $token['name'] === 'caption') {
- /* Clear the stack back to a table context. */
- $this->clearStackToTableContext($clear);
-
- /* Insert a marker at the end of the list of active
- formatting elements. */
- $this->a_formatting[] = self::MARKER;
-
- /* Insert an HTML element for the token, then switch the
- insertion mode to "in caption". */
- $this->insertElement($token);
- $this->mode = self::IN_CAPTION;
-
- /* A start tag whose tag name is "colgroup" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- $token['name'] === 'colgroup') {
- /* Clear the stack back to a table context. */
- $this->clearStackToTableContext($clear);
-
- /* Insert an HTML element for the token, then switch the
- insertion mode to "in column group". */
- $this->insertElement($token);
- $this->mode = self::IN_CGROUP;
-
- /* A start tag whose tag name is "col" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- $token['name'] === 'col') {
- $this->inTable(array(
- 'name' => 'colgroup',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- $this->inColumnGroup($token);
-
- /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */
- } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('tbody', 'tfoot', 'thead'))) {
- /* Clear the stack back to a table context. */
- $this->clearStackToTableContext($clear);
-
- /* Insert an HTML element for the token, then switch the insertion
- mode to "in table body". */
- $this->insertElement($token);
- $this->mode = self::IN_TBODY;
-
- /* A start tag whose tag name is one of: "td", "th", "tr" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- in_array($token['name'], array('td', 'th', 'tr'))) {
- /* Act as if a start tag token with the tag name "tbody" had been
- seen, then reprocess the current token. */
- $this->inTable(array(
- 'name' => 'tbody',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- return $this->inTableBody($token);
-
- /* A start tag whose tag name is "table" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- $token['name'] === 'table') {
- /* Parse error. Act as if an end tag token with the tag name "table"
- had been seen, then, if that token wasn't ignored, reprocess the
- current token. */
- $this->inTable(array(
- 'name' => 'table',
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->mainPhase($token);
-
- /* An end tag whose tag name is "table" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- $token['name'] === 'table') {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as the token, this is a parse error.
- Ignore the token. (innerHTML case) */
- if(!$this->elementInScope($token['name'], true)) {
- return false;
-
- /* Otherwise: */
- } else {
- /* Generate implied end tags. */
- $this->generateImpliedEndTags();
-
- /* Now, if the current node is not a table element, then this
- is a parse error. */
- // w/e
-
- /* Pop elements from this stack until a table element has been
- popped from the stack. */
- while(true) {
- $current = end($this->stack)->nodeName;
- array_pop($this->stack);
-
- if($current === 'table') {
- break;
- }
- }
-
- /* Reset the insertion mode appropriately. */
- $this->resetInsertionMode();
- }
-
- /* An end tag whose tag name is one of: "body", "caption", "col",
- "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
- } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
- array('body', 'caption', 'col', 'colgroup', 'html', 'tbody', 'td',
- 'tfoot', 'th', 'thead', 'tr'))) {
- // Parse error. Ignore the token.
-
- /* Anything else */
- } else {
- /* Parse error. Process the token as if the insertion mode was "in
- body", with the following exception: */
-
- /* If the current node is a table, tbody, tfoot, thead, or tr
- element, then, whenever a node would be inserted into the current
- node, it must instead be inserted into the foster parent element. */
- if(in_array(end($this->stack)->nodeName,
- array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
- /* The foster parent element is the parent element of the last
- table element in the stack of open elements, if there is a
- table element and it has such a parent element. If there is no
- table element in the stack of open elements (innerHTML case),
- then the foster parent element is the first element in the
- stack of open elements (the html element). Otherwise, if there
- is a table element in the stack of open elements, but the last
- table element in the stack of open elements has no parent, or
- its parent node is not an element, then the foster parent
- element is the element before the last table element in the
- stack of open elements. */
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- if($this->stack[$n]->nodeName === 'table') {
- $table = $this->stack[$n];
- break;
- }
- }
-
- if(isset($table) && $table->parentNode !== null) {
- $this->foster_parent = $table->parentNode;
-
- } elseif(!isset($table)) {
- $this->foster_parent = $this->stack[0];
-
- } elseif(isset($table) && ($table->parentNode === null ||
- $table->parentNode->nodeType !== XML_ELEMENT_NODE)) {
- $this->foster_parent = $this->stack[$n - 1];
- }
- }
-
- $this->inBody($token);
- }
- }
-
- private function inCaption($token) {
- /* An end tag whose tag name is "caption" */
- if($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as the token, this is a parse error.
- Ignore the token. (innerHTML case) */
- if(!$this->elementInScope($token['name'], true)) {
- // Ignore
-
- /* Otherwise: */
- } else {
- /* Generate implied end tags. */
- $this->generateImpliedEndTags();
-
- /* Now, if the current node is not a caption element, then this
- is a parse error. */
- // w/e
-
- /* Pop elements from this stack until a caption element has
- been popped from the stack. */
- while(true) {
- $node = end($this->stack)->nodeName;
- array_pop($this->stack);
-
- if($node === 'caption') {
- break;
- }
- }
-
- /* Clear the list of active formatting elements up to the last
- marker. */
- $this->clearTheActiveFormattingElementsUpToTheLastMarker();
-
- /* Switch the insertion mode to "in table". */
- $this->mode = self::IN_TABLE;
- }
-
- /* A start tag whose tag name is one of: "caption", "col", "colgroup",
- "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag
- name is "table" */
- } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
- 'thead', 'tr'))) || ($token['type'] === HTML5::ENDTAG &&
- $token['name'] === 'table')) {
- /* Parse error. Act as if an end tag with the tag name "caption"
- had been seen, then, if that token wasn't ignored, reprocess the
- current token. */
- $this->inCaption(array(
- 'name' => 'caption',
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->inTable($token);
-
- /* An end tag whose tag name is one of: "body", "col", "colgroup",
- "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
- } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
- array('body', 'col', 'colgroup', 'html', 'tbody', 'tfoot', 'th',
- 'thead', 'tr'))) {
- // Parse error. Ignore the token.
-
- /* Anything else */
- } else {
- /* Process the token as if the insertion mode was "in body". */
- $this->inBody($token);
- }
- }
-
- private function inColumnGroup($token) {
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append the character to the current node. */
- $text = $this->dom->createTextNode($token['data']);
- end($this->stack)->appendChild($text);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data
- attribute set to the data given in the comment token. */
- $comment = $this->dom->createComment($token['data']);
- end($this->stack)->appendChild($comment);
-
- /* A start tag whose tag name is "col" */
- } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') {
- /* Insert a col element for the token. Immediately pop the current
- node off the stack of open elements. */
- $this->insertElement($token);
- array_pop($this->stack);
-
- /* An end tag whose tag name is "colgroup" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- $token['name'] === 'colgroup') {
- /* If the current node is the root html element, then this is a
- parse error, ignore the token. (innerHTML case) */
- if(end($this->stack)->nodeName === 'html') {
- // Ignore
-
- /* Otherwise, pop the current node (which will be a colgroup
- element) from the stack of open elements. Switch the insertion
- mode to "in table". */
- } else {
- array_pop($this->stack);
- $this->mode = self::IN_TABLE;
- }
-
- /* An end tag whose tag name is "col" */
- } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') {
- /* Parse error. Ignore the token. */
-
- /* Anything else */
- } else {
- /* Act as if an end tag with the tag name "colgroup" had been seen,
- and then, if that token wasn't ignored, reprocess the current token. */
- $this->inColumnGroup(array(
- 'name' => 'colgroup',
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->inTable($token);
- }
- }
-
- private function inTableBody($token) {
- $clear = array('tbody', 'tfoot', 'thead', 'html');
-
- /* A start tag whose tag name is "tr" */
- if($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') {
- /* Clear the stack back to a table body context. */
- $this->clearStackToTableContext($clear);
-
- /* Insert a tr element for the token, then switch the insertion
- mode to "in row". */
- $this->insertElement($token);
- $this->mode = self::IN_ROW;
-
- /* A start tag whose tag name is one of: "th", "td" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- ($token['name'] === 'th' || $token['name'] === 'td')) {
- /* Parse error. Act as if a start tag with the tag name "tr" had
- been seen, then reprocess the current token. */
- $this->inTableBody(array(
- 'name' => 'tr',
- 'type' => HTML5::STARTTAG,
- 'attr' => array()
- ));
-
- return $this->inRow($token);
-
- /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as the token, this is a parse error.
- Ignore the token. */
- if(!$this->elementInScope($token['name'], true)) {
- // Ignore
-
- /* Otherwise: */
- } else {
- /* Clear the stack back to a table body context. */
- $this->clearStackToTableContext($clear);
-
- /* Pop the current node from the stack of open elements. Switch
- the insertion mode to "in table". */
- array_pop($this->stack);
- $this->mode = self::IN_TABLE;
- }
-
- /* A start tag whose tag name is one of: "caption", "col", "colgroup",
- "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */
- } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead'))) ||
- ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')) {
- /* If the stack of open elements does not have a tbody, thead, or
- tfoot element in table scope, this is a parse error. Ignore the
- token. (innerHTML case) */
- if(!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) {
- // Ignore.
-
- /* Otherwise: */
- } else {
- /* Clear the stack back to a table body context. */
- $this->clearStackToTableContext($clear);
-
- /* Act as if an end tag with the same tag name as the current
- node ("tbody", "tfoot", or "thead") had been seen, then
- reprocess the current token. */
- $this->inTableBody(array(
- 'name' => end($this->stack)->nodeName,
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->mainPhase($token);
- }
-
- /* An end tag whose tag name is one of: "body", "caption", "col",
- "colgroup", "html", "td", "th", "tr" */
- } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
- array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
- /* Parse error. Ignore the token. */
-
- /* Anything else */
- } else {
- /* Process the token as if the insertion mode was "in table". */
- $this->inTable($token);
- }
- }
-
- private function inRow($token) {
- $clear = array('tr', 'html');
-
- /* A start tag whose tag name is one of: "th", "td" */
- if($token['type'] === HTML5::STARTTAG &&
- ($token['name'] === 'th' || $token['name'] === 'td')) {
- /* Clear the stack back to a table row context. */
- $this->clearStackToTableContext($clear);
-
- /* Insert an HTML element for the token, then switch the insertion
- mode to "in cell". */
- $this->insertElement($token);
- $this->mode = self::IN_CELL;
-
- /* Insert a marker at the end of the list of active formatting
- elements. */
- $this->a_formatting[] = self::MARKER;
-
- /* An end tag whose tag name is "tr" */
- } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as the token, this is a parse error.
- Ignore the token. (innerHTML case) */
- if(!$this->elementInScope($token['name'], true)) {
- // Ignore.
-
- /* Otherwise: */
- } else {
- /* Clear the stack back to a table row context. */
- $this->clearStackToTableContext($clear);
-
- /* Pop the current node (which will be a tr element) from the
- stack of open elements. Switch the insertion mode to "in table
- body". */
- array_pop($this->stack);
- $this->mode = self::IN_TBODY;
- }
-
- /* A start tag whose tag name is one of: "caption", "col", "colgroup",
- "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */
- } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr'))) {
- /* Act as if an end tag with the tag name "tr" had been seen, then,
- if that token wasn't ignored, reprocess the current token. */
- $this->inRow(array(
- 'name' => 'tr',
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->inCell($token);
-
- /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as the token, this is a parse error.
- Ignore the token. */
- if(!$this->elementInScope($token['name'], true)) {
- // Ignore.
-
- /* Otherwise: */
- } else {
- /* Otherwise, act as if an end tag with the tag name "tr" had
- been seen, then reprocess the current token. */
- $this->inRow(array(
- 'name' => 'tr',
- 'type' => HTML5::ENDTAG
- ));
-
- return $this->inCell($token);
- }
-
- /* An end tag whose tag name is one of: "body", "caption", "col",
- "colgroup", "html", "td", "th" */
- } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
- array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
- /* Parse error. Ignore the token. */
-
- /* Anything else */
- } else {
- /* Process the token as if the insertion mode was "in table". */
- $this->inTable($token);
- }
- }
-
- private function inCell($token) {
- /* An end tag whose tag name is one of: "td", "th" */
- if($token['type'] === HTML5::ENDTAG &&
- ($token['name'] === 'td' || $token['name'] === 'th')) {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as that of the token, then this is a
- parse error and the token must be ignored. */
- if(!$this->elementInScope($token['name'], true)) {
- // Ignore.
-
- /* Otherwise: */
- } else {
- /* Generate implied end tags, except for elements with the same
- tag name as the token. */
- $this->generateImpliedEndTags(array($token['name']));
-
- /* Now, if the current node is not an element with the same tag
- name as the token, then this is a parse error. */
- // k
-
- /* Pop elements from this stack until an element with the same
- tag name as the token has been popped from the stack. */
- while(true) {
- $node = end($this->stack)->nodeName;
- array_pop($this->stack);
-
- if($node === $token['name']) {
- break;
- }
- }
-
- /* Clear the list of active formatting elements up to the last
- marker. */
- $this->clearTheActiveFormattingElementsUpToTheLastMarker();
-
- /* Switch the insertion mode to "in row". (The current node
- will be a tr element at this point.) */
- $this->mode = self::IN_ROW;
- }
-
- /* A start tag whose tag name is one of: "caption", "col", "colgroup",
- "tbody", "td", "tfoot", "th", "thead", "tr" */
- } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
- 'thead', 'tr'))) {
- /* If the stack of open elements does not have a td or th element
- in table scope, then this is a parse error; ignore the token.
- (innerHTML case) */
- if(!$this->elementInScope(array('td', 'th'), true)) {
- // Ignore.
-
- /* Otherwise, close the cell (see below) and reprocess the current
- token. */
- } else {
- $this->closeCell();
- return $this->inRow($token);
- }
-
- /* A start tag whose tag name is one of: "caption", "col", "colgroup",
- "tbody", "td", "tfoot", "th", "thead", "tr" */
- } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
- array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
- 'thead', 'tr'))) {
- /* If the stack of open elements does not have a td or th element
- in table scope, then this is a parse error; ignore the token.
- (innerHTML case) */
- if(!$this->elementInScope(array('td', 'th'), true)) {
- // Ignore.
-
- /* Otherwise, close the cell (see below) and reprocess the current
- token. */
- } else {
- $this->closeCell();
- return $this->inRow($token);
- }
-
- /* An end tag whose tag name is one of: "body", "caption", "col",
- "colgroup", "html" */
- } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
- array('body', 'caption', 'col', 'colgroup', 'html'))) {
- /* Parse error. Ignore the token. */
-
- /* An end tag whose tag name is one of: "table", "tbody", "tfoot",
- "thead", "tr" */
- } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
- array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as that of the token (which can only
- happen for "tbody", "tfoot" and "thead", or, in the innerHTML case),
- then this is a parse error and the token must be ignored. */
- if(!$this->elementInScope($token['name'], true)) {
- // Ignore.
-
- /* Otherwise, close the cell (see below) and reprocess the current
- token. */
- } else {
- $this->closeCell();
- return $this->inRow($token);
- }
-
- /* Anything else */
- } else {
- /* Process the token as if the insertion mode was "in body". */
- $this->inBody($token);
- }
- }
-
- private function inSelect($token) {
- /* Handle the token as follows: */
-
- /* A character token */
- if($token['type'] === HTML5::CHARACTR) {
- /* Append the token's character to the current node. */
- $this->insertText($token['data']);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data
- attribute set to the data given in the comment token. */
- $this->insertComment($token['data']);
-
- /* A start tag token whose tag name is "option" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- $token['name'] === 'option') {
- /* If the current node is an option element, act as if an end tag
- with the tag name "option" had been seen. */
- if(end($this->stack)->nodeName === 'option') {
- $this->inSelect(array(
- 'name' => 'option',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* A start tag token whose tag name is "optgroup" */
- } elseif($token['type'] === HTML5::STARTTAG &&
- $token['name'] === 'optgroup') {
- /* If the current node is an option element, act as if an end tag
- with the tag name "option" had been seen. */
- if(end($this->stack)->nodeName === 'option') {
- $this->inSelect(array(
- 'name' => 'option',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* If the current node is an optgroup element, act as if an end tag
- with the tag name "optgroup" had been seen. */
- if(end($this->stack)->nodeName === 'optgroup') {
- $this->inSelect(array(
- 'name' => 'optgroup',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* An end tag token whose tag name is "optgroup" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- $token['name'] === 'optgroup') {
- /* First, if the current node is an option element, and the node
- immediately before it in the stack of open elements is an optgroup
- element, then act as if an end tag with the tag name "option" had
- been seen. */
- $elements_in_stack = count($this->stack);
-
- if($this->stack[$elements_in_stack - 1]->nodeName === 'option' &&
- $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup') {
- $this->inSelect(array(
- 'name' => 'option',
- 'type' => HTML5::ENDTAG
- ));
- }
-
- /* If the current node is an optgroup element, then pop that node
- from the stack of open elements. Otherwise, this is a parse error,
- ignore the token. */
- if($this->stack[$elements_in_stack - 1] === 'optgroup') {
- array_pop($this->stack);
- }
-
- /* An end tag token whose tag name is "option" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- $token['name'] === 'option') {
- /* If the current node is an option element, then pop that node
- from the stack of open elements. Otherwise, this is a parse error,
- ignore the token. */
- if(end($this->stack)->nodeName === 'option') {
- array_pop($this->stack);
- }
-
- /* An end tag whose tag name is "select" */
- } elseif($token['type'] === HTML5::ENDTAG &&
- $token['name'] === 'select') {
- /* If the stack of open elements does not have an element in table
- scope with the same tag name as the token, this is a parse error.
- Ignore the token. (innerHTML case) */
- if(!$this->elementInScope($token['name'], true)) {
- // w/e
-
- /* Otherwise: */
- } else {
- /* Pop elements from the stack of open elements until a select
- element has been popped from the stack. */
- while(true) {
- $current = end($this->stack)->nodeName;
- array_pop($this->stack);
-
- if($current === 'select') {
- break;
- }
- }
-
- /* Reset the insertion mode appropriately. */
- $this->resetInsertionMode();
- }
-
- /* A start tag whose tag name is "select" */
- } elseif($token['name'] === 'select' &&
- $token['type'] === HTML5::STARTTAG) {
- /* Parse error. Act as if the token had been an end tag with the
- tag name "select" instead. */
- $this->inSelect(array(
- 'name' => 'select',
- 'type' => HTML5::ENDTAG
- ));
-
- /* An end tag whose tag name is one of: "caption", "table", "tbody",
- "tfoot", "thead", "tr", "td", "th" */
- } elseif(in_array($token['name'], array('caption', 'table', 'tbody',
- 'tfoot', 'thead', 'tr', 'td', 'th')) && $token['type'] === HTML5::ENDTAG) {
- /* Parse error. */
- // w/e
-
- /* If the stack of open elements has an element in table scope with
- the same tag name as that of the token, then act as if an end tag
- with the tag name "select" had been seen, and reprocess the token.
- Otherwise, ignore the token. */
- if($this->elementInScope($token['name'], true)) {
- $this->inSelect(array(
- 'name' => 'select',
- 'type' => HTML5::ENDTAG
- ));
-
- $this->mainPhase($token);
- }
-
- /* Anything else */
- } else {
- /* Parse error. Ignore the token. */
- }
- }
-
- private function afterBody($token) {
- /* Handle the token as follows: */
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Process the token as it would be processed if the insertion mode
- was "in body". */
- $this->inBody($token);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the first element in the stack of open
- elements (the html element), with the data attribute set to the
- data given in the comment token. */
- $comment = $this->dom->createComment($token['data']);
- $this->stack[0]->appendChild($comment);
-
- /* An end tag with the tag name "html" */
- } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {
- /* If the parser was originally created in order to handle the
- setting of an element's innerHTML attribute, this is a parse error;
- ignore the token. (The element will be an html element in this
- case.) (innerHTML case) */
-
- /* Otherwise, switch to the trailing end phase. */
- $this->phase = self::END_PHASE;
-
- /* Anything else */
- } else {
- /* Parse error. Set the insertion mode to "in body" and reprocess
- the token. */
- $this->mode = self::IN_BODY;
- return $this->inBody($token);
- }
- }
-
- private function inFrameset($token) {
- /* Handle the token as follows: */
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append the character to the current node. */
- $this->insertText($token['data']);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data
- attribute set to the data given in the comment token. */
- $this->insertComment($token['data']);
-
- /* A start tag with the tag name "frameset" */
- } elseif($token['name'] === 'frameset' &&
- $token['type'] === HTML5::STARTTAG) {
- $this->insertElement($token);
-
- /* An end tag with the tag name "frameset" */
- } elseif($token['name'] === 'frameset' &&
- $token['type'] === HTML5::ENDTAG) {
- /* If the current node is the root html element, then this is a
- parse error; ignore the token. (innerHTML case) */
- if(end($this->stack)->nodeName === 'html') {
- // Ignore
-
- } else {
- /* Otherwise, pop the current node from the stack of open
- elements. */
- array_pop($this->stack);
-
- /* If the parser was not originally created in order to handle
- the setting of an element's innerHTML attribute (innerHTML case),
- and the current node is no longer a frameset element, then change
- the insertion mode to "after frameset". */
- $this->mode = self::AFTR_FRAME;
- }
-
- /* A start tag with the tag name "frame" */
- } elseif($token['name'] === 'frame' &&
- $token['type'] === HTML5::STARTTAG) {
- /* Insert an HTML element for the token. */
- $this->insertElement($token);
-
- /* Immediately pop the current node off the stack of open elements. */
- array_pop($this->stack);
-
- /* A start tag with the tag name "noframes" */
- } elseif($token['name'] === 'noframes' &&
- $token['type'] === HTML5::STARTTAG) {
- /* Process the token as if the insertion mode had been "in body". */
- $this->inBody($token);
-
- /* Anything else */
- } else {
- /* Parse error. Ignore the token. */
- }
- }
-
- private function afterFrameset($token) {
- /* Handle the token as follows: */
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
- if($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Append the character to the current node. */
- $this->insertText($token['data']);
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the current node with the data
- attribute set to the data given in the comment token. */
- $this->insertComment($token['data']);
-
- /* An end tag with the tag name "html" */
- } elseif($token['name'] === 'html' &&
- $token['type'] === HTML5::ENDTAG) {
- /* Switch to the trailing end phase. */
- $this->phase = self::END_PHASE;
-
- /* A start tag with the tag name "noframes" */
- } elseif($token['name'] === 'noframes' &&
- $token['type'] === HTML5::STARTTAG) {
- /* Process the token as if the insertion mode had been "in body". */
- $this->inBody($token);
-
- /* Anything else */
- } else {
- /* Parse error. Ignore the token. */
- }
- }
-
- private function trailingEndPhase($token) {
- /* After the main phase, as each token is emitted from the tokenisation
- stage, it must be processed as described in this section. */
-
- /* A DOCTYPE token */
- if($token['type'] === HTML5::DOCTYPE) {
- // Parse error. Ignore the token.
-
- /* A comment token */
- } elseif($token['type'] === HTML5::COMMENT) {
- /* Append a Comment node to the Document object with the data
- attribute set to the data given in the comment token. */
- $comment = $this->dom->createComment($token['data']);
- $this->dom->appendChild($comment);
-
- /* A character token that is one of one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE */
- } elseif($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
- /* Process the token as it would be processed in the main phase. */
- $this->mainPhase($token);
-
- /* A character token that is not one of U+0009 CHARACTER TABULATION,
- U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
- or U+0020 SPACE. Or a start tag token. Or an end tag token. */
- } elseif(($token['type'] === HTML5::CHARACTR &&
- preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
- $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG) {
- /* Parse error. Switch back to the main phase and reprocess the
- token. */
- $this->phase = self::MAIN_PHASE;
- return $this->mainPhase($token);
-
- /* An end-of-file token */
- } elseif($token['type'] === HTML5::EOF) {
- /* OMG DONE!! */
- }
- }
-
- private function insertElement($token, $append = true, $check = false) {
- // Proprietary workaround for libxml2's limitations with tag names
- if ($check) {
- // Slightly modified HTML5 tag-name modification,
- // removing anything that's not an ASCII letter, digit, or hyphen
- $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']);
- // Remove leading hyphens and numbers
- $token['name'] = ltrim($token['name'], '-0..9');
- // In theory, this should ever be needed, but just in case
- if ($token['name'] === '') $token['name'] = 'span'; // arbitrary generic choice
- }
-
- $el = $this->dom->createElement($token['name']);
-
- foreach($token['attr'] as $attr) {
- if(!$el->hasAttribute($attr['name'])) {
- $el->setAttribute($attr['name'], $attr['value']);
- }
- }
-
- $this->appendToRealParent($el);
- $this->stack[] = $el;
-
- return $el;
- }
-
- private function insertText($data) {
- $text = $this->dom->createTextNode($data);
- $this->appendToRealParent($text);
- }
-
- private function insertComment($data) {
- $comment = $this->dom->createComment($data);
- $this->appendToRealParent($comment);
- }
-
- private function appendToRealParent($node) {
- if($this->foster_parent === null) {
- end($this->stack)->appendChild($node);
-
- } elseif($this->foster_parent !== null) {
- /* If the foster parent element is the parent element of the
- last table element in the stack of open elements, then the new
- node must be inserted immediately before the last table element
- in the stack of open elements in the foster parent element;
- otherwise, the new node must be appended to the foster parent
- element. */
- for($n = count($this->stack) - 1; $n >= 0; $n--) {
- if($this->stack[$n]->nodeName === 'table' &&
- $this->stack[$n]->parentNode !== null) {
- $table = $this->stack[$n];
- break;
- }
- }
-
- if(isset($table) && $this->foster_parent->isSameNode($table->parentNode))
- $this->foster_parent->insertBefore($node, $table);
- else
- $this->foster_parent->appendChild($node);
-
- $this->foster_parent = null;
- }
- }
-
- private function elementInScope($el, $table = false) {
- if(is_array($el)) {
- foreach($el as $element) {
- if($this->elementInScope($element, $table)) {
- return true;
- }
- }
-
- return false;
- }
-
- $leng = count($this->stack);
-
- for($n = 0; $n < $leng; $n++) {
- /* 1. Initialise node to be the current node (the bottommost node of
- the stack). */
- $node = $this->stack[$leng - 1 - $n];
-
- if($node->tagName === $el) {
- /* 2. If node is the target node, terminate in a match state. */
- return true;
-
- } elseif($node->tagName === 'table') {
- /* 3. Otherwise, if node is a table element, terminate in a failure
- state. */
- return false;
-
- } elseif($table === true && in_array($node->tagName, array('caption', 'td',
- 'th', 'button', 'marquee', 'object'))) {
- /* 4. Otherwise, if the algorithm is the "has an element in scope"
- variant (rather than the "has an element in table scope" variant),
- and node is one of the following, terminate in a failure state. */
- return false;
-
- } elseif($node === $node->ownerDocument->documentElement) {
- /* 5. Otherwise, if node is an html element (root element), terminate
- in a failure state. (This can only happen if the node is the topmost
- node of the stack of open elements, and prevents the next step from
- being invoked if there are no more elements in the stack.) */
- return false;
- }
-
- /* Otherwise, set node to the previous entry in the stack of open
- elements and return to step 2. (This will never fail, since the loop
- will always terminate in the previous step if the top of the stack
- is reached.) */
- }
- }
-
- private function reconstructActiveFormattingElements() {
- /* 1. If there are no entries in the list of active formatting elements,
- then there is nothing to reconstruct; stop this algorithm. */
- $formatting_elements = count($this->a_formatting);
-
- if($formatting_elements === 0) {
- return false;
- }
-
- /* 3. Let entry be the last (most recently added) element in the list
- of active formatting elements. */
- $entry = end($this->a_formatting);
-
- /* 2. If the last (most recently added) entry in the list of active
- formatting elements is a marker, or if it is an element that is in the
- stack of open elements, then there is nothing to reconstruct; stop this
- algorithm. */
- if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
- return false;
- }
-
- for($a = $formatting_elements - 1; $a >= 0; true) {
- /* 4. If there are no entries before entry in the list of active
- formatting elements, then jump to step 8. */
- if($a === 0) {
- $step_seven = false;
- break;
- }
-
- /* 5. Let entry be the entry one earlier than entry in the list of
- active formatting elements. */
- $a--;
- $entry = $this->a_formatting[$a];
-
- /* 6. If entry is neither a marker nor an element that is also in
- thetack of open elements, go to step 4. */
- if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
- break;
- }
- }
-
- while(true) {
- /* 7. Let entry be the element one later than entry in the list of
- active formatting elements. */
- if(isset($step_seven) && $step_seven === true) {
- $a++;
- $entry = $this->a_formatting[$a];
- }
-
- /* 8. Perform a shallow clone of the element entry to obtain clone. */
- $clone = $entry->cloneNode();
-
- /* 9. Append clone to the current node and push it onto the stack
- of open elements so that it is the new current node. */
- end($this->stack)->appendChild($clone);
- $this->stack[] = $clone;
-
- /* 10. Replace the entry for entry in the list with an entry for
- clone. */
- $this->a_formatting[$a] = $clone;
-
- /* 11. If the entry for clone in the list of active formatting
- elements is not the last entry in the list, return to step 7. */
- if(end($this->a_formatting) !== $clone) {
- $step_seven = true;
- } else {
- break;
- }
- }
- }
-
- private function clearTheActiveFormattingElementsUpToTheLastMarker() {
- /* When the steps below require the UA to clear the list of active
- formatting elements up to the last marker, the UA must perform the
- following steps: */
-
- while(true) {
- /* 1. Let entry be the last (most recently added) entry in the list
- of active formatting elements. */
- $entry = end($this->a_formatting);
-
- /* 2. Remove entry from the list of active formatting elements. */
- array_pop($this->a_formatting);
-
- /* 3. If entry was a marker, then stop the algorithm at this point.
- The list has been cleared up to the last marker. */
- if($entry === self::MARKER) {
- break;
- }
- }
- }
-
- private function generateImpliedEndTags($exclude = array()) {
- /* When the steps below require the UA to generate implied end tags,
- then, if the current node is a dd element, a dt element, an li element,
- a p element, a td element, a th element, or a tr element, the UA must
- act as if an end tag with the respective tag name had been seen and
- then generate implied end tags again. */
- $node = end($this->stack);
- $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude);
-
- while(in_array(end($this->stack)->nodeName, $elements)) {
- array_pop($this->stack);
- }
- }
-
- private function getElementCategory($node) {
- $name = $node->tagName;
- if(in_array($name, $this->special))
- return self::SPECIAL;
-
- elseif(in_array($name, $this->scoping))
- return self::SCOPING;
-
- elseif(in_array($name, $this->formatting))
- return self::FORMATTING;
-
- else
- return self::PHRASING;
- }
-
- private function clearStackToTableContext($elements) {
- /* When the steps above require the UA to clear the stack back to a
- table context, it means that the UA must, while the current node is not
- a table element or an html element, pop elements from the stack of open
- elements. If this causes any elements to be popped from the stack, then
- this is a parse error. */
- while(true) {
- $node = end($this->stack)->nodeName;
-
- if(in_array($node, $elements)) {
- break;
- } else {
- array_pop($this->stack);
- }
- }
- }
-
- private function resetInsertionMode() {
- /* 1. Let last be false. */
- $last = false;
- $leng = count($this->stack);
-
- for($n = $leng - 1; $n >= 0; $n--) {
- /* 2. Let node be the last node in the stack of open elements. */
- $node = $this->stack[$n];
-
- /* 3. If node is the first node in the stack of open elements, then
- set last to true. If the element whose innerHTML attribute is being
- set is neither a td element nor a th element, then set node to the
- element whose innerHTML attribute is being set. (innerHTML case) */
- if($this->stack[0]->isSameNode($node)) {
- $last = true;
- }
-
- /* 4. If node is a select element, then switch the insertion mode to
- "in select" and abort these steps. (innerHTML case) */
- if($node->nodeName === 'select') {
- $this->mode = self::IN_SELECT;
- break;
-
- /* 5. If node is a td or th element, then switch the insertion mode
- to "in cell" and abort these steps. */
- } elseif($node->nodeName === 'td' || $node->nodeName === 'th') {
- $this->mode = self::IN_CELL;
- break;
-
- /* 6. If node is a tr element, then switch the insertion mode to
- "in row" and abort these steps. */
- } elseif($node->nodeName === 'tr') {
- $this->mode = self::IN_ROW;
- break;
-
- /* 7. If node is a tbody, thead, or tfoot element, then switch the
- insertion mode to "in table body" and abort these steps. */
- } elseif(in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) {
- $this->mode = self::IN_TBODY;
- break;
-
- /* 8. If node is a caption element, then switch the insertion mode
- to "in caption" and abort these steps. */
- } elseif($node->nodeName === 'caption') {
- $this->mode = self::IN_CAPTION;
- break;
-
- /* 9. If node is a colgroup element, then switch the insertion mode
- to "in column group" and abort these steps. (innerHTML case) */
- } elseif($node->nodeName === 'colgroup') {
- $this->mode = self::IN_CGROUP;
- break;
-
- /* 10. If node is a table element, then switch the insertion mode
- to "in table" and abort these steps. */
- } elseif($node->nodeName === 'table') {
- $this->mode = self::IN_TABLE;
- break;
-
- /* 11. If node is a head element, then switch the insertion mode
- to "in body" ("in body"! not "in head"!) and abort these steps.
- (innerHTML case) */
- } elseif($node->nodeName === 'head') {
- $this->mode = self::IN_BODY;
- break;
-
- /* 12. If node is a body element, then switch the insertion mode to
- "in body" and abort these steps. */
- } elseif($node->nodeName === 'body') {
- $this->mode = self::IN_BODY;
- break;
-
- /* 13. If node is a frameset element, then switch the insertion
- mode to "in frameset" and abort these steps. (innerHTML case) */
- } elseif($node->nodeName === 'frameset') {
- $this->mode = self::IN_FRAME;
- break;
-
- /* 14. If node is an html element, then: if the head element
- pointer is null, switch the insertion mode to "before head",
- otherwise, switch the insertion mode to "after head". In either
- case, abort these steps. (innerHTML case) */
- } elseif($node->nodeName === 'html') {
- $this->mode = ($this->head_pointer === null)
- ? self::BEFOR_HEAD
- : self::AFTER_HEAD;
-
- break;
-
- /* 15. If last is true, then set the insertion mode to "in body"
- and abort these steps. (innerHTML case) */
- } elseif($last) {
- $this->mode = self::IN_BODY;
- break;
- }
- }
- }
-
- private function closeCell() {
- /* If the stack of open elements has a td or th element in table scope,
- then act as if an end tag token with that tag name had been seen. */
- foreach(array('td', 'th') as $cell) {
- if($this->elementInScope($cell, true)) {
- $this->inCell(array(
- 'name' => $cell,
- 'type' => HTML5::ENDTAG
- ));
-
- break;
- }
- }
- }
-
- public function save() {
- return $this->dom;
- }
-}
-?>
diff --git a/library/HTMLPurifier/Strategy/FixNesting.php b/library/HTMLPurifier/Strategy/FixNesting.php
deleted file mode 100644
index f81802391..000000000
--- a/library/HTMLPurifier/Strategy/FixNesting.php
+++ /dev/null
@@ -1,328 +0,0 @@
-getHTMLDefinition();
-
- // insert implicit "parent" node, will be removed at end.
- // DEFINITION CALL
- $parent_name = $definition->info_parent;
- array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));
- $tokens[] = new HTMLPurifier_Token_End($parent_name);
-
- // setup the context variable 'IsInline', for chameleon processing
- // is 'false' when we are not inline, 'true' when it must always
- // be inline, and an integer when it is inline for a certain
- // branch of the document tree
- $is_inline = $definition->info_parent_def->descendants_are_inline;
- $context->register('IsInline', $is_inline);
-
- // setup error collector
- $e =& $context->get('ErrorCollector', true);
-
- //####################################################################//
- // Loop initialization
-
- // stack that contains the indexes of all parents,
- // $stack[count($stack)-1] being the current parent
- $stack = array();
-
- // stack that contains all elements that are excluded
- // it is organized by parent elements, similar to $stack,
- // but it is only populated when an element with exclusions is
- // processed, i.e. there won't be empty exclusions.
- $exclude_stack = array();
-
- // variable that contains the start token while we are processing
- // nodes. This enables error reporting to do its job
- $start_token = false;
- $context->register('CurrentToken', $start_token);
-
- //####################################################################//
- // Loop
-
- // iterate through all start nodes. Determining the start node
- // is complicated so it has been omitted from the loop construct
- for ($i = 0, $size = count($tokens) ; $i < $size; ) {
-
- //################################################################//
- // Gather information on children
-
- // child token accumulator
- $child_tokens = array();
-
- // scroll to the end of this node, report number, and collect
- // all children
- for ($j = $i, $depth = 0; ; $j++) {
- if ($tokens[$j] instanceof HTMLPurifier_Token_Start) {
- $depth++;
- // skip token assignment on first iteration, this is the
- // token we currently are on
- if ($depth == 1) continue;
- } elseif ($tokens[$j] instanceof HTMLPurifier_Token_End) {
- $depth--;
- // skip token assignment on last iteration, this is the
- // end token of the token we're currently on
- if ($depth == 0) break;
- }
- $child_tokens[] = $tokens[$j];
- }
-
- // $i is index of start token
- // $j is index of end token
-
- $start_token = $tokens[$i]; // to make token available via CurrentToken
-
- //################################################################//
- // Gather information on parent
-
- // calculate parent information
- if ($count = count($stack)) {
- $parent_index = $stack[$count-1];
- $parent_name = $tokens[$parent_index]->name;
- if ($parent_index == 0) {
- $parent_def = $definition->info_parent_def;
- } else {
- $parent_def = $definition->info[$parent_name];
- }
- } else {
- // processing as if the parent were the "root" node
- // unknown info, it won't be used anyway, in the future,
- // we may want to enforce one element only (this is
- // necessary for HTML Purifier to clean entire documents
- $parent_index = $parent_name = $parent_def = null;
- }
-
- // calculate context
- if ($is_inline === false) {
- // check if conditions make it inline
- if (!empty($parent_def) && $parent_def->descendants_are_inline) {
- $is_inline = $count - 1;
- }
- } else {
- // check if we're out of inline
- if ($count === $is_inline) {
- $is_inline = false;
- }
- }
-
- //################################################################//
- // Determine whether element is explicitly excluded SGML-style
-
- // determine whether or not element is excluded by checking all
- // parent exclusions. The array should not be very large, two
- // elements at most.
- $excluded = false;
- if (!empty($exclude_stack)) {
- foreach ($exclude_stack as $lookup) {
- if (isset($lookup[$tokens[$i]->name])) {
- $excluded = true;
- // no need to continue processing
- break;
- }
- }
- }
-
- //################################################################//
- // Perform child validation
-
- if ($excluded) {
- // there is an exclusion, remove the entire node
- $result = false;
- $excludes = array(); // not used, but good to initialize anyway
- } else {
- // DEFINITION CALL
- if ($i === 0) {
- // special processing for the first node
- $def = $definition->info_parent_def;
- } else {
- $def = $definition->info[$tokens[$i]->name];
-
- }
-
- if (!empty($def->child)) {
- // have DTD child def validate children
- $result = $def->child->validateChildren(
- $child_tokens, $config, $context);
- } else {
- // weird, no child definition, get rid of everything
- $result = false;
- }
-
- // determine whether or not this element has any exclusions
- $excludes = $def->excludes;
- }
-
- // $result is now a bool or array
-
- //################################################################//
- // Process result by interpreting $result
-
- if ($result === true || $child_tokens === $result) {
- // leave the node as is
-
- // register start token as a parental node start
- $stack[] = $i;
-
- // register exclusions if there are any
- if (!empty($excludes)) $exclude_stack[] = $excludes;
-
- // move cursor to next possible start node
- $i++;
-
- } elseif($result === false) {
- // remove entire node
-
- if ($e) {
- if ($excluded) {
- $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
- } else {
- $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
- }
- }
-
- // calculate length of inner tokens and current tokens
- $length = $j - $i + 1;
-
- // perform removal
- array_splice($tokens, $i, $length);
-
- // update size
- $size -= $length;
-
- // there is no start token to register,
- // current node is now the next possible start node
- // unless it turns out that we need to do a double-check
-
- // this is a rought heuristic that covers 100% of HTML's
- // cases and 99% of all other cases. A child definition
- // that would be tricked by this would be something like:
- // ( | a b c) where it's all or nothing. Fortunately,
- // our current implementation claims that that case would
- // not allow empty, even if it did
- if (!$parent_def->child->allow_empty) {
- // we need to do a double-check
- $i = $parent_index;
- array_pop($stack);
- }
-
- // PROJECTED OPTIMIZATION: Process all children elements before
- // reprocessing parent node.
-
- } else {
- // replace node with $result
-
- // calculate length of inner tokens
- $length = $j - $i - 1;
-
- if ($e) {
- if (empty($result) && $length) {
- $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
- } else {
- $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
- }
- }
-
- // perform replacement
- array_splice($tokens, $i + 1, $length, $result);
-
- // update size
- $size -= $length;
- $size += count($result);
-
- // register start token as a parental node start
- $stack[] = $i;
-
- // register exclusions if there are any
- if (!empty($excludes)) $exclude_stack[] = $excludes;
-
- // move cursor to next possible start node
- $i++;
-
- }
-
- //################################################################//
- // Scroll to next start node
-
- // We assume, at this point, that $i is the index of the token
- // that is the first possible new start point for a node.
-
- // Test if the token indeed is a start tag, if not, move forward
- // and test again.
- $size = count($tokens);
- while ($i < $size and !$tokens[$i] instanceof HTMLPurifier_Token_Start) {
- if ($tokens[$i] instanceof HTMLPurifier_Token_End) {
- // pop a token index off the stack if we ended a node
- array_pop($stack);
- // pop an exclusion lookup off exclusion stack if
- // we ended node and that node had exclusions
- if ($i == 0 || $i == $size - 1) {
- // use specialized var if it's the super-parent
- $s_excludes = $definition->info_parent_def->excludes;
- } else {
- $s_excludes = $definition->info[$tokens[$i]->name]->excludes;
- }
- if ($s_excludes) {
- array_pop($exclude_stack);
- }
- }
- $i++;
- }
-
- }
-
- //####################################################################//
- // Post-processing
-
- // remove implicit parent tokens at the beginning and end
- array_shift($tokens);
- array_pop($tokens);
-
- // remove context variables
- $context->destroy('IsInline');
- $context->destroy('CurrentToken');
-
- //####################################################################//
- // Return
-
- return $tokens;
-
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/Token.php b/library/HTMLPurifier/Token.php
deleted file mode 100644
index 7900e6cb1..000000000
--- a/library/HTMLPurifier/Token.php
+++ /dev/null
@@ -1,57 +0,0 @@
-line = $l;
- $this->col = $c;
- }
-
- /**
- * Convenience function for DirectLex settings line/col position.
- */
- public function rawPosition($l, $c) {
- if ($c === -1) $l++;
- $this->line = $l;
- $this->col = $c;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/Token/Comment.php b/library/HTMLPurifier/Token/Comment.php
deleted file mode 100644
index dc6bdcabb..000000000
--- a/library/HTMLPurifier/Token/Comment.php
+++ /dev/null
@@ -1,22 +0,0 @@
-data = $data;
- $this->line = $line;
- $this->col = $col;
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/TokenFactory.php b/library/HTMLPurifier/TokenFactory.php
deleted file mode 100644
index 7cf48fb41..000000000
--- a/library/HTMLPurifier/TokenFactory.php
+++ /dev/null
@@ -1,94 +0,0 @@
-p_start = new HTMLPurifier_Token_Start('', array());
- $this->p_end = new HTMLPurifier_Token_End('');
- $this->p_empty = new HTMLPurifier_Token_Empty('', array());
- $this->p_text = new HTMLPurifier_Token_Text('');
- $this->p_comment= new HTMLPurifier_Token_Comment('');
- }
-
- /**
- * Creates a HTMLPurifier_Token_Start.
- * @param $name Tag name
- * @param $attr Associative array of attributes
- * @return Generated HTMLPurifier_Token_Start
- */
- public function createStart($name, $attr = array()) {
- $p = clone $this->p_start;
- $p->__construct($name, $attr);
- return $p;
- }
-
- /**
- * Creates a HTMLPurifier_Token_End.
- * @param $name Tag name
- * @return Generated HTMLPurifier_Token_End
- */
- public function createEnd($name) {
- $p = clone $this->p_end;
- $p->__construct($name);
- return $p;
- }
-
- /**
- * Creates a HTMLPurifier_Token_Empty.
- * @param $name Tag name
- * @param $attr Associative array of attributes
- * @return Generated HTMLPurifier_Token_Empty
- */
- public function createEmpty($name, $attr = array()) {
- $p = clone $this->p_empty;
- $p->__construct($name, $attr);
- return $p;
- }
-
- /**
- * Creates a HTMLPurifier_Token_Text.
- * @param $data Data of text token
- * @return Generated HTMLPurifier_Token_Text
- */
- public function createText($data) {
- $p = clone $this->p_text;
- $p->__construct($data);
- return $p;
- }
-
- /**
- * Creates a HTMLPurifier_Token_Comment.
- * @param $data Data of comment token
- * @return Generated HTMLPurifier_Token_Comment
- */
- public function createComment($data) {
- $p = clone $this->p_comment;
- $p->__construct($data);
- return $p;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URI.php b/library/HTMLPurifier/URI.php
deleted file mode 100644
index 8b50d0d18..000000000
--- a/library/HTMLPurifier/URI.php
+++ /dev/null
@@ -1,173 +0,0 @@
-scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme);
- $this->userinfo = $userinfo;
- $this->host = $host;
- $this->port = is_null($port) ? $port : (int) $port;
- $this->path = $path;
- $this->query = $query;
- $this->fragment = $fragment;
- }
-
- /**
- * Retrieves a scheme object corresponding to the URI's scheme/default
- * @param $config Instance of HTMLPurifier_Config
- * @param $context Instance of HTMLPurifier_Context
- * @return Scheme object appropriate for validating this URI
- */
- public function getSchemeObj($config, $context) {
- $registry = HTMLPurifier_URISchemeRegistry::instance();
- if ($this->scheme !== null) {
- $scheme_obj = $registry->getScheme($this->scheme, $config, $context);
- if (!$scheme_obj) return false; // invalid scheme, clean it out
- } else {
- // no scheme: retrieve the default one
- $def = $config->getDefinition('URI');
- $scheme_obj = $registry->getScheme($def->defaultScheme, $config, $context);
- if (!$scheme_obj) {
- // something funky happened to the default scheme object
- trigger_error(
- 'Default scheme object "' . $def->defaultScheme . '" was not readable',
- E_USER_WARNING
- );
- return false;
- }
- }
- return $scheme_obj;
- }
-
- /**
- * Generic validation method applicable for all schemes. May modify
- * this URI in order to get it into a compliant form.
- * @param $config Instance of HTMLPurifier_Config
- * @param $context Instance of HTMLPurifier_Context
- * @return True if validation/filtering succeeds, false if failure
- */
- public function validate($config, $context) {
-
- // ABNF definitions from RFC 3986
- $chars_sub_delims = '!$&\'()*+,;=';
- $chars_gen_delims = ':/?#[]@';
- $chars_pchar = $chars_sub_delims . ':@';
-
- // validate scheme (MUST BE FIRST!)
- if (!is_null($this->scheme) && is_null($this->host)) {
- $def = $config->getDefinition('URI');
- if ($def->defaultScheme === $this->scheme) {
- $this->scheme = null;
- }
- }
-
- // validate host
- if (!is_null($this->host)) {
- $host_def = new HTMLPurifier_AttrDef_URI_Host();
- $this->host = $host_def->validate($this->host, $config, $context);
- if ($this->host === false) $this->host = null;
- }
-
- // validate username
- if (!is_null($this->userinfo)) {
- $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':');
- $this->userinfo = $encoder->encode($this->userinfo);
- }
-
- // validate port
- if (!is_null($this->port)) {
- if ($this->port < 1 || $this->port > 65535) $this->port = null;
- }
-
- // validate path
- $path_parts = array();
- $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/');
- if (!is_null($this->host)) {
- // path-abempty (hier and relative)
- $this->path = $segments_encoder->encode($this->path);
- } elseif ($this->path !== '' && $this->path[0] === '/') {
- // path-absolute (hier and relative)
- if (strlen($this->path) >= 2 && $this->path[1] === '/') {
- // This shouldn't ever happen!
- $this->path = '';
- } else {
- $this->path = $segments_encoder->encode($this->path);
- }
- } elseif (!is_null($this->scheme) && $this->path !== '') {
- // path-rootless (hier)
- // Short circuit evaluation means we don't need to check nz
- $this->path = $segments_encoder->encode($this->path);
- } elseif (is_null($this->scheme) && $this->path !== '') {
- // path-noscheme (relative)
- // (once again, not checking nz)
- $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');
- $c = strpos($this->path, '/');
- if ($c !== false) {
- $this->path =
- $segment_nc_encoder->encode(substr($this->path, 0, $c)) .
- $segments_encoder->encode(substr($this->path, $c));
- } else {
- $this->path = $segment_nc_encoder->encode($this->path);
- }
- } else {
- // path-empty (hier and relative)
- $this->path = ''; // just to be safe
- }
-
- // qf = query and fragment
- $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?');
-
- if (!is_null($this->query)) {
- $this->query = $qf_encoder->encode($this->query);
- }
-
- if (!is_null($this->fragment)) {
- $this->fragment = $qf_encoder->encode($this->fragment);
- }
-
- return true;
-
- }
-
- /**
- * Convert URI back to string
- * @return String URI appropriate for output
- */
- public function toString() {
- // reconstruct authority
- $authority = null;
- if (!is_null($this->host)) {
- $authority = '';
- if(!is_null($this->userinfo)) $authority .= $this->userinfo . '@';
- $authority .= $this->host;
- if(!is_null($this->port)) $authority .= ':' . $this->port;
- }
-
- // reconstruct the result
- $result = '';
- if (!is_null($this->scheme)) $result .= $this->scheme . ':';
- if (!is_null($authority)) $result .= '//' . $authority;
- $result .= $this->path;
- if (!is_null($this->query)) $result .= '?' . $this->query;
- if (!is_null($this->fragment)) $result .= '#' . $this->fragment;
-
- return $result;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIFilter.php b/library/HTMLPurifier/URIFilter.php
deleted file mode 100644
index c116f93df..000000000
--- a/library/HTMLPurifier/URIFilter.php
+++ /dev/null
@@ -1,45 +0,0 @@
-getDefinition('URI')->host;
- if ($our_host !== null) $this->ourHostParts = array_reverse(explode('.', $our_host));
- }
- public function filter(&$uri, $config, $context) {
- if (is_null($uri->host)) return true;
- if ($this->ourHostParts === false) return false;
- $host_parts = array_reverse(explode('.', $uri->host));
- foreach ($this->ourHostParts as $i => $x) {
- if (!isset($host_parts[$i])) return false;
- if ($host_parts[$i] != $this->ourHostParts[$i]) return false;
- }
- return true;
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIFilter/DisableExternalResources.php b/library/HTMLPurifier/URIFilter/DisableExternalResources.php
deleted file mode 100644
index 881abc43c..000000000
--- a/library/HTMLPurifier/URIFilter/DisableExternalResources.php
+++ /dev/null
@@ -1,12 +0,0 @@
-get('EmbeddedURI', true)) return true;
- return parent::filter($uri, $config, $context);
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIFilter/HostBlacklist.php b/library/HTMLPurifier/URIFilter/HostBlacklist.php
deleted file mode 100644
index 045aa0992..000000000
--- a/library/HTMLPurifier/URIFilter/HostBlacklist.php
+++ /dev/null
@@ -1,21 +0,0 @@
-blacklist = $config->get('URI.HostBlacklist');
- return true;
- }
- public function filter(&$uri, $config, $context) {
- foreach($this->blacklist as $blacklisted_host_fragment) {
- if (strpos($uri->host, $blacklisted_host_fragment) !== false) {
- return false;
- }
- }
- return true;
- }
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIFilter/Munge.php b/library/HTMLPurifier/URIFilter/Munge.php
deleted file mode 100644
index efa10a645..000000000
--- a/library/HTMLPurifier/URIFilter/Munge.php
+++ /dev/null
@@ -1,58 +0,0 @@
-target = $config->get('URI.' . $this->name);
- $this->parser = new HTMLPurifier_URIParser();
- $this->doEmbed = $config->get('URI.MungeResources');
- $this->secretKey = $config->get('URI.MungeSecretKey');
- return true;
- }
- public function filter(&$uri, $config, $context) {
- if ($context->get('EmbeddedURI', true) && !$this->doEmbed) return true;
-
- $scheme_obj = $uri->getSchemeObj($config, $context);
- if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it
- if (is_null($uri->host) || empty($scheme_obj->browsable)) {
- return true;
- }
- // don't redirect if target host is our host
- if ($uri->host === $config->getDefinition('URI')->host) {
- return true;
- }
-
- $this->makeReplace($uri, $config, $context);
- $this->replace = array_map('rawurlencode', $this->replace);
-
- $new_uri = strtr($this->target, $this->replace);
- $new_uri = $this->parser->parse($new_uri);
- // don't redirect if the target host is the same as the
- // starting host
- if ($uri->host === $new_uri->host) return true;
- $uri = $new_uri; // overwrite
- return true;
- }
-
- protected function makeReplace($uri, $config, $context) {
- $string = $uri->toString();
- // always available
- $this->replace['%s'] = $string;
- $this->replace['%r'] = $context->get('EmbeddedURI', true);
- $token = $context->get('CurrentToken', true);
- $this->replace['%n'] = $token ? $token->name : null;
- $this->replace['%m'] = $context->get('CurrentAttr', true);
- $this->replace['%p'] = $context->get('CurrentCSSProperty', true);
- // not always available
- if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIScheme.php b/library/HTMLPurifier/URIScheme.php
deleted file mode 100644
index 039710fd1..000000000
--- a/library/HTMLPurifier/URIScheme.php
+++ /dev/null
@@ -1,42 +0,0 @@
-, resolves edge cases
- * with making relative URIs absolute
- */
- public $hierarchical = false;
-
- /**
- * Validates the components of a URI
- * @note This implementation should be called by children if they define
- * a default port, as it does port processing.
- * @param $uri Instance of HTMLPurifier_URI
- * @param $config HTMLPurifier_Config object
- * @param $context HTMLPurifier_Context object
- * @return Bool success or failure
- */
- public function validate(&$uri, $config, $context) {
- if ($this->default_port == $uri->port) $uri->port = null;
- return true;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIScheme/news.php b/library/HTMLPurifier/URIScheme/news.php
deleted file mode 100644
index f5f54f4f5..000000000
--- a/library/HTMLPurifier/URIScheme/news.php
+++ /dev/null
@@ -1,22 +0,0 @@
-userinfo = null;
- $uri->host = null;
- $uri->port = null;
- $uri->query = null;
- // typecode check needed on path
- return true;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/URIScheme/nntp.php b/library/HTMLPurifier/URIScheme/nntp.php
deleted file mode 100644
index 5bf93ea78..000000000
--- a/library/HTMLPurifier/URIScheme/nntp.php
+++ /dev/null
@@ -1,20 +0,0 @@
-userinfo = null;
- $uri->query = null;
- return true;
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/HTMLPurifier/VarParser.php b/library/HTMLPurifier/VarParser.php
deleted file mode 100644
index 68e72ae86..000000000
--- a/library/HTMLPurifier/VarParser.php
+++ /dev/null
@@ -1,154 +0,0 @@
- self::STRING,
- 'istring' => self::ISTRING,
- 'text' => self::TEXT,
- 'itext' => self::ITEXT,
- 'int' => self::INT,
- 'float' => self::FLOAT,
- 'bool' => self::BOOL,
- 'lookup' => self::LOOKUP,
- 'list' => self::ALIST,
- 'hash' => self::HASH,
- 'mixed' => self::MIXED
- );
-
- /**
- * Lookup table of types that are string, and can have aliases or
- * allowed value lists.
- */
- static public $stringTypes = array(
- self::STRING => true,
- self::ISTRING => true,
- self::TEXT => true,
- self::ITEXT => true,
- );
-
- /**
- * Validate a variable according to type. Throws
- * HTMLPurifier_VarParserException if invalid.
- * It may return NULL as a valid type if $allow_null is true.
- *
- * @param $var Variable to validate
- * @param $type Type of variable, see HTMLPurifier_VarParser->types
- * @param $allow_null Whether or not to permit null as a value
- * @return Validated and type-coerced variable
- */
- final public function parse($var, $type, $allow_null = false) {
- if (is_string($type)) {
- if (!isset(HTMLPurifier_VarParser::$types[$type])) {
- throw new HTMLPurifier_VarParserException("Invalid type '$type'");
- } else {
- $type = HTMLPurifier_VarParser::$types[$type];
- }
- }
- $var = $this->parseImplementation($var, $type, $allow_null);
- if ($allow_null && $var === null) return null;
- // These are basic checks, to make sure nothing horribly wrong
- // happened in our implementations.
- switch ($type) {
- case (self::STRING):
- case (self::ISTRING):
- case (self::TEXT):
- case (self::ITEXT):
- if (!is_string($var)) break;
- if ($type == self::ISTRING || $type == self::ITEXT) $var = strtolower($var);
- return $var;
- case (self::INT):
- if (!is_int($var)) break;
- return $var;
- case (self::FLOAT):
- if (!is_float($var)) break;
- return $var;
- case (self::BOOL):
- if (!is_bool($var)) break;
- return $var;
- case (self::LOOKUP):
- case (self::ALIST):
- case (self::HASH):
- if (!is_array($var)) break;
- if ($type === self::LOOKUP) {
- foreach ($var as $k) if ($k !== true) $this->error('Lookup table contains value other than true');
- } elseif ($type === self::ALIST) {
- $keys = array_keys($var);
- if (array_keys($keys) !== $keys) $this->error('Indices for list are not uniform');
- }
- return $var;
- case (self::MIXED):
- return $var;
- default:
- $this->errorInconsistent(get_class($this), $type);
- }
- $this->errorGeneric($var, $type);
- }
-
- /**
- * Actually implements the parsing. Base implementation is to not
- * do anything to $var. Subclasses should overload this!
- */
- protected function parseImplementation($var, $type, $allow_null) {
- return $var;
- }
-
- /**
- * Throws an exception.
- */
- protected function error($msg) {
- throw new HTMLPurifier_VarParserException($msg);
- }
-
- /**
- * Throws an inconsistency exception.
- * @note This should not ever be called. It would be called if we
- * extend the allowed values of HTMLPurifier_VarParser without
- * updating subclasses.
- */
- protected function errorInconsistent($class, $type) {
- throw new HTMLPurifier_Exception("Inconsistency in $class: ".HTMLPurifier_VarParser::getTypeName($type)." not implemented");
- }
-
- /**
- * Generic error for if a type didn't work.
- */
- protected function errorGeneric($var, $type) {
- $vtype = gettype($var);
- $this->error("Expected type ".HTMLPurifier_VarParser::getTypeName($type).", got $vtype");
- }
-
- static public function getTypeName($type) {
- static $lookup;
- if (!$lookup) {
- // Lazy load the alternative lookup table
- $lookup = array_flip(HTMLPurifier_VarParser::$types);
- }
- if (!isset($lookup[$type])) return 'unknown';
- return $lookup[$type];
- }
-
-}
-
-// vim: et sw=4 sts=4
diff --git a/library/ezyang/htmlpurifier/CREDITS b/library/ezyang/htmlpurifier/CREDITS
new file mode 100644
index 000000000..7921b45af
--- /dev/null
+++ b/library/ezyang/htmlpurifier/CREDITS
@@ -0,0 +1,9 @@
+
+CREDITS
+
+Almost everything written by Edward Z. Yang (Ambush Commander). Lots of thanks
+to the DevNetwork Community for their help (see docs/ref-devnetwork.html for
+more details), Feyd especially (namely IPv6 and optimization). Thanks to RSnake
+for letting me package his fantastic XSS cheatsheet for a smoketest.
+
+ vim: et sw=4 sts=4
diff --git a/library/ezyang/htmlpurifier/INSTALL b/library/ezyang/htmlpurifier/INSTALL
new file mode 100644
index 000000000..677c04aa0
--- /dev/null
+++ b/library/ezyang/htmlpurifier/INSTALL
@@ -0,0 +1,374 @@
+
+Install
+ How to install HTML Purifier
+
+HTML Purifier is designed to run out of the box, so actually using the
+library is extremely easy. (Although... if you were looking for a
+step-by-step installation GUI, you've downloaded the wrong software!)
+
+While the impatient can get going immediately with some of the sample
+code at the bottom of this library, it's well worth reading this entire
+document--most of the other documentation assumes that you are familiar
+with these contents.
+
+
+---------------------------------------------------------------------------
+1. Compatibility
+
+HTML Purifier is PHP 5 only, and is actively tested from PHP 5.0.5 and
+up. It has no core dependencies with other libraries. PHP
+4 support was deprecated on December 31, 2007 with HTML Purifier 3.0.0.
+HTML Purifier is not compatible with zend.ze1_compatibility_mode.
+
+These optional extensions can enhance the capabilities of HTML Purifier:
+
+ * iconv : Converts text to and from non-UTF-8 encodings
+ * bcmath : Used for unit conversion and imagecrash protection
+ * tidy : Used for pretty-printing HTML
+
+These optional libraries can enhance the capabilities of HTML Purifier:
+
+ * CSSTidy : Clean CSS stylesheets using %Core.ExtractStyleBlocks
+ * Net_IDNA2 (PEAR) : IRI support using %Core.EnableIDNA
+
+---------------------------------------------------------------------------
+2. Reconnaissance
+
+A big plus of HTML Purifier is its inerrant support of standards, so
+your web-pages should be standards-compliant. (They should also use
+semantic markup, but that's another issue altogether, one HTML Purifier
+cannot fix without reading your mind.)
+
+HTML Purifier can process these doctypes:
+
+* XHTML 1.0 Transitional (default)
+* XHTML 1.0 Strict
+* HTML 4.01 Transitional
+* HTML 4.01 Strict
+* XHTML 1.1
+
+...and these character encodings:
+
+* UTF-8 (default)
+* Any encoding iconv supports (with crippled internationalization support)
+
+These defaults reflect what my choices would be if I were authoring an
+HTML document, however, what you choose depends on the nature of your
+codebase. If you don't know what doctype you are using, you can determine
+the doctype from this identifier at the top of your source code:
+
+
+
+...and the character encoding from this code:
+
+
+
+If the character encoding declaration is missing, STOP NOW, and
+read 'docs/enduser-utf8.html' (web accessible at
+http://htmlpurifier.org/docs/enduser-utf8.html). In fact, even if it is
+present, read this document anyway, as many websites specify their
+document's character encoding incorrectly.
+
+
+---------------------------------------------------------------------------
+3. Including the library
+
+The procedure is quite simple:
+
+ require_once '/path/to/library/HTMLPurifier.auto.php';
+
+This will setup an autoloader, so the library's files are only included
+when you use them.
+
+Only the contents in the library/ folder are necessary, so you can remove
+everything else when using HTML Purifier in a production environment.
+
+If you installed HTML Purifier via PEAR, all you need to do is:
+
+ require_once 'HTMLPurifier.auto.php';
+
+Please note that the usual PEAR practice of including just the classes you
+want will not work with HTML Purifier's autoloading scheme.
+
+Advanced users, read on; other users can skip to section 4.
+
+Autoload compatibility
+----------------------
+
+ HTML Purifier attempts to be as smart as possible when registering an
+ autoloader, but there are some cases where you will need to change
+ your own code to accomodate HTML Purifier. These are those cases:
+
+ PHP VERSION IS LESS THAN 5.1.2, AND YOU'VE DEFINED __autoload
+ Because spl_autoload_register() doesn't exist in early versions
+ of PHP 5, HTML Purifier has no way of adding itself to the autoload
+ stack. Modify your __autoload function to test
+ HTMLPurifier_Bootstrap::autoload($class)
+
+ For example, suppose your autoload function looks like this:
+
+ function __autoload($class) {
+ require str_replace('_', '/', $class) . '.php';
+ return true;
+ }
+
+ A modified version with HTML Purifier would look like this:
+
+ function __autoload($class) {
+ if (HTMLPurifier_Bootstrap::autoload($class)) return true;
+ require str_replace('_', '/', $class) . '.php';
+ return true;
+ }
+
+ Note that there *is* some custom behavior in our autoloader; the
+ original autoloader in our example would work for 99% of the time,
+ but would fail when including language files.
+
+ AN __autoload FUNCTION IS DECLARED AFTER OUR AUTOLOADER IS REGISTERED
+ spl_autoload_register() has the curious behavior of disabling
+ the existing __autoload() handler. Users need to explicitly
+ spl_autoload_register('__autoload'). Because we use SPL when it
+ is available, __autoload() will ALWAYS be disabled. If __autoload()
+ is declared before HTML Purifier is loaded, this is not a problem:
+ HTML Purifier will register the function for you. But if it is
+ declared afterwards, it will mysteriously not work. This
+ snippet of code (after your autoloader is defined) will fix it:
+
+ spl_autoload_register('__autoload')
+
+ Users should also be on guard if they use a version of PHP previous
+ to 5.1.2 without an autoloader--HTML Purifier will define __autoload()
+ for you, which can collide with an autoloader that was added by *you*
+ later.
+
+
+For better performance
+----------------------
+
+ Opcode caches, which greatly speed up PHP initialization for scripts
+ with large amounts of code (HTML Purifier included), don't like
+ autoloaders. We offer an include file that includes all of HTML Purifier's
+ files in one go in an opcode cache friendly manner:
+
+ // If /path/to/library isn't already in your include path, uncomment
+ // the below line:
+ // require '/path/to/library/HTMLPurifier.path.php';
+
+ require 'HTMLPurifier.includes.php';
+
+ Optional components still need to be included--you'll know if you try to
+ use a feature and you get a class doesn't exists error! The autoloader
+ can be used in conjunction with this approach to catch classes that are
+ missing. Simply add this afterwards:
+
+ require 'HTMLPurifier.autoload.php';
+
+Standalone version
+------------------
+
+ HTML Purifier has a standalone distribution; you can also generate
+ a standalone file from the full version by running the script
+ maintenance/generate-standalone.php . The standalone version has the
+ benefit of having most of its code in one file, so parsing is much
+ faster and the library is easier to manage.
+
+ If HTMLPurifier.standalone.php exists in the library directory, you
+ can use it like this:
+
+ require '/path/to/HTMLPurifier.standalone.php';
+
+ This is equivalent to including HTMLPurifier.includes.php, except that
+ the contents of standalone/ will be added to your path. To override this
+ behavior, specify a new HTMLPURIFIER_PREFIX where standalone files can
+ be found (usually, this will be one directory up, the "true" library
+ directory in full distributions). Don't forget to set your path too!
+
+ The autoloader can be added to the end to ensure the classes are
+ loaded when necessary; otherwise you can manually include them.
+ To use the autoloader, use this:
+
+ require 'HTMLPurifier.autoload.php';
+
+For advanced users
+------------------
+
+ HTMLPurifier.auto.php performs a number of operations that can be done
+ individually. These are:
+
+ HTMLPurifier.path.php
+ Puts /path/to/library in the include path. For high performance,
+ this should be done in php.ini.
+
+ HTMLPurifier.autoload.php
+ Registers our autoload handler HTMLPurifier_Bootstrap::autoload($class).
+
+ You can do these operations by yourself--in fact, you must modify your own
+ autoload handler if you are using a version of PHP earlier than PHP 5.1.2
+ (See "Autoload compatibility" above).
+
+
+---------------------------------------------------------------------------
+4. Configuration
+
+HTML Purifier is designed to run out-of-the-box, but occasionally HTML
+Purifier needs to be told what to do. If you answer no to any of these
+questions, read on; otherwise, you can skip to the next section (or, if you're
+into configuring things just for the heck of it, skip to 4.3).
+
+* Am I using UTF-8?
+* Am I using XHTML 1.0 Transitional?
+
+If you answered no to any of these questions, instantiate a configuration
+object and read on:
+
+ $config = HTMLPurifier_Config::createDefault();
+
+
+4.1. Setting a different character encoding
+
+You really shouldn't use any other encoding except UTF-8, especially if you
+plan to support multilingual websites (read section three for more details).
+However, switching to UTF-8 is not always immediately feasible, so we can
+adapt.
+
+HTML Purifier uses iconv to support other character encodings, as such,
+any encoding that iconv supports
+HTML Purifier supports with this code:
+
+ $config->set('Core.Encoding', /* put your encoding here */);
+
+An example usage for Latin-1 websites (the most common encoding for English
+websites):
+
+ $config->set('Core.Encoding', 'ISO-8859-1');
+
+Note that HTML Purifier's support for non-Unicode encodings is crippled by the
+fact that any character not supported by that encoding will be silently
+dropped, EVEN if it is ampersand escaped. If you want to work around
+this, you are welcome to read docs/enduser-utf8.html for a fix,
+but please be cognizant of the issues the "solution" creates (for this
+reason, I do not include the solution in this document).
+
+
+4.2. Setting a different doctype
+
+For those of you using HTML 4.01 Transitional, you can disable
+XHTML output like this:
+
+ $config->set('HTML.Doctype', 'HTML 4.01 Transitional');
+
+Other supported doctypes include:
+
+ * HTML 4.01 Strict
+ * HTML 4.01 Transitional
+ * XHTML 1.0 Strict
+ * XHTML 1.0 Transitional
+ * XHTML 1.1
+
+
+4.3. Other settings
+
+There are more configuration directives which can be read about
+here: They're a bit boring,
+but they can help out for those of you who like to exert maximum control over
+your code. Some of the more interesting ones are configurable at the
+demo and are well worth looking into
+for your own system.
+
+For example, you can fine tune allowed elements and attributes, convert
+relative URLs to absolute ones, and even autoparagraph input text! These
+are, respectively, %HTML.Allowed, %URI.MakeAbsolute and %URI.Base, and
+%AutoFormat.AutoParagraph. The %Namespace.Directive naming convention
+translates to:
+
+ $config->set('Namespace.Directive', $value);
+
+E.g.
+
+ $config->set('HTML.Allowed', 'p,b,a[href],i');
+ $config->set('URI.Base', 'http://www.example.com');
+ $config->set('URI.MakeAbsolute', true);
+ $config->set('AutoFormat.AutoParagraph', true);
+
+
+---------------------------------------------------------------------------
+5. Caching
+
+HTML Purifier generates some cache files (generally one or two) to speed up
+its execution. For maximum performance, make sure that
+library/HTMLPurifier/DefinitionCache/Serializer is writeable by the webserver.
+
+If you are in the library/ folder of HTML Purifier, you can set the
+appropriate permissions using:
+
+ chmod -R 0755 HTMLPurifier/DefinitionCache/Serializer
+
+If the above command doesn't work, you may need to assign write permissions
+to all. This may be necessary if your webserver runs as nobody, but is
+not recommended since it means any other user can write files in the
+directory. Use:
+
+ chmod -R 0777 HTMLPurifier/DefinitionCache/Serializer
+
+You can also chmod files via your FTP client; this option
+is usually accessible by right clicking the corresponding directory and
+then selecting "chmod" or "file permissions".
+
+Starting with 2.0.1, HTML Purifier will generate friendly error messages
+that will tell you exactly what you have to chmod the directory to, if in doubt,
+follow its advice.
+
+If you are unable or unwilling to give write permissions to the cache
+directory, you can either disable the cache (and suffer a performance
+hit):
+
+ $config->set('Core.DefinitionCache', null);
+
+Or move the cache directory somewhere else (no trailing slash):
+
+ $config->set('Cache.SerializerPath', '/home/user/absolute/path');
+
+
+---------------------------------------------------------------------------
+6. Using the code
+
+The interface is mind-numbingly simple:
+
+ $purifier = new HTMLPurifier($config);
+ $clean_html = $purifier->purify( $dirty_html );
+
+That's it! For more examples, check out docs/examples/ (they aren't very
+different though). Also, docs/enduser-slow.html gives advice on what to
+do if HTML Purifier is slowing down your application.
+
+
+---------------------------------------------------------------------------
+7. Quick install
+
+First, make sure library/HTMLPurifier/DefinitionCache/Serializer is
+writable by the webserver (see Section 5: Caching above for details).
+If your website is in UTF-8 and XHTML Transitional, use this code:
+
+purify($dirty_html);
+?>
+
+If your website is in a different encoding or doctype, use this code:
+
+set('Core.Encoding', 'ISO-8859-1'); // replace with your encoding
+ $config->set('HTML.Doctype', 'HTML 4.01 Transitional'); // replace with your doctype
+ $purifier = new HTMLPurifier($config);
+
+ $clean_html = $purifier->purify($dirty_html);
+?>
+
+ vim: et sw=4 sts=4
diff --git a/library/ezyang/htmlpurifier/INSTALL.fr.utf8 b/library/ezyang/htmlpurifier/INSTALL.fr.utf8
new file mode 100644
index 000000000..06e628cc9
--- /dev/null
+++ b/library/ezyang/htmlpurifier/INSTALL.fr.utf8
@@ -0,0 +1,60 @@
+
+Installation
+ Comment installer HTML Purifier
+
+Attention : Ce document est encodé en UTF-8, si les lettres avec des accents
+ne s'affichent pas, prenez un meilleur éditeur de texte.
+
+L'installation de HTML Purifier est très simple, parce qu'il n'a pas besoin
+de configuration. Pour les utilisateurs impatients, le code se trouve dans le
+pied de page, mais je recommande de lire le document.
+
+1. Compatibilité
+
+HTML Purifier fonctionne avec PHP 5. PHP 5.0.5 est la dernière version testée.
+Il ne dépend pas d'autres librairies.
+
+Les extensions optionnelles sont iconv (généralement déjà installée) et tidy
+(répendue aussi). Si vous utilisez UTF-8 et que vous ne voulez pas l'indentation,
+vous pouvez utiliser HTML Purifier sans ces extensions.
+
+
+2. Inclure la librairie
+
+Quand vous devez l'utilisez, incluez le :
+
+ require_once('/path/to/library/HTMLPurifier.auto.php');
+
+Ne pas l'inclure si ce n'est pas nécessaire, car HTML Purifier est lourd.
+
+HTML Purifier utilise "autoload". Si vous avez défini la fonction __autoload,
+vous devez ajouter cette fonction :
+
+ spl_autoload_register('__autoload')
+
+Plus d'informations dans le document "INSTALL".
+
+3. Installation rapide
+
+Si votre site Web est en UTF-8 et XHTML Transitional, utilisez :
+
+purify($html_a_purifier);
+?>
+
+Sinon, utilisez :
+
+set('Core', 'Encoding', 'ISO-8859-1'); //Remplacez par votre
+ encodage
+ $config->set('Core', 'XHTML', true); //Remplacer par false si HTML 4.01
+ $purificateur = new HTMLPurifier($config);
+ $html_propre = $purificateur->purify($html_a_purifier);
+?>
+
+
+ vim: et sw=4 sts=4
diff --git a/library/ezyang/htmlpurifier/LICENSE b/library/ezyang/htmlpurifier/LICENSE
new file mode 100644
index 000000000..8c88a20d4
--- /dev/null
+++ b/library/ezyang/htmlpurifier/LICENSE
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ , 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+ vim: et sw=4 sts=4
diff --git a/library/ezyang/htmlpurifier/NEWS b/library/ezyang/htmlpurifier/NEWS
new file mode 100644
index 000000000..a9124af1a
--- /dev/null
+++ b/library/ezyang/htmlpurifier/NEWS
@@ -0,0 +1,1094 @@
+NEWS ( CHANGELOG and HISTORY ) HTMLPurifier
+|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
+
+= KEY ====================
+ # Breaks back-compat
+ ! Feature
+ - Bugfix
+ + Sub-comment
+ . Internal change
+==========================
+
+4.7.0, released 2015-08-04
+# opacity is now considered a "tricky" CSS property rather than a
+ proprietary one.
+! %AutoFormat.RemoveEmpty.Predicate for specifying exactly when
+ an element should be considered "empty" (maybe preserve if it
+ has attributes), and modify iframe support so that the iframe
+ is removed if it is missing a src attribute. Thanks meeva for
+ reporting.
+- Don't truncate upon encountering
when using DOMLex. Thanks
+ Myrto Christina for finally convincing me to fix this.
+- Update YouTube filter for new code.
+- Fix parsing of rgb() values with spaces in them for 'border'
+ attribute.
+- Don't remove foo="" attributes if foo is a boolean attribute. Thanks
+ valME for reporting.
+
+4.6.0, released 2013-11-30
+# Secure URI munge hashing algorithm has changed to hash_hmac("sha256", $url, $secret).
+ Please update any verification scripts you may have.
+# URI parsing algorithm was made more strict, so only prefixes which
+ looks like schemes will actually be schemes. Thanks
+ Michael Gusev for fixing.
+# %Core.EscapeInvalidChildren is no longer supported, and no longer does
+ anything.
+! New directive %Core.AllowHostnameUnderscore which allows underscores
+ in hostnames.
+- Eliminate quadratic behavior in DOMLex by using a proper queue.
+ Thanks Ole Laursen for noticing this.
+- Rewritten MakeWellFormed/FixNesting implementation eliminates quadratic
+ behavior in the rest of the purificaiton pipeline. Thanks Chedburn
+ Networks for sponsoring this work.
+- Made Linkify URL parser a bit less permissive, so that non-breaking
+ spaces and commas are not included as part of URL. Thanks nAS for fixing.
+- Fix some bad interactions with %HTML.Allowed and injectors. Thanks
+ David Hirtz for reporting.
+- Fix infinite loop in DirectLex. Thanks Ashar Javed (@soaj1664ashar)
+ for reporting.
+
+4.5.0, released 2013-02-17
+# Fix bug where stacked attribute transforms clobber each other;
+ this also means it's no longer possible to override attribute
+ transforms in later modules. No internal code was using this
+ but this may break some clients.
+# We now use SHA-1 to identify cached definitions, instead of MD5.
+! Support display:inline-block
+! Support for more white-space CSS values.
+! Permit underscores in font families
+! Support for page-break-* CSS3 properties when proprietary properties
+ are enabled.
+! New directive %Core.DisableExcludes; can be set to 'true' to turn off
+ SGML excludes checking. If HTML Purifier is removing too much text
+ and you don't care about full standards compliance, try setting this to
+ 'true'.
+- Use prepend for SPL autoloading on PHP 5.3 and later.
+- Fix bug with nofollow transform when pre-existing rel exists.
+- Fix bug where background:url() always gets lower-cased
+ (but not background-image:url())
+- Fix bug with non lower-case color names in HTML
+- Fix bug where data URI validation doesn't remove temporary files.
+ Thanks Javier Marín Ros for reporting.
+- Don't remove certain empty tags on RemoveEmpty.
+
+4.4.0, released 2012-01-18
+# Removed PEARSax3 handler.
+# URI.Munge now munges URIs inside the same host that go from https
+ to http. Reported by Neike Taika-Tessaro.
+# Core.EscapeNonASCIICharacters now always transforms entities to
+ entities, even if target encoding is UTF-8.
+# Tighten up selector validation in ExtractStyleBlocks.
+ Non-syntactically valid selectors are now rejected, along with
+ some of the more obscure ones such as attribute selectors, the
+ :lang pseudoselector, and anything not in CSS2.1. Furthermore,
+ ID and class selectors now work properly with the relevant
+ configuration attributes. Also, mute errors when parsing CSS
+ with CSS Tidy. Reported by Mario Heiderich and Norman Hippert.
+! Added support for 'scope' attribute on tables.
+! Added %HTML.TargetBlank, which adds target="blank" to all outgoing links.
+! Properly handle sub-lists directly nested inside of lists in
+ a standards compliant way, by moving them into the preceding
+! Added %HTML.AllowedComments and %HTML.AllowedCommentsRegexp for
+ limited allowed comments in untrusted situations.
+! Implement iframes, and allow them to be used in untrusted mode with
+ %HTML.SafeIframe and %URI.SafeIframeRegexp. Thanks Bradley M. Froehle
+ for submitting an initial version of the patch.
+! The Forms module now works properly for transitional doctypes.
+! Added support for internationalized domain names. You need the PEAR
+ Net_IDNA2 module to be in your path; if it is installed, ensure the
+ class can be loaded and then set %Core.EnableIDNA to true.
+- Color keywords are now case insensitive. Thanks Yzmir Ramirez
+ for reporting.
+- Explicitly initialize anonModule variable to null.
+- Do not duplicate nofollow if already present. Thanks 178
+ for reporting.
+- Do not add nofollow if hostname matches our current host. Thanks 178
+ for reporting, and Neike Taika-Tessaro for helping diagnose.
+- Do not unset parser variable; this fixes intermittent serialization
+ problems. Thanks Neike Taika-Tessaro for reporting, bill
+ <10010tiger@gmail.com> for diagnosing.
+- Fix iconv truncation bug, where non-UTF-8 target encodings see
+ output truncated after around 8000 characters. Thanks Jörg Ludwig
+ for reporting.
+- Fix broken table content model for XHTML1.1 (and also earlier
+ versions, although the W3C validator doesn't catch those violations).
+ Thanks GlitchMr for reporting.
+
+4.3.0, released 2011-03-27
+# Fixed broken caching of customized raw definitions, but requires an
+ API change. The old API still works but will emit a warning,
+ see http://htmlpurifier.org/docs/enduser-customize.html#optimized
+ for how to upgrade your code.
+# Protect against Internet Explorer innerHTML behavior by specially
+ treating attributes with backticks but no angled brackets, quotes or
+ spaces. This constitutes a slight semantic change, which can be
+ reverted using %Output.FixInnerHTML. Reported by Neike Taika-Tessaro
+ and Mario Heiderich.
+# Protect against cssText/innerHTML by restricting allowed characters
+ used in fonts further than mandated by the specification and encoding
+ some extra special characters in URLs. Reported by Neike
+ Taika-Tessaro and Mario Heiderich.
+! Added %HTML.Nofollow to add rel="nofollow" to external links.
+! More types of SPL autoloaders allowed on later versions of PHP.
+! Implementations for position, top, left, right, bottom, z-index
+ when %CSS.Trusted is on.
+! Add %Cache.SerializerPermissions option for custom serializer
+ directory/file permissions
+! Fix longstanding bug in Flash support for non-IE browsers, and
+ allow more wmode attributes.
+! Add %CSS.AllowedFonts to restrict permissible font names.
+- Switch to an iterative traversal of the DOM, which prevents us
+ from running out of stack space for deeply nested documents.
+ Thanks Maxim Krizhanovsky for contributing a patch.
+- Make removal of conditional IE comments ungreedy; thanks Bernd
+ for reporting.
+- Escape CDATA before removing Internet Explorer comments.
+- Fix removal of id attributes under certain conditions by ensuring
+ armor attributes are preserved when recreating tags.
+- Check if schema.ser was corrupted.
+- Check if zend.ze1_compatibility_mode is on, and error out if it is.
+ This safety check is only done for HTMLPurifier.auto.php; if you
+ are using standalone or the specialized includes files, you're
+ expected to know what you're doing.
+- Stop repeatedly writing the cache file after I'm done customizing a
+ raw definition. Reported by ajh.
+- Switch to using require_once in the Bootstrap to work around bad
+ interaction with Zend Debugger and APC. Reported by Antonio Parraga.
+- Fix URI handling when hostname is missing but scheme is present.
+ Reported by Neike Taika-Tessaro.
+- Fix missing numeric entities on DirectLex; thanks Neike Taika-Tessaro
+ for reporting.
+- Fix harmless notice from indexing into empty string. Thanks Matthijs
+ Kooijman for reporting.
+- Don't autoclose no parent elements are able to support the element
+ that triggered the autoclose. In particular fixes strange behavior
+ of stray
tags. Thanks pkuliga@gmail.com for reporting and
+ Neike Taika-Tessaro for debugging assistance.
+
+4.2.0, released 2010-09-15
+! Added %Core.RemoveProcessingInstructions, which lets you remove
+ ... ?> statements.
+! Added %URI.DisableResources functionality; the directive originally
+ did nothing. Thanks David Rothstein for reporting.
+! Add documentation about configuration directive types.
+! Add %CSS.ForbiddenProperties configuration directive.
+! Add %HTML.FlashAllowFullScreen to permit embedded Flash objects
+ to utilize full-screen mode.
+! Add optional support for the file URI scheme, enable
+ by explicitly setting %URI.AllowedSchemes.
+! Add %Core.NormalizeNewlines options to allow turning off newline
+ normalization.
+- Fix improper handling of Internet Explorer conditional comments
+ by parser. Thanks zmonteca for reporting.
+- Fix missing attributes bug when running on Mac Snow Leopard and APC.
+ Thanks sidepodcast for the fix.
+- Warn if an element is allowed, but an attribute it requires is
+ not allowed.
+
+4.1.1, released 2010-05-31
+- Fix undefined index warnings in maintenance scripts.
+- Fix bug in DirectLex for parsing elements with a single attribute
+ with entities.
+- Rewrite CSS output logic for font-family and url(). Thanks Mario
+ Heiderich for reporting and Takeshi
+ Terada for suggesting the fix.
+- Emit an error for CollectErrors if a body is extracted
+- Fix bug where in background-position for center keyword handling.
+- Fix infinite loop when a wrapper element is inserted in a context
+ where it's not allowed. Thanks Lars for reporting.
+- Remove +x bit and shebang from index.php; only supported mode is to
+ explicitly call it with php.
+- Make test script less chatty when log_errors is on.
+
+4.1.0, released 2010-04-26
+! Support proprietary height attribute on table element
+! Support YouTube slideshows that contain /cp/ in their URL.
+! Support for data: URI scheme; not enabled by default, add it using
+ %URI.AllowedSchemes
+! Support flashvars when using %HTML.SafeObject and %HTML.SafeEmbed.
+! Support for Internet Explorer compatibility with %HTML.SafeObject
+ using %Output.FlashCompat.
+! Handle properly, by inserting the necessary
tag.
+- Always quote the insides of url(...) in CSS.
+
+4.0.0, released 2009-07-07
+# APIs for ConfigSchema subsystem have substantially changed. See
+ docs/dev-config-bcbreaks.txt for details; in essence, anything that
+ had both namespace and directive now have a single unified key.
+# Some configuration directives were renamed, specifically:
+ %AutoFormatParam.PurifierLinkifyDocURL -> %AutoFormat.PurifierLinkify.DocURL
+ %FilterParam.ExtractStyleBlocksEscaping -> %Filter.ExtractStyleBlocks.Escaping
+ %FilterParam.ExtractStyleBlocksScope -> %Filter.ExtractStyleBlocks.Scope
+ %FilterParam.ExtractStyleBlocksTidyImpl -> %Filter.ExtractStyleBlocks.TidyImpl
+ As usual, the old directive names will still work, but will throw E_NOTICE
+ errors.
+# The allowed values for class have been relaxed to allow all of CDATA for
+ doctypes that are not XHTML 1.1 or XHTML 2.0. For old behavior, set
+ %Attr.ClassUseCDATA to false.
+# Instead of appending the content model to an old content model, a blank
+ element will replace the old content model. You can use #SUPER to get
+ the old content model.
+! More robust support for name="" and id=""
+! HTMLPurifier_Config::inherit($config) allows you to inherit one
+ configuration, and have changes to that configuration be propagated
+ to all of its children.
+! Implement %HTML.Attr.Name.UseCDATA, which relaxes validation rules on
+ the name attribute when set. Use with care. Thanks Ian Cook for
+ sponsoring.
+! Implement %AutoFormat.RemoveEmpty.RemoveNbsp, which removes empty
+ tags that contain non-breaking spaces as well other whitespace. You
+ can also modify which tags should have maintained with
+ %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.
+! Implement %Attr.AllowedClasses, which allows administrators to restrict
+ classes users can use to a specified finite set of classes, and
+ %Attr.ForbiddenClasses, which is the logical inverse.
+! You can now maintain your own configuration schema directories by
+ creating a config-schema.php file or passing an extra argument. Check
+ docs/dev-config-schema.html for more details.
+! Added HTMLPurifier_Config->serialize() method, which lets you save away
+ your configuration in a compact serial file, which you can unserialize
+ and use directly without having to go through the overhead of setup.
+- Fix bug where URIDefinition would not get cleared if it's directives got
+ changed.
+- Fix fatal error in HTMLPurifier_Encoder on certain platforms (probably NetBSD 5.0)
+- Fix bug in Linkify autoformatter involving http://foo
+- Make %URI.Munge not apply to links that have the same host as your host.
+- Prevent stray tag from truncating output, if a second
+ is present.
+. Created script maintenance/rename-config.php for renaming a configuration
+ directive while maintaining its alias. This script does not change source code.
+. Implement namespace locking for definition construction, to prevent
+ bugs where a directive is used for definition construction but is not
+ used to construct the cache hash.
+
+3.3.0, released 2009-02-16
+! Implement CSS property 'overflow' when %CSS.AllowTricky is true.
+! Implement generic property list classess
+- Fix bug with testEncodingSupportsASCII() algorithm when iconv() implementation
+ does not do the "right thing" with characters not supported in the output
+ set.
+- Spellcheck UTF-8: The Secret To Character Encoding
+- Fix improper removal of the contents of elements with only whitespace. Thanks
+ Eric Wald for reporting.
+- Fix broken test suite in versions of PHP without spl_autoload_register()
+- Fix degenerate case with YouTube filter involving double hyphens.
+ Thanks Pierre Attar for reporting.
+- Fix YouTube rendering problem on certain versions of Firefox.
+- Fix CSSDefinition Printer problems with decorators
+- Add text parameter to unit tests, forces text output
+. Add verbose mode to command line test runner, use (--verbose)
+. Turn on unit tests for UnitConverter
+. Fix missing version number in configuration %Attr.DefaultImageAlt (added 3.2.0)
+. Fix newline errors that caused spurious failures when CRLF HTML Purifier was
+ tested on Linux.
+. Removed trailing whitespace from all text files, see
+ remote-trailing-whitespace.php maintenance script.
+. Convert configuration to use property list backend.
+
+3.2.0, released 2008-10-31
+# Using %Core.CollectErrors forces line number/column tracking on, whereas
+ previously you could theoretically turn it off.
+# HTMLPurifier_Injector->notifyEnd() is formally deprecated. Please
+ use handleEnd() instead.
+! %Output.AttrSort for when you need your attributes in alphabetical order to
+ deal with a bug in FCKEditor. Requested by frank farmer.
+! Enable HTML comments when %HTML.Trusted is on. Requested by Waldo Jaquith.
+! Proper support for name attribute. It is now allowed and equivalent to the id
+ attribute in a and img tags, and is only converted to id when %HTML.TidyLevel
+ is heavy (for all doctypes).
+! %AutoFormat.RemoveEmpty to remove some empty tags from documents. Please don't
+ use on hand-written HTML.
+! Add error-cases for unsupported elements in MakeWellFormed. This enables
+ the strategy to be used, standalone, on untrusted input.
+! %Core.AggressivelyFixLt is on by default. This causes more sensible
+ processing of left angled brackets in smileys and other whatnot.
+! Test scripts now have a 'type' parameter, which lets you say 'htmlpurifier',
+ 'phpt', 'vtest', etc. in order to only execute those tests. This supercedes
+ the --only-phpt parameter, although for backwards-compatibility the flag
+ will still work.
+! AutoParagraph auto-formatter will now preserve double-newlines upon output.
+ Users who are not performing inbound filtering, this may seem a little
+ useless, but as a bonus, the test suite and handling of edge cases is also
+ improved.
+! Experimental implementation of forms for %HTML.Trusted
+! Track column numbers when maintain line numbers is on
+! Proprietary 'background' attribute on table-related elements converted into
+ corresponding CSS. Thanks Fusemail for sponsoring this feature!
+! Add forward(), forwardUntilEndToken(), backward() and current() to Injector
+ supertype.
+! HTMLPurifier_Injector->handleEnd() permits modification to end tokens. The
+ time of operation varies slightly from notifyEnd() as *all* end tokens are
+ processed by the injector before they are subject to the well-formedness rules.
+! %Attr.DefaultImageAlt allows overriding default behavior of setting alt to
+ basename of image when not present.
+! %AutoFormat.DisplayLinkURI neuters tags into plain text URLs.
+- Fix two bugs in %URI.MakeAbsolute; one involving empty paths in base URLs,
+ the other involving an undefined $is_folder error.
+- Throw error when %Core.Encoding is set to a spurious value. Previously,
+ this errored silently and returned false.
+- Redirected stderr to stdout for flush error output.
+- %URI.DisableExternal will now use the host in %URI.Base if %URI.Host is not
+ available.
+- Do not re-munge URL if the output URL has the same host as the input URL.
+ Requested by Chris.
+- Fix error in documentation regarding %Filter.ExtractStyleBlocks
+- Prevent