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 2242ba476..4ef30eada 100644 --- a/boot.php +++ b/boot.php @@ -36,7 +36,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', 1193 ); +define ( 'DB_UPDATE_VERSION', 1194 ); /** * @brief Constant with a HTML line break. @@ -530,6 +530,8 @@ class App { private $cached_profile_image; private $cached_profile_picdate; + private static $a; + /** * @brief App constructor. */ @@ -710,6 +712,8 @@ class App { } } + self::$a = $this; + } function get_basepath() { @@ -734,6 +738,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'))) { 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/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/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/include/Contact.php b/include/Contact.php index 93d6237cb..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); } } @@ -208,15 +208,15 @@ function get_contact_details_by_url($url, $uid = -1) { } // 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) AND !isset($profile)) - $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", + $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) AND !isset($profile)) - $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", + $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) { @@ -228,7 +228,7 @@ function get_contact_details_by_url($url, $uid = -1) { $profile["nick"] = $r[0]["nick"]; if (!isset($profile["addr"]) AND $r[0]["addr"]) $profile["addr"] = $r[0]["addr"]; - if (!isset($profile["photo"]) AND $r[0]["photo"]) + if ((!isset($profile["photo"]) OR $r[0]["self"]) AND $r[0]["photo"]) $profile["photo"] = $r[0]["photo"]; if (!isset($profile["location"]) AND $r[0]["location"]) $profile["location"] = $r[0]["location"]; @@ -246,6 +246,8 @@ function get_contact_details_by_url($url, $uid = -1) { $profile["addr"] = $r[0]["addr"]; 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 @@ -410,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)); @@ -439,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`, @@ -470,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) @@ -479,23 +479,23 @@ 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) ); @@ -662,4 +662,34 @@ function posts_from_contact($a, $contact_id) { 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/Photo.php b/include/Photo.php index 5fdd682e7..3f1608d3e 100644 --- a/include/Photo.php +++ b/include/Photo.php @@ -720,65 +720,100 @@ 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 + * + * @return array Returns array of the different avatar sizes + */ +function update_contact_avatar($avatar,$uid,$cid) { - $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) { + $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)); } diff --git a/include/Scrape.php b/include/Scrape.php index 9cc708615..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(); @@ -662,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/api.php b/include/api.php index 3bc7c8bab..4d206da28 100644 --- a/include/api.php +++ b/include/api.php @@ -1551,6 +1551,8 @@ WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0 AND `contact`.`id` = `item`.`contact-id` AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0 + AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = '' + AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' $sql_extra AND `item`.`id`=%d", intval($id) @@ -1579,7 +1581,8 @@ $_REQUEST["source"] = api_source(); item_post($a); - } + } else + throw new ForbiddenException(); // this should output the last post (the one we just posted). $called_api = null; diff --git a/include/cron.php b/include/cron.php index bf3243cb6..3acf711dd 100644 --- a/include/cron.php +++ b/include/cron.php @@ -30,7 +30,6 @@ function cron_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'); @@ -164,6 +163,9 @@ function cron_run(&$argv, &$argc){ // Repair missing Diaspora values in contacts cron_repair_diaspora($a); + // Repair entries in the database + cron_repair_database(); + $manual_id = 0; $generation = 0; $force = false; @@ -417,6 +419,23 @@ function cron_repair_diaspora(&$a) { } } +/** + * @brief Do some repairs in database entries + * + */ +function cron_repair_database() { + + // Set the parent if it wasn't set. (Shouldn't happen - but does sometimes) + // This call is very "cheap" so we can do it at any time without a problem + q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0"); + + /// @todo + /// - remove thread entries without item + /// - remove sign entries without item + /// - remove children when parent got lost + /// - set contact-id in item when not present +} + if (array_search(__file__,get_included_files())===0){ cron_run($_SERVER["argv"],$_SERVER["argc"]); killme(); diff --git a/include/dbstructure.php b/include/dbstructure.php index 43dfbd7b3..96d18cd78 100644 --- a/include/dbstructure.php +++ b/include/dbstructure.php @@ -453,6 +453,7 @@ function db_definition() { "keywords" => array("type" => "text", "not null" => "1"), "gender" => array("type" => "varchar(32)", "not null" => "1", "default" => ""), "attag" => array("type" => "varchar(255)", "not null" => "1", "default" => ""), + "avatar" => array("type" => "varchar(255)", "not null" => "1", "default" => ""), "photo" => array("type" => "text", "not null" => "1"), "thumb" => array("type" => "text", "not null" => "1"), "micro" => array("type" => "text", "not null" => "1"), diff --git a/include/delivery.php b/include/delivery.php index a88873361..5ef942dd0 100644 --- a/include/delivery.php +++ b/include/delivery.php @@ -5,6 +5,7 @@ require_once('include/html2plain.php'); require_once("include/Scrape.php"); require_once('include/diaspora.php'); require_once("include/ostatus.php"); +require_once("include/dfrn.php"); function delivery_run(&$argv, &$argc){ global $a, $db; @@ -264,8 +265,6 @@ function delivery_run(&$argv, &$argc){ if(count($r)) $contact = $r[0]; - $hubxml = feed_hublinks(); - if($contact['self']) continue; @@ -278,138 +277,54 @@ function delivery_run(&$argv, &$argc){ case NETWORK_DFRN: logger('notifier: '.$target_item["guid"].' dfrndelivery: ' . $contact['name']); - $feed_template = get_markup_template('atom_feed.tpl'); - $mail_template = get_markup_template('atom_mail.tpl'); - - $atom = ''; - - - $birthday = feed_birthday($owner['uid'],$owner['timezone']); - - if(strlen($birthday)) - $birthday = '' . xmlify($birthday) . ''; - - $atom .= replace_macros($feed_template, array( - '$version' => xmlify(FRIENDICA_VERSION), - '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ), - '$feed_title' => xmlify($owner['name']), - '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) , - '$hub' => $hubxml, - '$salmon' => '', // private feed, we don't use salmon here - '$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' => $birthday, - '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '1' : '') - )); - - if($mail) { - $public_message = false; // mail is not public - - $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']); - - $atom .= replace_macros($mail_template, array( - '$name' => xmlify($owner['name']), - '$profile_page' => xmlify($owner['url']), - '$thumb' => xmlify($owner['thumb']), - '$item_id' => xmlify($item['uri']), - '$subject' => xmlify($item['title']), - '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)), - '$content' => xmlify($body), - '$parent_id' => xmlify($item['parent-uri']) - )); - } elseif($fsuggest) { - $public_message = false; // suggestions are not public - - $sugg_template = get_markup_template('atom_suggest.tpl'); - - $atom .= replace_macros($sugg_template, array( - '$name' => xmlify($item['name']), - '$url' => xmlify($item['url']), - '$photo' => xmlify($item['photo']), - '$request' => xmlify($item['request']), - '$note' => xmlify($item['note']) - )); - - // We don't need this any more - - q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", - intval($item['id']) - ); - } elseif($relocate) { - $public_message = false; // suggestions are not public - - $sugg_template = get_markup_template('atom_relocate.tpl'); - - /* get site pubkey. this could be a new installation with no site keys*/ - $pubkey = get_config('system','site_pubkey'); - if(! $pubkey) { - $res = new_keypair(1024); - set_config('system','site_prvkey', $res['prvkey']); - set_config('system','site_pubkey', $res['pubkey']); - } - - $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` - WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid); - $photos = array(); - $ext = Photo::supportedTypes(); - foreach($rp as $p){ - $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']]; - } - unset($rp, $ext); - - $atom .= replace_macros($sugg_template, array( - '$name' => xmlify($owner['name']), - '$photo' => xmlify($photos[4]), - '$thumb' => xmlify($photos[5]), - '$micro' => xmlify($photos[6]), - '$url' => xmlify($owner['url']), - '$request' => xmlify($owner['request']), - '$confirm' => xmlify($owner['confirm']), - '$notify' => xmlify($owner['notify']), - '$poll' => xmlify($owner['poll']), - '$sitepubkey' => xmlify(get_config('system','site_pubkey')), - //'$pubkey' => xmlify($owner['pubkey']), - //'$prvkey' => xmlify($owner['prvkey']), - )); - unset($photos); - } elseif($followup) { + if ($mail) { + $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']); + $atom = dfrn::mail($item, $owner); + } elseif ($fsuggest) { + $atom = dfrn::fsuggest($item, $owner); + q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id'])); + } elseif ($relocate) + $atom = dfrn::relocate($owner, $uid); + elseif($followup) { + $msgitems = array(); foreach($items as $item) { // there is only one item - if(! $item['parent']) + if(!$item['parent']) continue; if($item['id'] == $item_id) { logger('followup: item: ' . print_r($item,true), LOGGER_DATA); - $atom .= atom_entry($item,'text',null,$owner,false); + $msgitems[] = $item; } } + $atom = dfrn::entries($msgitems,$owner); } else { + $msgitems = array(); foreach($items as $item) { - if(! $item['parent']) + if(!$item['parent']) continue; // private emails may be in included in public conversations. Filter them. - if(($public_message) && $item['private'] == 1) + if(($public_message) && $item['private']) continue; $item_contact = get_item_contact($item,$icontacts); - if(! $item_contact) + if(!$item_contact) continue; if($normal_mode) { - if($item_id == $item['id'] || $item['id'] == $item['parent']) - $atom .= atom_entry($item,'text',null,$owner,true,(($top_level) ? $contact['id'] : 0)); - } else - $atom .= atom_entry($item,'text',null,$owner,true); + if($item_id == $item['id'] || $item['id'] == $item['parent']) { + $item["entry:comment-allow"] = true; + $item["entry:cid"] = (($top_level) ? $contact['id'] : 0); + $msgitems[] = $item; + } + } else { + $item["entry:comment-allow"] = true; + $msgitems[] = $item; + } } + $atom = dfrn::entries($msgitems,$owner); } - $atom .= '' . "\r\n"; - - logger('notifier: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG); + logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG); logger('notifier: ' . $atom, LOGGER_DATA); $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3)); @@ -458,7 +373,6 @@ function delivery_run(&$argv, &$argc){ if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level) break; - require_once('library/simplepie/simplepie.inc'); logger('mod-delivery: local delivery'); local_delivery($x[0],$atom); break; @@ -466,7 +380,7 @@ function delivery_run(&$argv, &$argc){ } if(! was_recently_delayed($contact['id'])) - $deliver_status = dfrn_deliver($owner,$contact,$atom); + $deliver_status = dfrn::deliver($owner,$contact,$atom); else $deliver_status = (-1); diff --git a/include/dfrn.php b/include/dfrn.php new file mode 100644 index 000000000..2c8e8ce38 --- /dev/null +++ b/include/dfrn.php @@ -0,0 +1,1048 @@ +formatOutput = true; + + $root = self::add_header($doc, $owner, "dfrn:owner", "", false); + + if(! count($items)) + return trim($doc->saveXML()); + + foreach($items as $item) { + $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]); + $root->appendChild($entry); + } + + return(trim($doc->saveXML())); + } + + /** + * @brief Generate an atom feed for the given user + * + * This function is called when another server is pulling data from the user feed. + * + * @param string $dfrn_id DFRN ID from the requesting party + * @param string $owner_nick Owner nick name + * @param string $last_update Date of the last update + * @param int $direction Can be -1, 0 or 1. + * + * @return string DFRN feed entries + */ + function feed($dfrn_id, $owner_nick, $last_update, $direction = 0) { + + $a = get_app(); + + $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']; + + $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'; + + $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; + + $doc = new DOMDocument('1.0', 'utf-8'); + $doc->formatOutput = true; + + $alternatelink = $owner['url']; + + if(isset($category)) + $alternatelink .= "/category/".$category; + + if ($public_feed) + $author = "dfrn:owner"; + else + $author = "author"; + + $root = self::add_header($doc, $owner, $author, $alternatelink, true); + + // This hook can't work anymore + // call_hooks('atom_feed', $atom); + + if(! count($items)) { + $atom = trim($doc->saveXML()); + + call_hooks('atom_feed_end', $atom); + + 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'; + + $entry = self::entry($doc, $type, $item, $owner, true); + $root->appendChild($entry); + + } + + $atom = trim($doc->saveXML()); + + call_hooks('atom_feed_end', $atom); + + return $atom; + } + + /** + * @brief Create XML text for DFRN mails + * + * @param array $item message elements + * @param array $owner Owner record + * + * @return string DFRN mail + */ + function mail($item, $owner) { + $doc = new DOMDocument('1.0', 'utf-8'); + $doc->formatOutput = true; + + $root = self::add_header($doc, $owner, "dfrn:owner", "", false); + + $mail = $doc->createElement("dfrn:mail"); + $sender = $doc->createElement("dfrn:sender"); + + xml_add_element($doc, $sender, "dfrn:name", $owner['name']); + xml_add_element($doc, $sender, "dfrn:uri", $owner['url']); + xml_add_element($doc, $sender, "dfrn:avatar", $owner['thumb']); + + $mail->appendChild($sender); + + xml_add_element($doc, $mail, "dfrn:id", $item['uri']); + xml_add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']); + xml_add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)); + xml_add_element($doc, $mail, "dfrn:subject", $item['title']); + xml_add_element($doc, $mail, "dfrn:content", $item['body']); + + $root->appendChild($mail); + + return(trim($doc->saveXML())); + } + + /** + * @brief Create XML text for DFRN friend suggestions + * + * @param array $item suggestion elements + * @param array $owner Owner record + * + * @return string DFRN suggestions + */ + function fsuggest($item, $owner) { + $doc = new DOMDocument('1.0', 'utf-8'); + $doc->formatOutput = true; + + $root = self::add_header($doc, $owner, "dfrn:owner", "", false); + + $suggest = $doc->createElement("dfrn:suggest"); + + xml_add_element($doc, $suggest, "dfrn:url", $item['url']); + xml_add_element($doc, $suggest, "dfrn:name", $item['name']); + xml_add_element($doc, $suggest, "dfrn:photo", $item['photo']); + xml_add_element($doc, $suggest, "dfrn:request", $item['request']); + xml_add_element($doc, $suggest, "dfrn:note", $item['note']); + + $root->appendChild($suggest); + + return(trim($doc->saveXML())); + } + + /** + * @brief Create XML text for DFRN relocations + * + * @param array $owner Owner record + * @param int $uid User ID + * + * @return string DFRN relocations + */ + function relocate($owner, $uid) { + + /* get site pubkey. this could be a new installation with no site keys*/ + $pubkey = get_config('system','site_pubkey'); + if(! $pubkey) { + $res = new_keypair(1024); + set_config('system','site_prvkey', $res['prvkey']); + set_config('system','site_pubkey', $res['pubkey']); + } + + $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` + WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid); + $photos = array(); + $ext = Photo::supportedTypes(); + + foreach($rp as $p) + $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']]; + + unset($rp, $ext); + + $doc = new DOMDocument('1.0', 'utf-8'); + $doc->formatOutput = true; + + $root = self::add_header($doc, $owner, "dfrn:owner", "", false); + + $relocate = $doc->createElement("dfrn:relocate"); + + xml_add_element($doc, $relocate, "dfrn:url", $owner['url']); + xml_add_element($doc, $relocate, "dfrn:name", $owner['name']); + xml_add_element($doc, $relocate, "dfrn:photo", $photos[4]); + xml_add_element($doc, $relocate, "dfrn:thumb", $photos[5]); + xml_add_element($doc, $relocate, "dfrn:micro", $photos[6]); + xml_add_element($doc, $relocate, "dfrn:request", $owner['request']); + xml_add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']); + xml_add_element($doc, $relocate, "dfrn:notify", $owner['notify']); + xml_add_element($doc, $relocate, "dfrn:poll", $owner['poll']); + xml_add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey')); + + $root->appendChild($relocate); + + return(trim($doc->saveXML())); + } + + /** + * @brief Adds the header elements for the DFRN protocol + * + * @param object $doc XML document + * @param array $owner Owner record + * @param string $authorelement Element name for the author + * @param string $alternatelink link to profile or category + * @param bool $public Is it a header for public posts? + * + * @return object XML root object + */ + private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) { + + if ($alternatelink == "") + $alternatelink = $owner['url']; + + $root = $doc->createElementNS(NS_ATOM, 'feed'); + $doc->appendChild($root); + + $root->setAttribute("xmlns:thr", NS_THR); + $root->setAttribute("xmlns:at", "http://purl.org/atompub/tombstones/1.0"); + $root->setAttribute("xmlns:media", NS_MEDIA); + $root->setAttribute("xmlns:dfrn", "http://purl.org/macgirvin/dfrn/1.0"); + $root->setAttribute("xmlns:activity", NS_ACTIVITY); + $root->setAttribute("xmlns:georss", NS_GEORSS); + $root->setAttribute("xmlns:poco", NS_POCO); + $root->setAttribute("xmlns:ostatus", NS_OSTATUS); + $root->setAttribute("xmlns:statusnet", NS_STATUSNET); + + //xml_add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]); + xml_add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]); + xml_add_element($doc, $root, "title", $owner["name"]); + + $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION); + xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes); + + $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"); + xml_add_element($doc, $root, "link", "", $attributes); + + $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink); + xml_add_element($doc, $root, "link", "", $attributes); + + ostatus_hublinks($doc, $root); + + if ($public) { + $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]); + xml_add_element($doc, $root, "link", "", $attributes); + + $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]); + xml_add_element($doc, $root, "link", "", $attributes); + + $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]); + xml_add_element($doc, $root, "link", "", $attributes); + } + + if ($owner['page-flags'] == PAGE_COMMUNITY) + xml_add_element($doc, $root, "dfrn:community", 1); + + xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME)); + + $author = self::add_author($doc, $owner, $authorelement, $public); + $root->appendChild($author); + + return $root; + } + + /** + * @brief Adds the author element in the header for the DFRN protocol + * + * @param object $doc XML document + * @param array $owner Owner record + * @param string $authorelement Element name for the author + * + * @return object XML author object + */ + private function add_author($doc, $owner, $authorelement, $public) { + + $author = $doc->createElement($authorelement); + + $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00' , ATOM_TIME); + $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME); + $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME); + + $attributes = array("dfrn:updated" => $namdate); + xml_add_element($doc, $author, "name", $owner["name"], $attributes); + + $attributes = array("dfrn:updated" => $namdate); + xml_add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes); + + $attributes = array("dfrn:updated" => $namdate); + xml_add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes); + + $attributes = array("rel" => "photo", "type" => "image/jpeg", "dfrn:updated" => $picdate, + "media:width" => 175, "media:height" => 175, "href" => $owner['photo']); + xml_add_element($doc, $author, "link", "", $attributes); + + $attributes = array("rel" => "avatar", "type" => "image/jpeg", "dfrn:updated" => $picdate, + "media:width" => 175, "media:height" => 175, "href" => $owner['photo']); + xml_add_element($doc, $author, "link", "", $attributes); + + $birthday = feed_birthday($owner['user_uid'], $owner['timezone']); + + if ($birthday) + xml_add_element($doc, $author, "dfrn:birthday", $birthday); + + // The following fields will only be generated if this isn't for a public feed + if ($public) + return $author; + + // Only show contact details when we are allowed to + $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`, `user`.`timezone`, + `profile`.`locality`, `profile`.`region`, `profile`.`country-name`, `profile`.`pub_keywords`, `profile`.`dob` + FROM `profile` + INNER JOIN `user` ON `user`.`uid` = `profile`.`uid` + WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d", + intval($owner['user_uid'])); + if ($r) { + $profile = $r[0]; + xml_add_element($doc, $author, "poco:displayName", $profile["name"]); + xml_add_element($doc, $author, "poco:updated", $namdate); + + if (trim($profile["dob"]) != "0000-00-00") + xml_add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"]))); + + xml_add_element($doc, $author, "poco:note", $profile["about"]); + xml_add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]); + + $savetz = date_default_timezone_get(); + date_default_timezone_set($profile["timezone"]); + xml_add_element($doc, $author, "poco:utcOffset", date("P")); + date_default_timezone_set($savetz); + + if (trim($profile["homepage"]) != "") { + $urls = $doc->createElement("poco:urls"); + xml_add_element($doc, $urls, "poco:type", "homepage"); + xml_add_element($doc, $urls, "poco:value", $profile["homepage"]); + xml_add_element($doc, $urls, "poco:primary", "true"); + $author->appendChild($urls); + } + + if (trim($profile["pub_keywords"]) != "") { + $keywords = explode(",", $profile["pub_keywords"]); + + foreach ($keywords AS $keyword) + xml_add_element($doc, $author, "poco:tags", trim($keyword)); + + } + + /// @todo When we are having the XMPP address in the profile we should propagate it here + $xmpp = ""; + if (trim($xmpp) != "") { + $ims = $doc->createElement("poco:ims"); + xml_add_element($doc, $ims, "poco:type", "xmpp"); + xml_add_element($doc, $ims, "poco:value", $xmpp); + xml_add_element($doc, $ims, "poco:primary", "true"); + $author->appendChild($ims); + } + + if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") { + $element = $doc->createElement("poco:address"); + + xml_add_element($doc, $element, "poco:formatted", formatted_location($profile)); + + if (trim($profile["locality"]) != "") + xml_add_element($doc, $element, "poco:locality", $profile["locality"]); + + if (trim($profile["region"]) != "") + xml_add_element($doc, $element, "poco:region", $profile["region"]); + + if (trim($profile["country-name"]) != "") + xml_add_element($doc, $element, "poco:country", $profile["country-name"]); + + $author->appendChild($element); + } + } + + return $author; + } + + /** + * @brief Adds the author elements in the "entry" elements of the DFRN protocol + * + * @param object $doc XML document + * @param string $element Element name for the author + * @param string $contact_url Link of the contact + * @param array $items Item elements + * + * @return object XML author object + */ + private function add_entry_author($doc, $element, $contact_url, $item) { + + $contact = get_contact_details_by_url($contact_url, $item["uid"]); + + $author = $doc->createElement($element); + xml_add_element($doc, $author, "name", $contact["name"]); + xml_add_element($doc, $author, "uri", $contact["url"]); + xml_add_element($doc, $author, "dfrn:handle", $contact["addr"]); + + /// @Todo + /// - Check real image type and image size + /// - Check which of these boths elements we should use + $attributes = array( + "rel" => "photo", + "type" => "image/jpeg", + "media:width" => 80, + "media:height" => 80, + "href" => $contact["photo"]); + xml_add_element($doc, $author, "link", "", $attributes); + + $attributes = array( + "rel" => "avatar", + "type" => "image/jpeg", + "media:width" => 80, + "media:height" => 80, + "href" => $contact["photo"]); + xml_add_element($doc, $author, "link", "", $attributes); + + return $author; + } + + /** + * @brief Adds the activity elements + * + * @param object $doc XML document + * @param string $element Element name for the activity + * @param string $activity activity value + * + * @return object XML activity object + */ + private function create_activity($doc, $element, $activity) { + + if($activity) { + $entry = $doc->createElement($element); + + $r = parse_xml_string($activity, false); + if(!$r) + return false; + if($r->type) + xml_add_element($doc, $entry, "activity:object-type", $r->type); + if($r->id) + xml_add_element($doc, $entry, "id", $r->id); + if($r->title) + xml_add_element($doc, $entry, "title", $r->title); + 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); + + $data = parse_xml_string($r->link, false); + foreach ($data->attributes() AS $parameter => $value) + $attributes[$parameter] = $value; + } else + $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link); + + xml_add_element($doc, $entry, "link", "", $attributes); + } + if($r->content) + xml_add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html")); + + return $entry; + } + + return false; + } + + /** + * @brief Adds the elements for attachments + * + * @param object $doc XML document + * @param object $root XML root + * @param array $item Item element + * + * @return object XML attachment object + */ + private function get_attachment($doc, $root, $item) { + $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) { + $attributes = array("rel" => "enclosure", + "href" => $matches[1], + "type" => $matches[3]); + + if(intval($matches[2])) + $attributes["length"] = intval($matches[2]); + + if(trim($matches[4]) != "") + $attributes["title"] = trim($matches[4]); + + xml_add_element($doc, $root, "link", "", $attributes); + } + } + } + } + + /** + * @brief Adds the "entry" elements for the DFRN protocol + * + * @param object $doc XML document + * @param string $type "text" or "html" + * @param array $item Item element + * @param array $owner Owner record + * @param bool $comment Trigger the sending of the "comment" element + * @param int $cid Contact ID of the recipient + * + * @return object XML entry object + */ + private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) { + + $mentioned = array(); + + if(!$item['parent']) + return; + + if($item['deleted']) { + $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)); + return xml_create_element($doc, "at:deleted-entry", "", $attributes); + } + + $entry = $doc->createElement("entry"); + + 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']; + + if ($type == 'html') { + $htmlbody = $body; + + if ($item['title'] != "") + $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody; + + $htmlbody = bbcode($htmlbody, false, false, 7); + } + + $author = self::add_entry_author($doc, "author", $item["author-link"], $item); + $entry->appendChild($author); + + $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item); + $entry->appendChild($dfrnowner); + + 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']); + $attributes = array("ref" => $parent_item, "type" => "text/html", + "href" => app::get_baseurl().'/display/'.$parent[0]['guid'], + "dfrn:diaspora_guid" => $parent[0]['guid']); + xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes); + } + + xml_add_element($doc, $entry, "id", $item["uri"]); + xml_add_element($doc, $entry, "title", $item["title"]); + + xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME)); + xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME)); + + xml_add_element($doc, $entry, "dfrn:env", base64url_encode($body, true)); + xml_add_element($doc, $entry, "content", (($type === 'html') ? $htmlbody : $body), array("type" => $type)); + + xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html", + "href" => app::get_baseurl()."/display/".$item["guid"])); + + // "comment-allow" is some old fashioned stuff for old Friendica versions. + // It is included in the rewritten code for completeness + if ($comment) + xml_add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child'])); + + if($item['location']) + xml_add_element($doc, $entry, "dfrn:location", $item['location']); + + if($item['coord']) + xml_add_element($doc, $entry, "georss:point", $item['coord']); + + if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) + xml_add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1)); + + if($item['extid']) + xml_add_element($doc, $entry, "dfrn:extid", $item['extid']); + + if($item['bookmark']) + xml_add_element($doc, $entry, "dfrn:bookmark", "true"); + + if($item['app']) + xml_add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app'])); + + xml_add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]); + + // The signed text contains the content in Markdown, the sender handle and the signatur for the content + // It is needed for relayed comments to Diaspora. + if($item['signed_text']) { + $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']))); + xml_add_element($doc, $entry, "dfrn:diaspora_signature", $sign); + } + + xml_add_element($doc, $entry, "activity:verb", construct_verb($item)); + + if ($item['object-type'] != "") + xml_add_element($doc, $entry, "activity:object-type", $item['object-type']); + elseif ($item['id'] == $item['parent']) + xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE); + else + xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT); + + $actobj = self::create_activity($doc, "activity:object", $item['object']); + if ($actobj) + $entry->appendChild($actobj); + + $actarg = self::create_activity($doc, "activity:target", $item['target']); + if ($actarg) + $entry->appendChild($actarg); + + $tags = item_getfeedtags($item); + + if(count($tags)) { + foreach($tags as $t) + if (($type != 'html') OR ($t[0] != "@")) + xml_add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2])); + } + + if(count($tags)) + foreach($tags as $t) + if ($t[0] == "@") + $mentioned[$t[1]] = $t[1]; + + foreach ($mentioned AS $mention) { + $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'", + intval($owner["uid"]), + dbesc(normalise_link($mention))); + if ($r[0]["forum"] OR $r[0]["prv"]) + xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned", + "ostatus:object-type" => ACTIVITY_OBJ_GROUP, + "href" => $mention)); + else + xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned", + "ostatus:object-type" => ACTIVITY_OBJ_PERSON, + "href" => $mention)); + } + + self::get_attachment($doc, $entry, $item); + + return $entry; + } + + /** + * @brief Delivers the atom content to the contacts + * + * @param array $owner Owner record + * @param array $contactr Contact record of the receiver + * @param string $atom Content that will be transmitted + * @param bool $dissolve (to be documented) + * + * @return int Deliver status. -1 means an error. + */ + function 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; + } +} diff --git a/include/diaspora.php b/include/diaspora.php index f03486fc2..93fe2a472 100644 --- a/include/diaspora.php +++ b/include/diaspora.php @@ -14,6 +14,7 @@ require_once('include/queue_fn.php'); require_once('include/lock.php'); require_once('include/threads.php'); require_once('mod/share.php'); +require_once('include/enotify.php'); function diaspora_dispatch_public($msg) { @@ -728,7 +729,7 @@ function diaspora_request($importer,$xml) { require_once('include/Photo.php'); - $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']); + update_contact_avatar($contact_record['photo'],$importer['uid'],$contact_record['id']); // technically they are sharing with us (CONTACT_IS_SHARING), // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX @@ -739,26 +740,17 @@ function diaspora_request($importer,$xml) { else $new_relation = CONTACT_IS_FOLLOWER; - $r = q("UPDATE `contact` SET - `photo` = '%s', - `thumb` = '%s', - `micro` = '%s', - `rel` = %d, + $r = q("UPDATE `contact` SET `rel` = %d, `name-date` = '%s', `uri-date` = '%s', - `avatar-date` = '%s', `blocked` = 0, `pending` = 0, `writable` = 1 WHERE `id` = %d ", - dbesc($photos[0]), - dbesc($photos[1]), - dbesc($photos[2]), intval($new_relation), dbesc(datetime_convert()), dbesc(datetime_convert()), - dbesc(datetime_convert()), intval($contact_record['id']) ); @@ -826,6 +818,23 @@ function diaspora_plink($addr, $guid) { return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid; } +function diaspora_repair_signature($signature, $handle = "", $level = 1) { + + if ($signature == "") + return($signature); + + if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) { + $signature = base64_decode($signature); + logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG); + + // Do a recursive call to be able to fix even multiple levels + if ($level < 10) + $signature = diaspora_repair_signature($signature, $handle, ++$level); + } + + return($signature); +} + function diaspora_post($importer,$xml,$msg) { $a = get_app(); @@ -1565,62 +1574,22 @@ function diaspora_comment($importer,$xml,$msg) { //); //} - if(($parent_item['origin']) && (! $parent_author_signature)) { + // If we are the origin of the parent we store the original signature and notify our followers + if($parent_item['origin']) { + $author_signature_base64 = base64_encode($author_signature); + $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle); + q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ", intval($message_id), dbesc($signed_data), - dbesc(base64_encode($author_signature)), + dbesc($author_signature_base64), dbesc($diaspora_handle) ); - // if the message isn't already being relayed, notify others - // the existence of parent_author_signature means the parent_author or owner - // is already relaying. - + // notify others proc_run('php','include/notifier.php','comment-import',$message_id); } - $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ", - dbesc($parent_item['uri']), - intval($importer['uid']) - ); - - if(count($myconv)) { - $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname']; - - 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['uid'], - 'item' => $datarray, - 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']), - 'source_name' => $datarray['author-name'], - 'source_link' => $datarray['author-link'], - 'source_photo' => $datarray['author-avatar'], - 'verb' => ACTIVITY_POST, - 'otype' => 'item', - 'parent' => $conv_parent, - 'parent_uri' => $parent_uri - )); - - // only send one notification - break; - } - } return; } @@ -1775,7 +1744,6 @@ function diaspora_conversation($importer,$xml,$msg) { intval($conversation['id']) ); - require_once('include/enotify.php'); notification(array( 'type' => NOTIFY_MAIL, 'notify_flags' => $importer['notify-flags'], @@ -2226,21 +2194,21 @@ EOT; // ); //} - if(! $parent_author_signature) { + // If we are the origin of the parent we store the original signature and notify our followers + if($parent_item['origin']) { + $author_signature_base64 = base64_encode($author_signature); + $author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle); + q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ", intval($message_id), dbesc($signed_data), - dbesc(base64_encode($author_signature)), + dbesc($author_signature_base64), dbesc($diaspora_handle) ); - } - // if the message isn't already being relayed, notify others - // the existence of parent_author_signature means the parent_author or owner - // is already relaying. The parent_item['origin'] indicates the message was created on our system - - if(($parent_item['origin']) && (! $parent_author_signature)) + // notify others proc_run('php','include/notifier.php','comment-import',$message_id); + } return; } @@ -2336,8 +2304,7 @@ function diaspora_signed_retraction($importer,$xml,$msg) { return; } - } - else { + } else { $sig_decode = base64_decode($sig); @@ -2371,7 +2338,7 @@ function diaspora_signed_retraction($importer,$xml,$msg) { intval($r[0]['parent']) ); if(count($p)) { - if(($p[0]['origin']) && (! $parent_author_signature)) { + if($p[0]['origin']) { q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ", $r[0]['id'], dbesc($signed_data), @@ -2456,7 +2423,7 @@ function diaspora_profile($importer,$xml,$msg) { require_once('include/Photo.php'); - $images = import_profile_photo($image_url,$importer['uid'],$contact['id']); + update_contact_avatar($image_url,$importer['uid'],$contact['id']); // Generic birthday. We don't know the timezone. The year is irrelevant. @@ -2474,15 +2441,12 @@ function diaspora_profile($importer,$xml,$msg) { /// @TODO Update name on item['author-name'] if the name changed. See consume_feed() /// (Not doing this currently because D* protocol is scheduled for revision soon). - $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d", + $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s', + `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d", dbesc($name), dbesc($nick), dbesc($diaspora_handle), dbesc(datetime_convert()), - dbesc($image_url), - dbesc($images[1]), - dbesc($images[2]), - dbesc(datetime_convert()), dbesc($birthday), dbesc($location), dbesc($about), @@ -2819,7 +2783,7 @@ function diaspora_send_followup($item,$owner,$contact,$public_batch = false) { // sign it if($like) - $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr; + $signed_text = $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr; else $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr; @@ -2852,9 +2816,6 @@ function diaspora_send_relay($item,$owner,$contact,$public_batch = false) { $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3); // $theiraddr = $contact['addr']; - $body = $item['body']; - $text = html_entity_decode(bb2diaspora($body)); - // Diaspora doesn't support threaded comments, but some // versions of Diaspora (i.e. Diaspora-pistos) support // likes on comments @@ -2905,61 +2866,53 @@ function diaspora_send_relay($item,$owner,$contact,$public_batch = false) { // fetch the original signature if the relayable was created by a Diaspora // or DFRN user. Relayables for other networks are not supported. -/* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1", + $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1", intval($item['id']) ); - if(count($r)) { + if(count($r)) { $orig_sign = $r[0]; $signed_text = $orig_sign['signed_text']; $authorsig = $orig_sign['signature']; $handle = $orig_sign['signer']; + + // Split the signed text + $signed_parts = explode(";", $signed_text); + + // Remove the parent guid + array_shift($signed_parts); + + // Remove the comment guid + array_shift($signed_parts); + + // Remove the handle + array_pop($signed_parts); + + // Glue the parts together + $text = implode(";", $signed_parts); } else { + // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica) + // This means that the comment won't be accepted by newer Diaspora servers - // Author signature information (for likes, comments, and retractions of likes or comments, - // whether from Diaspora or Friendica) must be placed in the `sign` table before this - // function is called - logger('diaspora_send_relay: original author signature not found, cannot send relayable'); - return; - }*/ + $body = $item['body']; + $text = html_entity_decode(bb2diaspora($body)); - /* Since the author signature is only checked by the parent, not by the relay recipients, - * I think it may not be necessary for us to do so much work to preserve all the original - * signatures. The important thing that Diaspora DOES need is the original creator's handle. - * Let's just generate that and forget about all the original author signature stuff. - * - * Note: this might be more of an problem if we want to support likes on comments for older - * versions of Diaspora (diaspora-pistos), but since there are a number of problems with - * doing that, let's ignore it for now. - * - * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't - * been done yet - */ + $handle = diaspora_handle_from_contact($item['contact-id']); + if(! $handle) + return; - $handle = diaspora_handle_from_contact($item['contact-id']); - if(! $handle) - return; + if($relay_retract) + $signed_text = $item['guid'] . ';' . $target_type; + elseif($like) + $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle; + else + $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle; - - if($relay_retract) - $sender_signed_text = $item['guid'] . ';' . $target_type; - elseif($like) - $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle; - else - $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle; + $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')); + } // Sign the relayable with the top-level owner's signature - // - // We'll use the $sender_signed_text that we just created, instead of the $signed_text - // stored in the database, because that provides the best chance that Diaspora will - // be able to reconstruct the signed text the same way we did. This is particularly a - // concern for the comment, whose signed text includes the text of the comment. The - // smallest change in the text of the comment, including removing whitespace, will - // make the signature verification fail. Since we translate from BB code to Diaspora's - // markup at the top of this function, which is AFTER we placed the original $signed_text - // in the database, it's hazardous to trust the original $signed_text. - - $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256')); + $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')); $msg = replace_macros($tpl,array( '$guid' => xmlify($item['guid']), diff --git a/include/discover_poco.php b/include/discover_poco.php index 6293317d3..a8f670334 100644 --- a/include/discover_poco.php +++ b/include/discover_poco.php @@ -76,11 +76,18 @@ function discover_poco_run(&$argv, &$argc){ update_suggestions(); elseif (($mode == 2) AND get_config('system','poco_completion')) discover_users(); - elseif (($mode == 1) AND ($search != "") and get_config('system','poco_local_search')) + elseif (($mode == 1) AND ($search != "") and get_config('system','poco_local_search')) { discover_directory($search); - elseif (($mode == 0) AND ($search == "") and (get_config('system','poco_discovery') > 0)) + gs_search_user($search); + } elseif (($mode == 0) AND ($search == "") and (get_config('system','poco_discovery') > 0)) { + // Query Friendica and Hubzilla servers for their users poco_discover(); + // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server) + if (!get_config('system','ostatus_disabled')) + gs_discover(); + } + logger('end '.$search); return; @@ -128,7 +135,7 @@ function discover_users() { else $server_url = poco_detect_server($user["url"]); - if (poco_check_server($server_url, $gcontacts[0]["network"])) { + if (($server_url == "") OR poco_check_server($server_url, $gcontacts[0]["network"])) { logger('Check user '.$user["url"]); poco_last_updated($user["url"], true); @@ -191,6 +198,36 @@ function discover_directory($search) { Cache::set("dirsearch:".$search, time(), CACHE_DAY); } +/** + * @brief Search for GNU Social user with gstools.org + * + * @param str $search User name + */ +function gs_search_user($search) { + + $a = get_app(); + + $url = "http://gstools.org/api/users_search/".urlencode($search); + + $result = z_fetch_url($url); + if (!$result["success"]) + return false; + + $contacts = json_decode($result["body"]); + + if ($contacts->status == 'ERROR') + return false; + + foreach($contacts->data AS $user) { + $contact = probe_url($user->site_address."/".$user->name); + if ($contact["network"] != NETWORK_PHANTOM) { + $contact["about"] = $user->description; + update_gcontact($contact); + } + } +} + + if (array_search(__file__,get_included_files())===0){ discover_poco_run($_SERVER["argv"],$_SERVER["argc"]); killme(); diff --git a/include/enotify.php b/include/enotify.php index e02c61383..54b59857c 100644 --- a/include/enotify.php +++ b/include/enotify.php @@ -633,4 +633,129 @@ function notification($params) { } +/** + * @brief Checks for item related notifications and sends them + * + * @param int $itemid ID of the item for which the check should be done + * @param int $uid User ID + * @param str $defaulttype (Optional) Forces a notification with this type. + */ +function check_item_notification($itemid, $uid, $defaulttype = "") { + + $notification_data = array("uid" => $uid, "profiles" => array()); + call_hooks('check_item_notification', $notification_data); + + $profiles = $notification_data["profiles"]; + + $user = q("SELECT `notify-flags`, `language`, `username`, `email` FROM `user` WHERE `uid` = %d", intval($uid)); + if (!$user) + return false; + + $owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid)); + if (!$owner) + return false; + + $profiles[] = $owner[0]["url"]; + + $profiles2 = array(); + + foreach ($profiles AS $profile) { + $profiles2[] = normalise_link($profile); + $profiles2[] = str_replace("http://", "https://", normalise_link($profile)); + } + + $profiles = $profiles2; + + $profile_list = ""; + + foreach ($profiles AS $profile) { + if ($profile_list != "") + $profile_list .= "', '"; + + $profile_list .= dbesc($profile); + } + + $profile_list = "'".$profile_list."'"; + + // Only act if it is a "real" post + // We need the additional check for the "local_profile" because of mixed situations on connector networks + $item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`, + `parent-uri`, `uri`, `contact-id` + FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND + NOT (`author-link` IN ($profile_list)) LIMIT 1", + intval($itemid), dbesc(ACTIVITY_POST)); + if (!$item) + return false; + + // Generate the notification array + $params = array(); + $params["uid"] = $uid; + $params["notify_flags"] = $user[0]["notify-flags"]; + $params["language"] = $user[0]["language"]; + $params["to_name"] = $user[0]["username"]; + $params["to_email"] = $user[0]["email"]; + $params["item"] = $item[0]; + $params["parent"] = $item[0]["parent"]; + $params["link"] = App::get_baseurl().'/display/'.urlencode($item[0]["guid"]); + $params["otype"] = 'item'; + $params["source_name"] = $item[0]["author-name"]; + $params["source_link"] = $item[0]["author-link"]; + $params["source_photo"] = $item[0]["author-avatar"]; + + if ($item[0]["parent-uri"] === $item[0]["uri"]) { + // 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($item[0]['contact-id']), + intval($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($itemid), intval(TERM_MENTION), intval($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($uid)); + if (count($r)) + $send_notification = true; + } + } + } + + if ($send_notification) { + $params["type"] = NOTIFY_SHARE; + $params["verb"] = ACTIVITY_TAG; + } + } + + // Is the user mentioned in this post? + $tagged = false; + + foreach ($profiles AS $profile) { + if (strpos($item[0]["tag"], "=".$profile."]") OR strpos($item[0]["body"], "=".$profile."]")) + $tagged = true; + } + + if ($item[0]["mention"] OR $tagged OR ($defaulttype == NOTIFY_TAGSELF)) { + $params["type"] = NOTIFY_TAGSELF; + $params["verb"] = ACTIVITY_TAG; + } + + // Is it a post that the user had started or where he interacted? + $parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid` + WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND + (`thread`.`mention` OR `item`.`author-link` IN ($profile_list)) + LIMIT 1", + intval($item[0]["parent"]), intval($uid)); + + if ($parent AND !isset($params["type"])) { + $params["type"] = NOTIFY_COMMENT; + $params["verb"] = ACTIVITY_POST; + } + + if (isset($params["type"])) + notification($params); +} ?> diff --git a/include/event.php b/include/event.php index c4111dc0b..13c414c9e 100644 --- a/include/event.php +++ b/include/event.php @@ -61,7 +61,7 @@ function format_event_html($ev, $simple = false) { . bbcode($ev['location']) . '

' . "\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; } 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/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 index 995a29cad..952d09a49 100644 --- a/include/forums.php +++ b/include/forums.php @@ -42,6 +42,9 @@ function get_forumlist($uid, $showhidden = true, $lastitem, $showprivate = false intval($uid) ); + if (!$contacts) + return($forumlist); + foreach($contacts as $contact) { $forumlist[] = array( 'url' => $contact['url'], 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/items.php b/include/items.php index a74ca3b36..21a0c414d 100644 --- a/include/items.php +++ b/include/items.php @@ -14,314 +14,18 @@ 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('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,8 +144,6 @@ function title_is_body($title, $body) { return($title == $body); } - - function get_atom_elements($feed, $item, $contact = array()) { require_once('library/HTMLPurifier.auto.php'); @@ -465,17 +167,6 @@ function get_atom_elements($feed, $item, $contact = array()) { $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 @@ -853,62 +544,6 @@ function get_atom_elements($feed, $item, $contact = array()) { $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); @@ -1334,9 +969,37 @@ function item_store($arr,$force_parent = false, $notify = false, $dontcache = fa logger("item_store: Set network to ".$arr["network"]." for ".$arr["uri"], LOGGER_DEBUG); } - if ($arr["gcontact-id"] == 0) - $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['author-link'], "network" => $arr['network'], - "photo" => $arr['author-avatar'], "name" => $arr['author-name'])); + // 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 @@ -1609,6 +1272,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 +1324,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 +1528,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 +1624,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 @@ -2643,7 +1995,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) logger('consume_feed: feed item count = ' . $feed->get_item_quantity()); - // in inverse date order + // in inverse date order if ($datedir) $items = array_reverse($feed->get_items()); else @@ -3040,6 +2392,9 @@ function item_is_remote_self($contact, &$datarray) { } function local_delivery($importer,$data) { + + require_once('library/simplepie/simplepie.inc'); + $a = get_app(); logger(__function__, LOGGER_TRACE); @@ -3818,33 +3173,7 @@ function local_delivery($importer,$data) { } 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; @@ -3966,59 +3295,6 @@ function local_delivery($importer,$data) { $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; } } @@ -4313,7 +3589,6 @@ function lose_sharer($importer,$contact,$datarray,$item) { } } - function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') { $a = get_app(); @@ -4356,189 +3631,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 .= "\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 +3734,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 +3794,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 611f00632..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; 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/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 b7799fa9d..37b308db7 100644 --- a/include/ostatus.php +++ b/include/ostatus.php @@ -127,7 +127,8 @@ 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 $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue; @@ -158,24 +159,21 @@ function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG); - 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"]); } - if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['photo'])) { + 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($author["author-avatar"]), 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"]; @@ -558,29 +556,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"] - )); - } } } @@ -1025,28 +1000,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) { @@ -1121,7 +1074,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) { @@ -1129,7 +1082,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); } diff --git a/include/poller.php b/include/poller.php index c681bfb38..190f3fb1a 100644 --- a/include/poller.php +++ b/include/poller.php @@ -39,8 +39,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 +52,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); @@ -124,6 +117,32 @@ function poller_run(&$argv, &$argc){ } +/** + * @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/socgraph.php b/include/socgraph.php index a01c9c5cb..c54534339 100644 --- a/include/socgraph.php +++ b/include/socgraph.php @@ -289,93 +289,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 (($alias == "") AND ($x[0]['alias'] != "")) - $alias = $x[0]['alias']; - - if (($notify == "") AND ($x[0]['notify'] != "")) - $notify = $x[0]['notify']; - - 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, - `alias` = '$s', `notify` = '%s' - 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), - dbesc($alias), - dbesc($notify), - intval($generation), - intval($generation), - dbesc(normalise_link($profile_url)) - ); - } - } else { - // Maybe another process had inserted the entry after the first check, so it again - $x = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", - dbesc(normalise_link($profile_url)) - ); - if(!$x) { - q("INSERT INTO `gcontact` (`name`, `nick`, `addr`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `alias`, `notify`, `generation`) - VALUES ('%s', '%s', '%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), - dbesc($alias), - dbesc($notify), - intval($generation) - ); - $x = q("SELECT `id` 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", @@ -402,13 +334,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; } @@ -721,6 +646,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; @@ -792,19 +721,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; - $versionparts = explode("-", $version); - $version = $versionparts[0]; + 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) { @@ -1315,18 +1248,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) { @@ -1520,7 +1465,7 @@ function get_gcontact_id($contact) { if ($contact["network"] == NETWORK_STATUSNET) $contact["network"] = NETWORK_OSTATUS; - $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", + $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2", dbesc(normalise_link($contact["url"]))); if ($r) @@ -1542,13 +1487,18 @@ function get_gcontact_id($contact) { intval($contact["generation"]) ); - $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", + $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; } @@ -1567,78 +1517,55 @@ function update_gcontact($contact) { if (!$gcontact_id) return false; - $r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`, `hide`, `nsfw`, `network`, `alias`, `notify`, `url` + $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)); - if ($contact["generation"] == 0) - $contact["generation"] = $r[0]["generation"]; + // Get all field names + $fields = array(); + foreach ($r[0] AS $field => $data) + $fields[$field] = $data; - if ($contact["photo"] == "") - $contact["photo"] = $r[0]["photo"]; + unset($fields["url"]); + unset($fields["updated"]); - if ($contact["name"] == "") - $contact["name"] = $r[0]["name"]; - - if ($contact["nick"] == "") - $contact["nick"] = $r[0]["nick"]; - - if ($contact["addr"] == "") - $contact["addr"] = $r[0]["addr"]; - - if ($contact["location"] =="") - $contact["location"] = $r[0]["location"]; - - if ($contact["about"] =="") - $contact["about"] = $r[0]["about"]; - - if ($contact["birthday"] =="") - $contact["birthday"] = $r[0]["birthday"]; - - if ($contact["gender"] =="") - $contact["gender"] = $r[0]["gender"]; - - if ($contact["keywords"] =="") - $contact["keywords"] = $r[0]["keywords"]; - - if (!isset($contact["hide"])) - $contact["hide"] = $r[0]["hide"]; - - if (!isset($contact["nsfw"])) - $contact["nsfw"] = $r[0]["nsfw"]; - - if ($contact["network"] =="") - $contact["network"] = $r[0]["network"]; - - if ($contact["alias"] =="") - $contact["alias"] = $r[0]["alias"]; - - if ($contact["url"] =="") - $contact["url"] = $r[0]["url"]; - - if ($contact["notify"] =="") - $contact["notify"] = $r[0]["notify"]; + // 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 (($contact["photo"] != $r[0]["photo"]) OR ($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["addr"] != $r[0]["addr"]) OR - ($contact["birthday"] != $r[0]["birthday"]) OR ($contact["gender"] != $r[0]["gender"]) OR ($contact["keywords"] != $r[0]["keywords"]) OR - ($contact["hide"] != $r[0]["hide"]) OR ($contact["nsfw"] != $r[0]["nsfw"]) OR ($contact["network"] != $r[0]["network"]) OR - ($contact["alias"] != $r[0]["alias"]) OR ($contact["notify"] != $r[0]["notify"]) OR ($contact["url"] != $r[0]["url"]) OR - ($contact["location"] != $r[0]["location"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["generation"] < $r[0]["generation"])) { + 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` = %d, `hide` = %d, `nsfw` = %d, `alias` = '%s', `notify` = '%s', `url` = '%s', - `location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%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(datetime_convert()), + intval($contact["generation"]), dbesc($contact["updated"]), + dbesc($contact["server_url"]), dbesc($contact["connect"]), dbesc(normalise_link($contact["url"])), intval($contact["generation"])); } @@ -1656,4 +1583,82 @@ function update_gcontact_from_probe($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 fc5e79294..4f3af5aee 100644 --- a/include/text.php +++ b/include/text.php @@ -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. @@ -1533,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')).''. '