]> git.mxchange.org Git - friendica.git/blob - include/dfrn.php
DFRN: Mentions were imported as hash tags
[friendica.git] / include / dfrn.php
1 <?php
2 /**
3  * @file include/dfrn.php
4  * @brief The implementation of the dfrn protocol
5  *
6  * https://github.com/friendica/friendica/wiki/Protocol
7  */
8
9 require_once("include/Contact.php");
10 require_once("include/ostatus.php");
11 require_once("include/enotify.php");
12 require_once("include/threads.php");
13 require_once("include/socgraph.php");
14 require_once("include/items.php");
15 require_once("include/tags.php");
16 require_once("include/files.php");
17 require_once("include/event.php");
18 require_once("include/text.php");
19 require_once("include/oembed.php");
20 require_once("include/html2bbcode.php");
21 require_once("include/bbcode.php");
22
23 /**
24  * @brief This class contain functions to create and send DFRN XML files
25  *
26  */
27 class dfrn {
28
29         const DFRN_TOP_LEVEL = 0;       // Top level posting
30         const DFRN_REPLY = 1;           // Regular reply that is stored locally
31         const DFRN_REPLY_RC = 2;        // Reply that will be relayed
32
33         /**
34          * @brief Generates the atom entries for delivery.php
35          *
36          * This function is used whenever content is transmitted via DFRN.
37          *
38          * @param array $items Item elements
39          * @param array $owner Owner record
40          *
41          * @return string DFRN entries
42          */
43         public static function entries($items,$owner) {
44
45                 $doc = new DOMDocument('1.0', 'utf-8');
46                 $doc->formatOutput = true;
47
48                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
49
50                 if(! count($items))
51                         return trim($doc->saveXML());
52
53                 foreach($items as $item) {
54                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
55                         $root->appendChild($entry);
56                 }
57
58                 return(trim($doc->saveXML()));
59         }
60
61         /**
62          * @brief Generate an atom feed for the given user
63          *
64          * This function is called when another server is pulling data from the user feed.
65          *
66          * @param string $dfrn_id DFRN ID from the requesting party
67          * @param string $owner_nick Owner nick name
68          * @param string $last_update Date of the last update
69          * @param int $direction Can be -1, 0 or 1.
70          *
71          * @return string DFRN feed entries
72          */
73         public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0) {
74
75                 $a = get_app();
76
77                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
78                 $public_feed = (($dfrn_id) ? false : true);
79                 $starred     = false;   // not yet implemented, possible security issues
80                 $converse    = false;
81
82                 if($public_feed && $a->argc > 2) {
83                         for($x = 2; $x < $a->argc; $x++) {
84                                 if($a->argv[$x] == 'converse')
85                                         $converse = true;
86                                 if($a->argv[$x] == 'starred')
87                                         $starred = true;
88                                 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
89                                         $category = $a->argv[$x+1];
90                         }
91                 }
92
93
94
95                 // default permissions - anonymous user
96
97                 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
98
99                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
100                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
101                         WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
102                         dbesc($owner_nick)
103                 );
104
105                 if(! count($r))
106                         killme();
107
108                 $owner = $r[0];
109                 $owner_id = $owner['uid'];
110                 $owner_nick = $owner['nickname'];
111
112                 $sql_post_table = "";
113                 $visibility = "";
114
115                 if(! $public_feed) {
116
117                         $sql_extra = '';
118                         switch($direction) {
119                                 case (-1):
120                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
121                                         $my_id = $dfrn_id;
122                                         break;
123                                 case 0:
124                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
125                                         $my_id = '1:' . $dfrn_id;
126                                         break;
127                                 case 1:
128                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
129                                         $my_id = '0:' . $dfrn_id;
130                                         break;
131                                 default:
132                                         return false;
133                                         break; // NOTREACHED
134                         }
135
136                         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
137                                 intval($owner_id)
138                         );
139
140                         if(! count($r))
141                                 killme();
142
143                         $contact = $r[0];
144                         require_once('include/security.php');
145                         $groups = init_groups_visitor($contact['id']);
146
147                         if(count($groups)) {
148                                 for($x = 0; $x < count($groups); $x ++)
149                                         $groups[$x] = '<' . intval($groups[$x]) . '>' ;
150                                 $gs = implode('|', $groups);
151                         } else
152                                 $gs = '<<>>' ; // Impossible to match
153
154                         $sql_extra = sprintf("
155                                 AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
156                                 AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
157                                 AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
158                                 AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
159                         ",
160                                 intval($contact['id']),
161                                 intval($contact['id']),
162                                 dbesc($gs),
163                                 dbesc($gs)
164                         );
165                 }
166
167                 if($public_feed)
168                         $sort = 'DESC';
169                 else
170                         $sort = 'ASC';
171
172                 $date_field = "`changed`";
173                 $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
174
175                 if(! strlen($last_update))
176                         $last_update = 'now -30 days';
177
178                 if(isset($category)) {
179                         $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` ",
180                                         dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
181                         //$sql_extra .= file_tag_file_query('item',$category,'category');
182                 }
183
184                 if($public_feed) {
185                         if(! $converse)
186                                 $sql_extra .= " AND `contact`.`self` = 1 ";
187                 }
188
189                 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
190
191                 //      AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
192                 //      dbesc($check_date),
193
194                 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`,
195                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
196                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
197                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
198                         `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
199                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
200                         FROM `item` $sql_post_table
201                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
202                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
203                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
204                         WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
205                         AND ((`item`.`wall` = 1) $visibility) AND `item`.$date_field > '%s'
206                         $sql_extra
207                         ORDER BY $sql_order LIMIT 0, 300",
208                         intval($owner_id),
209                         dbesc($check_date),
210                         dbesc($sort)
211                 );
212
213                 // Will check further below if this actually returned results.
214                 // We will provide an empty feed if that is the case.
215
216                 $items = $r;
217
218                 $doc = new DOMDocument('1.0', 'utf-8');
219                 $doc->formatOutput = true;
220
221                 $alternatelink = $owner['url'];
222
223                 if(isset($category))
224                         $alternatelink .= "/category/".$category;
225
226                 if ($public_feed)
227                         $author = "dfrn:owner";
228                 else
229                         $author = "author";
230
231                 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
232
233                 // This hook can't work anymore
234                 //      call_hooks('atom_feed', $atom);
235
236                 if(! count($items)) {
237                         $atom = trim($doc->saveXML());
238
239                         call_hooks('atom_feed_end', $atom);
240
241                         return $atom;
242                 }
243
244                 foreach($items as $item) {
245
246                         // prevent private email from leaking.
247                         if($item['network'] === NETWORK_MAIL)
248                                 continue;
249
250                         // public feeds get html, our own nodes use bbcode
251
252                         if($public_feed) {
253                                 $type = 'html';
254                                 // catch any email that's in a public conversation and make sure it doesn't leak
255                                 if($item['private'])
256                                         continue;
257                         } else
258                                 $type = 'text';
259
260                         $entry = self::entry($doc, $type, $item, $owner, true);
261                         $root->appendChild($entry);
262
263                 }
264
265                 $atom = trim($doc->saveXML());
266
267                 call_hooks('atom_feed_end', $atom);
268
269                 return $atom;
270         }
271
272         /**
273          * @brief Create XML text for DFRN mails
274          *
275          * @param array $item message elements
276          * @param array $owner Owner record
277          *
278          * @return string DFRN mail
279          */
280         public static function mail($item, $owner) {
281                 $doc = new DOMDocument('1.0', 'utf-8');
282                 $doc->formatOutput = true;
283
284                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
285
286                 $mail = $doc->createElement("dfrn:mail");
287                 $sender = $doc->createElement("dfrn:sender");
288
289                 xml_add_element($doc, $sender, "dfrn:name", $owner['name']);
290                 xml_add_element($doc, $sender, "dfrn:uri", $owner['url']);
291                 xml_add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
292
293                 $mail->appendChild($sender);
294
295                 xml_add_element($doc, $mail, "dfrn:id", $item['uri']);
296                 xml_add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
297                 xml_add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
298                 xml_add_element($doc, $mail, "dfrn:subject", $item['title']);
299                 xml_add_element($doc, $mail, "dfrn:content", $item['body']);
300
301                 $root->appendChild($mail);
302
303                 return(trim($doc->saveXML()));
304         }
305
306         /**
307          * @brief Create XML text for DFRN friend suggestions
308          *
309          * @param array $item suggestion elements
310          * @param array $owner Owner record
311          *
312          * @return string DFRN suggestions
313          */
314         public static function fsuggest($item, $owner) {
315                 $doc = new DOMDocument('1.0', 'utf-8');
316                 $doc->formatOutput = true;
317
318                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
319
320                 $suggest = $doc->createElement("dfrn:suggest");
321
322                 xml_add_element($doc, $suggest, "dfrn:url", $item['url']);
323                 xml_add_element($doc, $suggest, "dfrn:name", $item['name']);
324                 xml_add_element($doc, $suggest, "dfrn:photo", $item['photo']);
325                 xml_add_element($doc, $suggest, "dfrn:request", $item['request']);
326                 xml_add_element($doc, $suggest, "dfrn:note", $item['note']);
327
328                 $root->appendChild($suggest);
329
330                 return(trim($doc->saveXML()));
331         }
332
333         /**
334          * @brief Create XML text for DFRN relocations
335          *
336          * @param array $owner Owner record
337          * @param int $uid User ID
338          *
339          * @return string DFRN relocations
340          */
341         public static function relocate($owner, $uid) {
342
343                 /* get site pubkey. this could be a new installation with no site keys*/
344                 $pubkey = get_config('system','site_pubkey');
345                 if(! $pubkey) {
346                         $res = new_keypair(1024);
347                         set_config('system','site_prvkey', $res['prvkey']);
348                         set_config('system','site_pubkey', $res['pubkey']);
349                 }
350
351                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
352                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
353                 $photos = array();
354                 $ext = Photo::supportedTypes();
355
356                 foreach($rp as $p)
357                         $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
358
359                 unset($rp, $ext);
360
361                 $doc = new DOMDocument('1.0', 'utf-8');
362                 $doc->formatOutput = true;
363
364                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
365
366                 $relocate = $doc->createElement("dfrn:relocate");
367
368                 xml_add_element($doc, $relocate, "dfrn:url", $owner['url']);
369                 xml_add_element($doc, $relocate, "dfrn:name", $owner['name']);
370                 xml_add_element($doc, $relocate, "dfrn:photo", $photos[4]);
371                 xml_add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
372                 xml_add_element($doc, $relocate, "dfrn:micro", $photos[6]);
373                 xml_add_element($doc, $relocate, "dfrn:request", $owner['request']);
374                 xml_add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
375                 xml_add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
376                 xml_add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
377                 xml_add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
378
379                 $root->appendChild($relocate);
380
381                 return(trim($doc->saveXML()));
382         }
383
384         /**
385          * @brief Adds the header elements for the DFRN protocol
386          *
387          * @param object $doc XML document
388          * @param array $owner Owner record
389          * @param string $authorelement Element name for the author
390          * @param string $alternatelink link to profile or category
391          * @param bool $public Is it a header for public posts?
392          *
393          * @return object XML root object
394          */
395         private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
396
397                 if ($alternatelink == "")
398                         $alternatelink = $owner['url'];
399
400                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
401                 $doc->appendChild($root);
402
403                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
404                 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
405                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
406                 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
407                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
408                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
409                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
410                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
411                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
412
413                 xml_add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
414                 xml_add_element($doc, $root, "title", $owner["name"]);
415
416                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
417                 xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
418
419                 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
420                 xml_add_element($doc, $root, "link", "", $attributes);
421
422                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
423                 xml_add_element($doc, $root, "link", "", $attributes);
424
425
426                 if ($public) {
427                         // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
428                         ostatus_hublinks($doc, $root);
429
430                         $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
431                         xml_add_element($doc, $root, "link", "", $attributes);
432
433                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
434                         xml_add_element($doc, $root, "link", "", $attributes);
435
436                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
437                         xml_add_element($doc, $root, "link", "", $attributes);
438                 }
439
440                 if ($owner['page-flags'] == PAGE_COMMUNITY)
441                         xml_add_element($doc, $root, "dfrn:community", 1);
442
443                 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
444
445                 xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
446
447                 $author = self::add_author($doc, $owner, $authorelement, $public);
448                 $root->appendChild($author);
449
450                 return $root;
451         }
452
453         /**
454          * @brief Adds the author element in the header for the DFRN protocol
455          *
456          * @param object $doc XML document
457          * @param array $owner Owner record
458          * @param string $authorelement Element name for the author
459          *
460          * @return object XML author object
461          */
462         private function add_author($doc, $owner, $authorelement, $public) {
463
464                 $author = $doc->createElement($authorelement);
465
466                 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00' , ATOM_TIME);
467                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
468                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
469
470                 $attributes = array("dfrn:updated" => $namdate);
471                 xml_add_element($doc, $author, "name", $owner["name"], $attributes);
472
473                 $attributes = array("dfrn:updated" => $namdate);
474                 xml_add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
475
476                 $attributes = array("dfrn:updated" => $namdate);
477                 xml_add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
478
479                 $attributes = array("rel" => "photo", "type" => "image/jpeg", "dfrn:updated" => $picdate,
480                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
481                 xml_add_element($doc, $author, "link", "", $attributes);
482
483                 $attributes = array("rel" => "avatar", "type" => "image/jpeg", "dfrn:updated" => $picdate,
484                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
485                 xml_add_element($doc, $author, "link", "", $attributes);
486
487                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
488
489                 if ($birthday)
490                         xml_add_element($doc, $author, "dfrn:birthday", $birthday);
491
492                 // The following fields will only be generated if this isn't for a public feed
493                 if ($public)
494                         return $author;
495
496                 // Only show contact details when we are allowed to
497                 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`, `user`.`timezone`,
498                                 `profile`.`locality`, `profile`.`region`, `profile`.`country-name`, `profile`.`pub_keywords`, `profile`.`dob`
499                         FROM `profile`
500                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
501                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
502                         intval($owner['uid']));
503                 if ($r) {
504                         $profile = $r[0];
505                         xml_add_element($doc, $author, "poco:displayName", $profile["name"]);
506                         xml_add_element($doc, $author, "poco:updated", $namdate);
507
508                         if (trim($profile["dob"]) != "0000-00-00")
509                                 xml_add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
510
511                         xml_add_element($doc, $author, "poco:note", $profile["about"]);
512                         xml_add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
513
514                         $savetz = date_default_timezone_get();
515                         date_default_timezone_set($profile["timezone"]);
516                         xml_add_element($doc, $author, "poco:utcOffset", date("P"));
517                         date_default_timezone_set($savetz);
518
519                         if (trim($profile["homepage"]) != "") {
520                                 $urls = $doc->createElement("poco:urls");
521                                 xml_add_element($doc, $urls, "poco:type", "homepage");
522                                 xml_add_element($doc, $urls, "poco:value", $profile["homepage"]);
523                                 xml_add_element($doc, $urls, "poco:primary", "true");
524                                 $author->appendChild($urls);
525                         }
526
527                         if (trim($profile["pub_keywords"]) != "") {
528                                 $keywords = explode(",", $profile["pub_keywords"]);
529
530                                 foreach ($keywords AS $keyword)
531                                         xml_add_element($doc, $author, "poco:tags", trim($keyword));
532
533                         }
534
535                         /// @todo When we are having the XMPP address in the profile we should propagate it here
536                         $xmpp = "";
537                         if (trim($xmpp) != "") {
538                                 $ims = $doc->createElement("poco:ims");
539                                 xml_add_element($doc, $ims, "poco:type", "xmpp");
540                                 xml_add_element($doc, $ims, "poco:value", $xmpp);
541                                 xml_add_element($doc, $ims, "poco:primary", "true");
542                                 $author->appendChild($ims);
543                         }
544
545                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
546                                 $element = $doc->createElement("poco:address");
547
548                                 xml_add_element($doc, $element, "poco:formatted", formatted_location($profile));
549
550                                 if (trim($profile["locality"]) != "")
551                                         xml_add_element($doc, $element, "poco:locality", $profile["locality"]);
552
553                                 if (trim($profile["region"]) != "")
554                                         xml_add_element($doc, $element, "poco:region", $profile["region"]);
555
556                                 if (trim($profile["country-name"]) != "")
557                                         xml_add_element($doc, $element, "poco:country", $profile["country-name"]);
558
559                                 $author->appendChild($element);
560                         }
561                 }
562
563                 return $author;
564         }
565
566         /**
567          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
568          *
569          * @param object $doc XML document
570          * @param string $element Element name for the author
571          * @param string $contact_url Link of the contact
572          * @param array $items Item elements
573          *
574          * @return object XML author object
575          */
576         private function add_entry_author($doc, $element, $contact_url, $item) {
577
578                 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
579
580                 $author = $doc->createElement($element);
581                 xml_add_element($doc, $author, "name", $contact["name"]);
582                 xml_add_element($doc, $author, "uri", $contact["url"]);
583                 xml_add_element($doc, $author, "dfrn:handle", $contact["addr"]);
584
585                 /// @Todo
586                 /// - Check real image type and image size
587                 /// - Check which of these boths elements we should use
588                 $attributes = array(
589                                 "rel" => "photo",
590                                 "type" => "image/jpeg",
591                                 "media:width" => 80,
592                                 "media:height" => 80,
593                                 "href" => $contact["photo"]);
594                 xml_add_element($doc, $author, "link", "", $attributes);
595
596                 $attributes = array(
597                                 "rel" => "avatar",
598                                 "type" => "image/jpeg",
599                                 "media:width" => 80,
600                                 "media:height" => 80,
601                                 "href" => $contact["photo"]);
602                 xml_add_element($doc, $author, "link", "", $attributes);
603
604                 return $author;
605         }
606
607         /**
608          * @brief Adds the activity elements
609          *
610          * @param object $doc XML document
611          * @param string $element Element name for the activity
612          * @param string $activity activity value
613          *
614          * @return object XML activity object
615          */
616         private function create_activity($doc, $element, $activity) {
617
618                 if($activity) {
619                         $entry = $doc->createElement($element);
620
621                         $r = parse_xml_string($activity, false);
622                         if(!$r)
623                                 return false;
624                         if($r->type)
625                                 xml_add_element($doc, $entry, "activity:object-type", $r->type);
626                         if($r->id)
627                                 xml_add_element($doc, $entry, "id", $r->id);
628                         if($r->title)
629                                 xml_add_element($doc, $entry, "title", $r->title);
630                         if($r->link) {
631                                 if(substr($r->link,0,1) === '<') {
632                                         if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
633                                                 $r->link = str_replace('&','&amp;', $r->link);
634
635                                         $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
636
637                                         // XML does need a single element as root element so we add a dummy element here
638                                         $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
639                                         if (is_object($data)) {
640                                                 foreach ($data->link AS $link) {
641                                                         $attributes = array();
642                                                         foreach ($link->attributes() AS $parameter => $value)
643                                                                 $attributes[$parameter] = $value;
644                                                         xml_add_element($doc, $entry, "link", "", $attributes);
645                                                 }
646                                         }
647                                 } else {
648                                         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
649                                         xml_add_element($doc, $entry, "link", "", $attributes);
650                                 }
651                         }
652                         if($r->content)
653                                 xml_add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
654
655                         return $entry;
656                 }
657
658                 return false;
659         }
660
661         /**
662          * @brief Adds the elements for attachments
663          *
664          * @param object $doc XML document
665          * @param object $root XML root
666          * @param array $item Item element
667          *
668          * @return object XML attachment object
669          */
670         private function get_attachment($doc, $root, $item) {
671                 $arr = explode('[/attach],',$item['attach']);
672                 if(count($arr)) {
673                         foreach($arr as $r) {
674                                 $matches = false;
675                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
676                                 if($cnt) {
677                                         $attributes = array("rel" => "enclosure",
678                                                         "href" => $matches[1],
679                                                         "type" => $matches[3]);
680
681                                         if(intval($matches[2]))
682                                                 $attributes["length"] = intval($matches[2]);
683
684                                         if(trim($matches[4]) != "")
685                                                 $attributes["title"] = trim($matches[4]);
686
687                                         xml_add_element($doc, $root, "link", "", $attributes);
688                                 }
689                         }
690                 }
691         }
692
693         /**
694          * @brief Adds the "entry" elements for the DFRN protocol
695          *
696          * @param object $doc XML document
697          * @param string $type "text" or "html"
698          * @param array $item Item element
699          * @param array $owner Owner record
700          * @param bool $comment Trigger the sending of the "comment" element
701          * @param int $cid Contact ID of the recipient
702          *
703          * @return object XML entry object
704          */
705         private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
706
707                 $mentioned = array();
708
709                 if(!$item['parent'])
710                         return;
711
712                 if($item['deleted']) {
713                         $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
714                         return xml_create_element($doc, "at:deleted-entry", "", $attributes);
715                 }
716
717                 $entry = $doc->createElement("entry");
718
719                 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
720                         $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
721                 else
722                         $body = $item['body'];
723
724                 // Remove the abstract element. It is only locally important.
725                 $body = remove_abstract($body);
726
727                 if ($type == 'html') {
728                         $htmlbody = $body;
729
730                         if ($item['title'] != "")
731                                 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
732
733                         $htmlbody = bbcode($htmlbody, false, false, 7);
734                 }
735
736                 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
737                 $entry->appendChild($author);
738
739                 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
740                 $entry->appendChild($dfrnowner);
741
742                 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
743                         $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
744                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
745                         $attributes = array("ref" => $parent_item, "type" => "text/html",
746                                                 "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
747                                                 "dfrn:diaspora_guid" => $parent[0]['guid']);
748                         xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
749                 }
750
751                 xml_add_element($doc, $entry, "id", $item["uri"]);
752                 xml_add_element($doc, $entry, "title", $item["title"]);
753
754                 xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
755                 xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
756
757                 // "dfrn:env" is used to read the content
758                 xml_add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
759
760                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
761                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
762                 xml_add_element($doc, $entry, "content", (($type === 'html') ? $htmlbody : $body), array("type" => $type));
763
764                 // We save this value in "plink". Maybe we should read it from there as well?
765                 xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
766                                                                 "href" => app::get_baseurl()."/display/".$item["guid"]));
767
768                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
769                 // It is included in the rewritten code for completeness
770                 if ($comment)
771                         xml_add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
772
773                 if($item['location'])
774                         xml_add_element($doc, $entry, "dfrn:location", $item['location']);
775
776                 if($item['coord'])
777                         xml_add_element($doc, $entry, "georss:point", $item['coord']);
778
779                 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
780                         xml_add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
781
782                 if($item['extid'])
783                         xml_add_element($doc, $entry, "dfrn:extid", $item['extid']);
784
785                 if($item['bookmark'])
786                         xml_add_element($doc, $entry, "dfrn:bookmark", "true");
787
788                 if($item['app'])
789                         xml_add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
790
791                 xml_add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
792
793                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
794                 // It is needed for relayed comments to Diaspora.
795                 if($item['signed_text']) {
796                         $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
797                         xml_add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
798                 }
799
800                 xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
801
802                 if ($item['object-type'] != "")
803                         xml_add_element($doc, $entry, "activity:object-type", $item['object-type']);
804                 elseif ($item['id'] == $item['parent'])
805                         xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
806                 else
807                         xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
808
809                 $actobj = self::create_activity($doc, "activity:object", $item['object']);
810                 if ($actobj)
811                         $entry->appendChild($actobj);
812
813                 $actarg = self::create_activity($doc, "activity:target", $item['target']);
814                 if ($actarg)
815                         $entry->appendChild($actarg);
816
817                 $tags = item_getfeedtags($item);
818
819                 if(count($tags)) {
820                         foreach($tags as $t)
821                                 if (($type != 'html') OR ($t[0] != "@"))
822                                         xml_add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
823                 }
824
825                 if(count($tags))
826                         foreach($tags as $t)
827                                 if ($t[0] == "@")
828                                         $mentioned[$t[1]] = $t[1];
829
830                 foreach ($mentioned AS $mention) {
831                         $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
832                                 intval($owner["uid"]),
833                                 dbesc(normalise_link($mention)));
834                         if ($r[0]["forum"] OR $r[0]["prv"])
835                                 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
836                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
837                                                                                         "href" => $mention));
838                         else
839                                 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
840                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
841                                                                                         "href" => $mention));
842                 }
843
844                 self::get_attachment($doc, $entry, $item);
845
846                 return $entry;
847         }
848
849         /**
850          * @brief Delivers the atom content to the contacts
851          *
852          * @param array $owner Owner record
853          * @param array $contactr Contact record of the receiver
854          * @param string $atom Content that will be transmitted
855          * @param bool $dissolve (to be documented)
856          *
857          * @return int Deliver status. -1 means an error.
858          */
859         public static function deliver($owner,$contact,$atom, $dissolve = false) {
860
861                 $a = get_app();
862
863                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
864
865                 if($contact['duplex'] && $contact['dfrn-id'])
866                         $idtosend = '0:' . $orig_id;
867                 if($contact['duplex'] && $contact['issued-id'])
868                         $idtosend = '1:' . $orig_id;
869
870
871                 $rino = get_config('system','rino_encrypt');
872                 $rino = intval($rino);
873                 // use RINO1 if mcrypt isn't installed and RINO2 was selected
874                 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
875
876                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
877
878                 $ssl_val = intval(get_config('system','ssl_policy'));
879                 $ssl_policy = '';
880
881                 switch($ssl_val){
882                         case SSL_POLICY_FULL:
883                                 $ssl_policy = 'full';
884                                 break;
885                         case SSL_POLICY_SELFSIGN:
886                                 $ssl_policy = 'self';
887                                 break;
888                         case SSL_POLICY_NONE:
889                         default:
890                                 $ssl_policy = 'none';
891                                 break;
892                 }
893
894                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
895
896                 logger('dfrn_deliver: ' . $url);
897
898                 $xml = fetch_url($url);
899
900                 $curl_stat = $a->get_curl_code();
901                 if(! $curl_stat)
902                         return(-1); // timed out
903
904                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
905
906                 if(! $xml)
907                         return 3;
908
909                 if(strpos($xml,'<?xml') === false) {
910                         logger('dfrn_deliver: no valid XML returned');
911                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
912                         return 3;
913                 }
914
915                 $res = parse_xml_string($xml);
916
917                 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
918                         return (($res->status) ? $res->status : 3);
919
920                 $postvars     = array();
921                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
922                 $challenge    = hex2bin((string) $res->challenge);
923                 $perm         = (($res->perm) ? $res->perm : null);
924                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
925                 $rino_remote_version = intval($res->rino);
926                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
927
928                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
929
930                 if($owner['page-flags'] == PAGE_PRVGROUP)
931                         $page = 2;
932
933                 $final_dfrn_id = '';
934
935                 if($perm) {
936                         if((($perm == 'rw') && (! intval($contact['writable'])))
937                                 || (($perm == 'r') && (intval($contact['writable'])))) {
938                                 q("update contact set writable = %d where id = %d",
939                                         intval(($perm == 'rw') ? 1 : 0),
940                                         intval($contact['id'])
941                                 );
942                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
943                         }
944                 }
945
946                 if(($contact['duplex'] && strlen($contact['pubkey']))
947                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
948                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
949                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
950                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
951                 } else {
952                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
953                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
954                 }
955
956                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
957
958                 if(strpos($final_dfrn_id,':') == 1)
959                         $final_dfrn_id = substr($final_dfrn_id,2);
960
961                 if($final_dfrn_id != $orig_id) {
962                         logger('dfrn_deliver: wrong dfrn_id.');
963                         // did not decode properly - cannot trust this site
964                         return 3;
965                 }
966
967                 $postvars['dfrn_id']      = $idtosend;
968                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
969                 if($dissolve)
970                         $postvars['dissolve'] = '1';
971
972
973                 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
974                         $postvars['data'] = $atom;
975                         $postvars['perm'] = 'rw';
976                 } else {
977                         $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
978                         $postvars['perm'] = 'r';
979                 }
980
981                 $postvars['ssl_policy'] = $ssl_policy;
982
983                 if($page)
984                         $postvars['page'] = $page;
985
986
987                 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
988                         logger('rino version: '. $rino_remote_version);
989
990                         switch($rino_remote_version) {
991                                 case 1:
992                                         // Deprecated rino version!
993                                         $key = substr(random_string(),0,16);
994                                         $data = aes_encrypt($postvars['data'],$key);
995                                         break;
996                                 case 2:
997                                         // RINO 2 based on php-encryption
998                                         try {
999                                                 $key = Crypto::createNewRandomKey();
1000                                         } catch (CryptoTestFailed $ex) {
1001                                                 logger('Cannot safely create a key');
1002                                                 return -1;
1003                                         } catch (CannotPerformOperation $ex) {
1004                                                 logger('Cannot safely create a key');
1005                                                 return -1;
1006                                         }
1007                                         try {
1008                                                 $data = Crypto::encrypt($postvars['data'], $key);
1009                                         } catch (CryptoTestFailed $ex) {
1010                                                 logger('Cannot safely perform encryption');
1011                                                 return -1;
1012                                         } catch (CannotPerformOperation $ex) {
1013                                                 logger('Cannot safely perform encryption');
1014                                                 return -1;
1015                                         }
1016                                         break;
1017                                 default:
1018                                         logger("rino: invalid requested verision '$rino_remote_version'");
1019                                         return -1;
1020                         }
1021
1022                         $postvars['rino'] = $rino_remote_version;
1023                         $postvars['data'] = bin2hex($data);
1024
1025                         #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1026
1027
1028                         if($dfrn_version >= 2.1) {
1029                                 if(($contact['duplex'] && strlen($contact['pubkey']))
1030                                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1031                                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
1032
1033                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1034                                 else
1035                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1036
1037                         } else {
1038                                 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
1039                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1040                                 else
1041                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1042
1043                         }
1044
1045                         logger('md5 rawkey ' . md5($postvars['key']));
1046
1047                         $postvars['key'] = bin2hex($postvars['key']);
1048                 }
1049
1050
1051                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1052
1053                 $xml = post_url($contact['notify'],$postvars);
1054
1055                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1056
1057                 $curl_stat = $a->get_curl_code();
1058                 if((! $curl_stat) || (! strlen($xml)))
1059                         return(-1); // timed out
1060
1061                 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1062                         return(-1);
1063
1064                 if(strpos($xml,'<?xml') === false) {
1065                         logger('dfrn_deliver: phase 2: no valid XML returned');
1066                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1067                         return 3;
1068                 }
1069
1070                 if($contact['term-date'] != '0000-00-00 00:00:00') {
1071                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1072                         require_once('include/Contact.php');
1073                         unmark_for_death($contact);
1074                 }
1075
1076                 $res = parse_xml_string($xml);
1077
1078                 return $res->status;
1079         }
1080
1081         /**
1082          * @brief Add new birthday event for this person
1083          *
1084          * @param array $contact Contact record
1085          * @param string $birthday Birthday of the contact
1086          *
1087          */
1088         private function birthday_event($contact, $birthday) {
1089
1090                 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1091
1092                 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1093                 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1094
1095
1096                 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1097                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1098                         intval($contact["uid"]),
1099                         intval($contact["id"]),
1100                         dbesc(datetime_convert()),
1101                         dbesc(datetime_convert()),
1102                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1103                         dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1104                         dbesc($bdtext),
1105                         dbesc($bdtext2),
1106                         dbesc("birthday")
1107                 );
1108         }
1109
1110         /**
1111          * @brief Fetch the author data from head or entry items
1112          *
1113          * @param object $xpath XPath object
1114          * @param object $context In which context should the data be searched
1115          * @param array $importer Record of the importer user mixed with contact of the content
1116          * @param string $element Element name from which the data is fetched
1117          * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1118          *
1119          * @return Returns an array with relevant data of the author
1120          */
1121         private function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1122
1123                 $author = array();
1124                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1125                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1126
1127                 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1128                                 `name`, `nick`, `about`, `location`, `keywords`, `bdyear`, `bd`
1129                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1130                         intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1131                 if ($r) {
1132                         $contact = $r[0];
1133                         $author["contact-id"] = $r[0]["id"];
1134                         $author["network"] = $r[0]["network"];
1135                 } else {
1136                         if (!$onlyfetch)
1137                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1138
1139                         $author["contact-id"] = $importer["id"];
1140                         $author["network"] = $importer["network"];
1141                         $onlyfetch = true;
1142                 }
1143
1144                 // Until now we aren't serving different sizes - but maybe later
1145                 $avatarlist = array();
1146                 // @todo check if "avatar" or "photo" would be the best field in the specification
1147                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1148                 foreach($avatars AS $avatar) {
1149                         $href = "";
1150                         $width = 0;
1151                         foreach($avatar->attributes AS $attributes) {
1152                                 if ($attributes->name == "href")
1153                                         $href = $attributes->textContent;
1154                                 if ($attributes->name == "width")
1155                                         $width = $attributes->textContent;
1156                                 if ($attributes->name == "updated")
1157                                         $contact["avatar-date"] = $attributes->textContent;
1158                         }
1159                         if (($width > 0) AND ($href != ""))
1160                                 $avatarlist[$width] = $href;
1161                 }
1162                 if (count($avatarlist) > 0) {
1163                         krsort($avatarlist);
1164                         $author["avatar"] = current($avatarlist);
1165                 }
1166
1167                 if ($r AND !$onlyfetch) {
1168                         logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
1169
1170                         $poco = array("url" => $contact["url"]);
1171
1172                         // When was the last change to name or uri?
1173                         $name_element = $xpath->query($element."/atom:name", $context)->item(0);
1174                         foreach($name_element->attributes AS $attributes)
1175                                 if ($attributes->name == "updated")
1176                                         $poco["name-date"] = $attributes->textContent;
1177
1178                         $link_element = $xpath->query($element."/atom:link", $context)->item(0);
1179                         foreach($link_element->attributes AS $attributes)
1180                                 if ($attributes->name == "updated")
1181                                         $poco["uri-date"] = $attributes->textContent;
1182
1183                         // Update contact data
1184                         $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
1185                         if ($value != "")
1186                                 $poco["addr"] = $value;
1187
1188                         $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
1189                         if ($value != "")
1190                                 $poco["name"] = $value;
1191
1192                         $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1193                         if ($value != "")
1194                                 $poco["nick"] = $value;
1195
1196                         $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
1197                         if ($value != "")
1198                                 $poco["about"] = $value;
1199
1200                         $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1201                         if ($value != "")
1202                                 $poco["location"] = $value;
1203
1204                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1205                         /// - poco:utcOffset
1206                         /// - poco:ims
1207                         /// - poco:urls
1208                         /// - poco:locality
1209                         /// - poco:region
1210                         /// - poco:country
1211
1212                         // Save the keywords into the contact table
1213                         $tags = array();
1214                         $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
1215                         foreach($tagelements AS $tag)
1216                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1217
1218                         if (count($tags))
1219                                 $poco["keywords"] = implode(", ", $tags);
1220
1221                         // "dfrn:birthday" contains the birthday converted to UTC
1222                         $old_bdyear = $contact["bdyear"];
1223
1224                         $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1225
1226                         if (strtotime($birthday) > time()) {
1227                                 $bd_timestamp = strtotime($birthday);
1228
1229                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1230                         }
1231
1232                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1233                         $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
1234
1235                         if (!in_array($value, array("", "0000-00-00"))) {
1236                                 $bdyear = date("Y");
1237                                 $value = str_replace("0000", $bdyear, $value);
1238
1239                                 if (strtotime($value) < time()) {
1240                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1241                                         $bdyear = $bdyear + 1;
1242                                 }
1243
1244                                 $poco["bd"] = $value;
1245                         }
1246
1247                         $contact = array_merge($contact, $poco);
1248
1249                         if ($old_bdyear != $contact["bdyear"])
1250                                 self::birthday_event($contact, $birthday);
1251
1252                         // Get all field names
1253                         $fields = array();
1254                         foreach ($r[0] AS $field => $data)
1255                                 $fields[$field] = $data;
1256
1257                         unset($fields["id"]);
1258                         unset($fields["uid"]);
1259                         unset($fields["url"]);
1260                         unset($fields["avatar-date"]);
1261                         unset($fields["name-date"]);
1262                         unset($fields["uri-date"]);
1263
1264                          // Update check for this field has to be done differently
1265                         $datefields = array("name-date", "uri-date");
1266                         foreach ($datefields AS $field)
1267                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1268                                         logger("Difference for contact ".$contact["id"]." in field '".$field."'. Old value: '".$contact[$field]."', new value '".$r[0][$field]."'", LOGGER_DEBUG);
1269                                         $update = true;
1270                                 }
1271
1272                         foreach ($fields AS $field => $data)
1273                                 if ($contact[$field] != $r[0][$field]) {
1274                                         logger("Difference for contact ".$contact["id"]." in field '".$field."'. Old value: '".$contact[$field]."', new value '".$r[0][$field]."'", LOGGER_DEBUG);
1275                                         $update = true;
1276                                 }
1277
1278                         if ($update) {
1279                                 logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
1280
1281                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1282                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s',
1283                                         `name-date`  = '%s', `uri-date` = '%s'
1284                                         WHERE `id` = %d AND `network` = '%s'",
1285                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1286                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1287                                         dbesc($contact["bd"]), dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
1288                                         intval($contact["id"]), dbesc($contact["network"]));
1289                         }
1290
1291                         update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1292                                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1293
1294                         // The generation is a sign for the reliability of the provided data.
1295                         // It is used in the socgraph.php to prevent that old contact data
1296                         // that was relayed over several servers can overwrite contact
1297                         // data that we received directly.
1298
1299                         $poco["generation"] = 2;
1300                         $poco["photo"] = $author["avatar"];
1301                         update_gcontact($poco);
1302                 }
1303
1304                 return($author);
1305         }
1306
1307         /**
1308          * @brief Transforms activity objects into an XML string
1309          *
1310          * @param object $xpath XPath object
1311          * @param object $activity Activity object
1312          * @param text $element element name
1313          *
1314          * @return string XML string
1315          */
1316         private function transform_activity($xpath, $activity, $element) {
1317                 if (!is_object($activity))
1318                         return "";
1319
1320                 $obj_doc = new DOMDocument("1.0", "utf-8");
1321                 $obj_doc->formatOutput = true;
1322
1323                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1324
1325                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1326                 xml_add_element($obj_doc, $obj_element, "type", $activity_type);
1327
1328                 $id = $xpath->query("atom:id", $activity)->item(0);
1329                 if (is_object($id))
1330                         $obj_element->appendChild($obj_doc->importNode($id, true));
1331
1332                 $title = $xpath->query("atom:title", $activity)->item(0);
1333                 if (is_object($title))
1334                         $obj_element->appendChild($obj_doc->importNode($title, true));
1335
1336                 $links = $xpath->query("atom:link", $activity);
1337                 if (is_object($links))
1338                         foreach ($links AS $link)
1339                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1340
1341                 $content = $xpath->query("atom:content", $activity)->item(0);
1342                 if (is_object($content))
1343                         $obj_element->appendChild($obj_doc->importNode($content, true));
1344
1345                 $obj_doc->appendChild($obj_element);
1346
1347                 $objxml = $obj_doc->saveXML($obj_element);
1348
1349                 // @todo This isn't totally clean. We should find a way to transform the namespaces
1350                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1351                 return($objxml);
1352         }
1353
1354         /**
1355          * @brief Processes the mail elements
1356          *
1357          * @param object $xpath XPath object
1358          * @param object $mail mail elements
1359          * @param array $importer Record of the importer user mixed with contact of the content
1360          */
1361         private function process_mail($xpath, $mail, $importer) {
1362
1363                 logger("Processing mails");
1364
1365                 $msg = array();
1366                 $msg["uid"] = $importer["importer_uid"];
1367                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1368                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1369                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1370                 $msg["contact-id"] = $importer["id"];
1371                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1372                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1373                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1374                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1375                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1376                 $msg["seen"] = 0;
1377                 $msg["replied"] = 0;
1378
1379                 dbesc_array($msg);
1380
1381                 $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES ('".implode("', '", array_values($msg))."')");
1382
1383                 // send notifications.
1384
1385                 $notif_params = array(
1386                         "type" => NOTIFY_MAIL,
1387                         "notify_flags" => $importer["notify-flags"],
1388                         "language" => $importer["language"],
1389                         "to_name" => $importer["username"],
1390                         "to_email" => $importer["email"],
1391                         "uid" => $importer["importer_uid"],
1392                         "item" => $msg,
1393                         "source_name" => $msg["from-name"],
1394                         "source_link" => $importer["url"],
1395                         "source_photo" => $importer["thumb"],
1396                         "verb" => ACTIVITY_POST,
1397                         "otype" => "mail"
1398                 );
1399
1400                 notification($notif_params);
1401
1402                 logger("Mail is processed, notification was sent.");
1403         }
1404
1405         /**
1406          * @brief Processes the suggestion elements
1407          *
1408          * @param object $xpath XPath object
1409          * @param object $suggestion suggestion elements
1410          * @param array $importer Record of the importer user mixed with contact of the content
1411          */
1412         private function process_suggestion($xpath, $suggestion, $importer) {
1413
1414                 logger("Processing suggestions");
1415
1416                 $suggest = array();
1417                 $suggest["uid"] = $importer["importer_uid"];
1418                 $suggest["cid"] = $importer["id"];
1419                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1420                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1421                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1422                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1423                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1424
1425                 // Does our member already have a friend matching this description?
1426
1427                 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1428                         dbesc($suggest["name"]),
1429                         dbesc(normalise_link($suggest["url"])),
1430                         intval($suggest["uid"])
1431                 );
1432                 if(count($r))
1433                         return false;
1434
1435                 // Do we already have an fcontact record for this person?
1436
1437                 $fid = 0;
1438                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1439                         dbesc($suggest["url"]),
1440                         dbesc($suggest["name"]),
1441                         dbesc($suggest["request"])
1442                 );
1443                 if(count($r)) {
1444                         $fid = $r[0]["id"];
1445
1446                         // OK, we do. Do we already have an introduction for this person ?
1447                         $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1448                                 intval($suggest["uid"]),
1449                                 intval($fid)
1450                         );
1451                         if(count($r))
1452                                 return false;
1453                 }
1454                 if(!$fid)
1455                         $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1456                         dbesc($suggest["name"]),
1457                         dbesc($suggest["url"]),
1458                         dbesc($suggest["photo"]),
1459                         dbesc($suggest["request"])
1460                 );
1461                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1462                         dbesc($suggest["url"]),
1463                         dbesc($suggest["name"]),
1464                         dbesc($suggest["request"])
1465                 );
1466                 if(count($r))
1467                         $fid = $r[0]["id"];
1468                 else
1469                         // database record did not get created. Quietly give up.
1470                         return false;
1471
1472
1473                 $hash = random_string();
1474
1475                 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1476                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1477                         intval($suggest["uid"]),
1478                         intval($fid),
1479                         intval($suggest["cid"]),
1480                         dbesc($suggest["body"]),
1481                         dbesc($hash),
1482                         dbesc(datetime_convert()),
1483                         intval(0)
1484                 );
1485
1486                 notification(array(
1487                         "type"         => NOTIFY_SUGGEST,
1488                         "notify_flags" => $importer["notify-flags"],
1489                         "language"     => $importer["language"],
1490                         "to_name"      => $importer["username"],
1491                         "to_email"     => $importer["email"],
1492                         "uid"          => $importer["importer_uid"],
1493                         "item"         => $suggest,
1494                         "link"         => App::get_baseurl()."/notifications/intros",
1495                         "source_name"  => $importer["name"],
1496                         "source_link"  => $importer["url"],
1497                         "source_photo" => $importer["photo"],
1498                         "verb"         => ACTIVITY_REQ_FRIEND,
1499                         "otype"        => "intro"
1500                 ));
1501
1502                 return true;
1503
1504         }
1505
1506         /**
1507          * @brief Processes the relocation elements
1508          *
1509          * @param object $xpath XPath object
1510          * @param object $relocation relocation elements
1511          * @param array $importer Record of the importer user mixed with contact of the content
1512          */
1513         private function process_relocation($xpath, $relocation, $importer) {
1514
1515                 logger("Processing relocations");
1516
1517                 $relocate = array();
1518                 $relocate["uid"] = $importer["importer_uid"];
1519                 $relocate["cid"] = $importer["id"];
1520                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1521                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1522                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1523                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1524                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1525                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1526                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1527                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1528                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1529                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1530
1531                 // update contact
1532                 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1533                         intval($importer["id"]),
1534                         intval($importer["importer_uid"]));
1535                 if (!$r)
1536                         return false;
1537
1538                 $old = $r[0];
1539
1540                 $x = q("UPDATE `contact` SET
1541                                         `name` = '%s',
1542                                         `photo` = '%s',
1543                                         `thumb` = '%s',
1544                                         `micro` = '%s',
1545                                         `url` = '%s',
1546                                         `nurl` = '%s',
1547                                         `request` = '%s',
1548                                         `confirm` = '%s',
1549                                         `notify` = '%s',
1550                                         `poll` = '%s',
1551                                         `site-pubkey` = '%s'
1552                         WHERE `id` = %d AND `uid` = %d;",
1553                                         dbesc($relocate["name"]),
1554                                         dbesc($relocate["photo"]),
1555                                         dbesc($relocate["thumb"]),
1556                                         dbesc($relocate["micro"]),
1557                                         dbesc($relocate["url"]),
1558                                         dbesc(normalise_link($relocate["url"])),
1559                                         dbesc($relocate["request"]),
1560                                         dbesc($relocate["confirm"]),
1561                                         dbesc($relocate["notify"]),
1562                                         dbesc($relocate["poll"]),
1563                                         dbesc($relocate["sitepubkey"]),
1564                                         intval($importer["id"]),
1565                                         intval($importer["importer_uid"]));
1566
1567                 if ($x === false)
1568                         return false;
1569
1570                 // update items
1571                 $fields = array(
1572                         'owner-link' => array($old["url"], $relocate["url"]),
1573                         'author-link' => array($old["url"], $relocate["url"]),
1574                         'owner-avatar' => array($old["photo"], $relocate["photo"]),
1575                         'author-avatar' => array($old["photo"], $relocate["photo"]),
1576                         );
1577                 foreach ($fields as $n=>$f){
1578                         $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1579                                         $n, dbesc($f[1]),
1580                                         $n, dbesc($f[0]),
1581                                         intval($importer["importer_uid"]));
1582                                 if ($x === false)
1583                                         return false;
1584                         }
1585
1586                 /// @TODO
1587                 /// merge with current record, current contents have priority
1588                 /// update record, set url-updated
1589                 /// update profile photos
1590                 /// schedule a scan?
1591                 return true;
1592         }
1593
1594         /**
1595          * @brief Updates an item
1596          *
1597          * @param array $current the current item record
1598          * @param array $item the new item record
1599          * @param array $importer Record of the importer user mixed with contact of the content
1600          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1601          */
1602         private function update_content($current, $item, $importer, $entrytype) {
1603                 $changed = false;
1604
1605                 if (edited_timestamp_is_newer($current, $item)) {
1606
1607                         // do not accept (ignore) an earlier edit than one we currently have.
1608                         if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
1609                                 return(false);
1610
1611                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1612                                 dbesc($item["title"]),
1613                                 dbesc($item["body"]),
1614                                 dbesc($item["tag"]),
1615                                 dbesc(datetime_convert("UTC","UTC",$item["edited"])),
1616                                 dbesc(datetime_convert()),
1617                                 dbesc($item["uri"]),
1618                                 intval($importer["importer_uid"])
1619                         );
1620                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
1621                         update_thread_uri($item["uri"], $importer["importer_uid"]);
1622
1623                         $changed = true;
1624
1625                         if ($entrytype == DFRN_REPLY_RC)
1626                                 proc_run("php", "include/notifier.php","comment-import", $current["id"]);
1627                 }
1628
1629                 // update last-child if it changes
1630                 if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
1631                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1632                                 dbesc(datetime_convert()),
1633                                 dbesc($item["parent-uri"]),
1634                                 intval($importer["importer_uid"])
1635                         );
1636                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
1637                                 intval($item["last-child"]),
1638                                 dbesc(datetime_convert()),
1639                                 dbesc($item["uri"]),
1640                                 intval($importer["importer_uid"])
1641                         );
1642                 }
1643                 return $changed;
1644         }
1645
1646         /**
1647          * @brief Detects the entry type of the item
1648          *
1649          * @param array $importer Record of the importer user mixed with contact of the content
1650          * @param array $item the new item record
1651          *
1652          * @return int Is it a toplevel entry, a comment or a relayed comment?
1653          */
1654         private function get_entry_type($importer, $item) {
1655                 if ($item["parent-uri"] != $item["uri"]) {
1656                         $community = false;
1657
1658                         if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
1659                                 $sql_extra = "";
1660                                 $community = true;
1661                                 logger("possible community action");
1662                         } else
1663                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
1664
1665                         // was the top-level post for this action written by somebody on this site?
1666                         // Specifically, the recipient?
1667
1668                         $is_a_remote_action = false;
1669
1670                         $r = q("SELECT `item`.`parent-uri` FROM `item`
1671                                 WHERE `item`.`uri` = '%s'
1672                                 LIMIT 1",
1673                                 dbesc($item["parent-uri"])
1674                         );
1675                         if($r && count($r)) {
1676                                 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
1677                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1678                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
1679                                         AND `item`.`uid` = %d
1680                                         $sql_extra
1681                                         LIMIT 1",
1682                                         dbesc($r[0]["parent-uri"]),
1683                                         dbesc($r[0]["parent-uri"]),
1684                                         dbesc($r[0]["parent-uri"]),
1685                                         intval($importer["importer_uid"])
1686                                 );
1687                                 if($r && count($r))
1688                                         $is_a_remote_action = true;
1689                         }
1690
1691                         // Does this have the characteristics of a community or private group action?
1692                         // If it's an action to a wall post on a community/prvgroup page it's a
1693                         // valid community action. Also forum_mode makes it valid for sure.
1694                         // If neither, it's not.
1695
1696                         if($is_a_remote_action && $community) {
1697                                 if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
1698                                         $is_a_remote_action = false;
1699                                         logger("not a community action");
1700                                 }
1701                         }
1702
1703                         if ($is_a_remote_action)
1704                                 return DFRN_REPLY_RC;
1705                         else
1706                                 return DFRN_REPLY;
1707
1708                 } else
1709                         return DFRN_TOP_LEVEL;
1710
1711         }
1712
1713         /**
1714          * @brief Send a "poke"
1715          *
1716          * @param array $item the new item record
1717          * @param array $importer Record of the importer user mixed with contact of the content
1718          * @param int $posted_id The record number of item record that was just posted
1719          */
1720         private function do_poke($item, $importer, $posted_id) {
1721                 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
1722                 if(!$verb)
1723                         return;
1724                 $xo = parse_xml_string($item["object"],false);
1725
1726                 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
1727
1728                         // somebody was poked/prodded. Was it me?
1729                         foreach($xo->link as $l) {
1730                                 $atts = $l->attributes();
1731                                 switch($atts["rel"]) {
1732                                         case "alternate":
1733                                                 $Blink = $atts["href"];
1734                                                 break;
1735                                         default:
1736                                                 break;
1737                                 }
1738                         }
1739
1740                         if($Blink && link_compare($Blink,App::get_baseurl()."/profile/".$importer["nickname"])) {
1741
1742                                 // send a notification
1743                                 notification(array(
1744                                         "type"         => NOTIFY_POKE,
1745                                         "notify_flags" => $importer["notify-flags"],
1746                                         "language"     => $importer["language"],
1747                                         "to_name"      => $importer["username"],
1748                                         "to_email"     => $importer["email"],
1749                                         "uid"          => $importer["importer_uid"],
1750                                         "item"         => $item,
1751                                         "link"         => App::get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
1752                                         "source_name"  => stripslashes($item["author-name"]),
1753                                         "source_link"  => $item["author-link"],
1754                                         "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
1755                                                 ? $importer["thumb"] : $item["author-avatar"]),
1756                                         "verb"         => $item["verb"],
1757                                         "otype"        => "person",
1758                                         "activity"     => $verb,
1759                                         "parent"       => $item["parent"]
1760                                 ));
1761                         }
1762                 }
1763         }
1764
1765         /**
1766          * @brief Processes several actions, depending on the verb
1767          *
1768          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1769          * @param array $importer Record of the importer user mixed with contact of the content
1770          * @param array $item the new item record
1771          * @param bool $is_like Is the verb a "like"?
1772          *
1773          * @return bool Should the processing of the entries be continued?
1774          */
1775         private function process_verbs($entrytype, $importer, &$item, &$is_like) {
1776                 if (($entrytype == DFRN_TOP_LEVEL)) {
1777                         // The filling of the the "contact" variable is done for legcy reasons
1778                         // The functions below are partly used by ostatus.php as well - where we have this variable
1779                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
1780                         $contact = $r[0];
1781                         $nickname = $contact["nick"];
1782
1783                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
1784                         // This function once was responsible for DFRN and OStatus.
1785                         if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
1786                                 logger("New follower");
1787                                 new_follower($importer, $contact, $item, $nickname);
1788                                 return false;
1789                         }
1790                         if(activity_match($item["verb"],ACTIVITY_UNFOLLOW))  {
1791                                 logger("Lost follower");
1792                                 lose_follower($importer, $contact, $item);
1793                                 return false;
1794                         }
1795                         if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
1796                                 logger("New friend request");
1797                                 new_follower($importer, $contact, $item, $nickname, true);
1798                                 return false;
1799                         }
1800                         if(activity_match($item["verb"],ACTIVITY_UNFRIEND))  {
1801                                 logger("Lost sharer");
1802                                 lose_sharer($importer, $contact, $item);
1803                                 return false;
1804                         }
1805                 } else {
1806                         if(($item["verb"] === ACTIVITY_LIKE)
1807                                 || ($item["verb"] === ACTIVITY_DISLIKE)
1808                                 || ($item["verb"] === ACTIVITY_ATTEND)
1809                                 || ($item["verb"] === ACTIVITY_ATTENDNO)
1810                                 || ($item["verb"] === ACTIVITY_ATTENDMAYBE)) {
1811                                 $is_like = true;
1812                                 $item["type"] = "activity";
1813                                 $item["gravity"] = GRAVITY_LIKE;
1814                                 // only one like or dislike per person
1815                                 // splitted into two queries for performance issues
1816                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
1817                                         intval($item["uid"]),
1818                                         dbesc($item["author-link"]),
1819                                         dbesc($item["verb"]),
1820                                         dbesc($item["parent-uri"])
1821                                 );
1822                                 if($r && count($r))
1823                                         return false;
1824
1825                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
1826                                         intval($item["uid"]),
1827                                         dbesc($item["author-link"]),
1828                                         dbesc($item["verb"]),
1829                                         dbesc($item["parent-uri"])
1830                                 );
1831                                 if($r && count($r))
1832                                         return false;
1833                         } else
1834                                 $is_like = false;
1835
1836                         if(($item["verb"] === ACTIVITY_TAG) && ($item["object-type"] === ACTIVITY_OBJ_TAGTERM)) {
1837
1838                                 $xo = parse_xml_string($item["object"],false);
1839                                 $xt = parse_xml_string($item["target"],false);
1840
1841                                 if($xt->type == ACTIVITY_OBJ_NOTE) {
1842                                         $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1843                                                 dbesc($xt->id),
1844                                                 intval($importer["importer_uid"])
1845                                         );
1846
1847                                         if(!count($r))
1848                                                 return false;
1849
1850                                         // extract tag, if not duplicate, add to parent item
1851                                         if($xo->content) {
1852                                                 if(!(stristr($r[0]["tag"],trim($xo->content)))) {
1853                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
1854                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
1855                                                                 intval($r[0]["id"])
1856                                                         );
1857                                                         create_tags_from_item($r[0]["id"]);
1858                                                 }
1859                                         }
1860                                 }
1861                         }
1862                 }
1863                 return true;
1864         }
1865
1866         /**
1867          * @brief Processes the link elements
1868          *
1869          * @param object $links link elements
1870          * @param array $item the item record
1871          */
1872         private function parse_links($links, &$item) {
1873                 $rel = "";
1874                 $href = "";
1875                 $type = "";
1876                 $length = "0";
1877                 $title = "";
1878                 foreach ($links AS $link) {
1879                         foreach($link->attributes AS $attributes) {
1880                                 if ($attributes->name == "href")
1881                                         $href = $attributes->textContent;
1882                                 if ($attributes->name == "rel")
1883                                         $rel = $attributes->textContent;
1884                                 if ($attributes->name == "type")
1885                                         $type = $attributes->textContent;
1886                                 if ($attributes->name == "length")
1887                                         $length = $attributes->textContent;
1888                                 if ($attributes->name == "title")
1889                                         $title = $attributes->textContent;
1890                         }
1891                         if (($rel != "") AND ($href != ""))
1892                                 switch($rel) {
1893                                         case "alternate":
1894                                                 $item["plink"] = $href;
1895                                                 break;
1896                                         case "enclosure":
1897                                                 $enclosure = $href;
1898                                                 if(strlen($item["attach"]))
1899                                                         $item["attach"] .= ",";
1900
1901                                                 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
1902                                                 break;
1903                                 }
1904                 }
1905         }
1906
1907         /**
1908          * @brief Processes the entry elements which contain the items and comments
1909          *
1910          * @param array $header Array of the header elements that always stay the same
1911          * @param object $xpath XPath object
1912          * @param object $entry entry elements
1913          * @param array $importer Record of the importer user mixed with contact of the content
1914          */
1915         private function process_entry($header, $xpath, $entry, $importer) {
1916
1917                 logger("Processing entries");
1918
1919                 $item = $header;
1920
1921                 // Get the uri
1922                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
1923
1924                 // Fetch the owner
1925                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
1926
1927                 $item["owner-name"] = $owner["name"];
1928                 $item["owner-link"] = $owner["link"];
1929                 $item["owner-avatar"] = $owner["avatar"];
1930
1931                 // fetch the author
1932                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
1933
1934                 $item["author-name"] = $author["name"];
1935                 $item["author-link"] = $author["link"];
1936                 $item["author-avatar"] = $author["avatar"];
1937
1938                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
1939
1940                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
1941                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
1942
1943                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
1944                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
1945                 // make sure nobody is trying to sneak some html tags by us
1946                 $item["body"] = notags(base64url_decode($item["body"]));
1947
1948                 $item["body"] = limit_body_size($item["body"]);
1949
1950                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
1951                 if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
1952
1953                         $item['body'] = reltoabs($item['body'],$base_url);
1954
1955                         $item['body'] = html2bb_video($item['body']);
1956
1957                         $item['body'] = oembed_html2bbcode($item['body']);
1958
1959                         $config = HTMLPurifier_Config::createDefault();
1960                         $config->set('Cache.DefinitionImpl', null);
1961
1962                         // we shouldn't need a whitelist, because the bbcode converter
1963                         // will strip out any unsupported tags.
1964
1965                         $purifier = new HTMLPurifier($config);
1966                         $item['body'] = $purifier->purify($item['body']);
1967
1968                         $item['body'] = @html2bbcode($item['body']);
1969                 }
1970
1971                 /// @todo We should check for a repeated post and if we know the repeated author.
1972
1973                 // We don't need the content element since "dfrn:env" is always present
1974                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
1975
1976                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
1977                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
1978
1979                 $georsspoint = $xpath->query("georss:point", $entry);
1980                 if ($georsspoint)
1981                         $item["coord"] = $georsspoint->item(0)->nodeValue;
1982
1983                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
1984
1985                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
1986
1987                 if ($xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue == "true")
1988                         $item["bookmark"] = true;
1989
1990                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
1991                 if ($notice_info AND ($notice_info->length > 0)) {
1992                         foreach($notice_info->item(0)->attributes AS $attributes) {
1993                                 if ($attributes->name == "source")
1994                                         $item["app"] = strip_tags($attributes->textContent);
1995                         }
1996                 }
1997
1998                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
1999
2000                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2001                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2002                 if ($dsprsig != "")
2003                         $item["dsprsig"] = $dsprsig;
2004
2005                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2006
2007                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
2008                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2009
2010                 $object = $xpath->query("activity:object", $entry)->item(0);
2011                 $item["object"] = self::transform_activity($xpath, $object, "object");
2012
2013                 if (trim($item["object"]) != "") {
2014                         $r = parse_xml_string($item["object"], false);
2015                         if (isset($r->type))
2016                                 $item["object-type"] = $r->type;
2017                 }
2018
2019                 $target = $xpath->query("activity:target", $entry)->item(0);
2020                 $item["target"] = self::transform_activity($xpath, $target, "target");
2021
2022                 $categories = $xpath->query("atom:category", $entry);
2023                 if ($categories) {
2024                         foreach ($categories AS $category) {
2025                                 $term = "";
2026                                 $scheme = "";
2027                                 foreach($category->attributes AS $attributes) {
2028                                         if ($attributes->name == "term")
2029                                                 $term = $attributes->textContent;
2030
2031                                         if ($attributes->name == "scheme")
2032                                                 $scheme = $attributes->textContent;
2033                                 }
2034
2035                                 if (($term != "") AND ($scheme != "")) {
2036                                         $parts = explode(":", $scheme);
2037                                         if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
2038                                                 $termhash = array_shift($parts);
2039                                                 $termurl = implode(":", $parts);
2040
2041                                                 if(strlen($item["tag"]))
2042                                                         $item["tag"] .= ",";
2043
2044                                                 $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
2045                                         }
2046                                 }
2047                         }
2048                 }
2049
2050                 $enclosure = "";
2051
2052                 $links = $xpath->query("atom:link", $entry);
2053                 if ($links)
2054                         self::parse_links($links, $item);
2055
2056                 // Is it a reply or a top level posting?
2057                 $item["parent-uri"] = $item["uri"];
2058
2059                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2060                 if (is_object($inreplyto->item(0)))
2061                         foreach($inreplyto->item(0)->attributes AS $attributes)
2062                                 if ($attributes->name == "ref")
2063                                         $item["parent-uri"] = $attributes->textContent;
2064
2065                 // Get the type of the item (Top level post, reply or remote reply)
2066                 $entrytype = self::get_entry_type($importer, $item);
2067
2068                 // Now assign the rest of the values that depend on the type of the message
2069                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2070                         if (!isset($item["object-type"]))
2071                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2072
2073                         if ($item["contact-id"] != $owner["contact-id"])
2074                                 $item["contact-id"] = $owner["contact-id"];
2075
2076                         if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
2077                                 $item["network"] = $owner["network"];
2078
2079                         if ($item["contact-id"] != $author["contact-id"])
2080                                 $item["contact-id"] = $author["contact-id"];
2081
2082                         if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
2083                                 $item["network"] = $author["network"];
2084
2085                         // This code was taken from the old DFRN code
2086                         // When activated, forums don't work.
2087                         // And: Why should we disallow commenting by followers?
2088                         // the behaviour is now similar to the Diaspora part.
2089                         //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
2090                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2091                         //      return;
2092                         //}
2093                 }
2094
2095                 if ($entrytype == DFRN_REPLY_RC) {
2096                         $item["type"] = "remote-comment";
2097                         $item["wall"] = 1;
2098                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2099                         if (!isset($item["object-type"]))
2100                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2101
2102                         // Is it an event?
2103                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2104                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2105                                 $ev = bbtoevent($item["body"]);
2106                                 if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2107                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2108                                         $ev["cid"] = $importer["id"];
2109                                         $ev["uid"] = $importer["uid"];
2110                                         $ev["uri"] = $item["uri"];
2111                                         $ev["edited"] = $item["edited"];
2112                                         $ev['private'] = $item['private'];
2113                                         $ev["guid"] = $item["guid"];
2114
2115                                         $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2116                                                 dbesc($item["uri"]),
2117                                                 intval($importer["uid"])
2118                                         );
2119                                         if(count($r))
2120                                                 $ev["id"] = $r[0]["id"];
2121
2122                                         $event_id = event_store($ev);
2123                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2124                                         return;
2125                                 }
2126                         }
2127                 }
2128
2129                 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2130                         dbesc($item["uri"]),
2131                         intval($importer["importer_uid"])
2132                 );
2133
2134                 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2135                         logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2136                         return;
2137                 }
2138
2139                 // Update content if 'updated' changes
2140                 if(count($r)) {
2141                         if (self::update_content($r[0], $item, $importer, $entrytype))
2142                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2143                         else
2144                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2145                         return;
2146                 }
2147
2148                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2149                         $posted_id = item_store($item);
2150                         $parent = 0;
2151
2152                         if($posted_id) {
2153
2154                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2155
2156                                 $item["id"] = $posted_id;
2157
2158                                 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2159                                         intval($posted_id),
2160                                         intval($importer["importer_uid"])
2161                                 );
2162                                 if(count($r)) {
2163                                         $parent = $r[0]["parent"];
2164                                         $parent_uri = $r[0]["parent-uri"];
2165                                 }
2166
2167                                 if(!$is_like) {
2168                                         $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2169                                                 dbesc(datetime_convert()),
2170                                                 intval($importer["importer_uid"]),
2171                                                 intval($r[0]["parent"])
2172                                         );
2173
2174                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2175                                                 dbesc(datetime_convert()),
2176                                                 intval($importer["importer_uid"]),
2177                                                 intval($posted_id)
2178                                         );
2179                                 }
2180
2181                                 if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
2182                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2183                                         proc_run("php", "include/notifier.php", "comment-import", $posted_id);
2184                                 }
2185
2186                                 return true;
2187                         }
2188                 } else { // $entrytype == DFRN_TOP_LEVEL
2189                         if(!link_compare($item["owner-link"],$importer["url"])) {
2190                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2191                                 // but otherwise there's a possible data mixup on the sender's system.
2192                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
2193                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2194                                 logger('Correcting item owner.', LOGGER_DEBUG);
2195                                 $item["owner-name"]   = $importer["senderName"];
2196                                 $item["owner-link"]   = $importer["url"];
2197                                 $item["owner-avatar"] = $importer["thumb"];
2198                         }
2199
2200                         if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2201                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2202                                 return;
2203                         }
2204
2205                         // This is my contact on another system, but it's really me.
2206                         // Turn this into a wall post.
2207                         $notify = item_is_remote_self($importer, $item);
2208
2209                         $posted_id = item_store($item, false, $notify);
2210
2211                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2212
2213                         if(stristr($item["verb"],ACTIVITY_POKE))
2214                                 self::do_poke($item, $importer, $posted_id);
2215                 }
2216         }
2217
2218         /**
2219          * @brief Deletes items
2220          *
2221          * @param object $xpath XPath object
2222          * @param object $deletion deletion elements
2223          * @param array $importer Record of the importer user mixed with contact of the content
2224          */
2225         private function process_deletion($xpath, $deletion, $importer) {
2226
2227                 logger("Processing deletions");
2228
2229                 foreach($deletion->attributes AS $attributes) {
2230                         if ($attributes->name == "ref")
2231                                 $uri = $attributes->textContent;
2232                         if ($attributes->name == "when")
2233                                 $when = $attributes->textContent;
2234                 }
2235                 if ($when)
2236                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2237                 else
2238                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2239
2240                 if (!$uri OR !$importer["id"])
2241                         return false;
2242
2243                 /// @todo Only select the used fields
2244                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2245                                 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2246                                 dbesc($uri),
2247                                 intval($importer["uid"]),
2248                                 intval($importer["id"])
2249                         );
2250                 if(!count($r)) {
2251                         logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
2252                         return;
2253                 } else {
2254
2255                         $item = $r[0];
2256
2257                         $entrytype = self::get_entry_type($importer, $item);
2258
2259                         if(!$item["deleted"])
2260                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2261                         else
2262                                 return;
2263
2264                         if($item["object-type"] === ACTIVITY_OBJ_EVENT) {
2265                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2266                                 event_delete($item["event-id"]);
2267                         }
2268
2269                         if(($item["verb"] === ACTIVITY_TAG) && ($item["object-type"] === ACTIVITY_OBJ_TAGTERM)) {
2270                                 $xo = parse_xml_string($item["object"],false);
2271                                 $xt = parse_xml_string($item["target"],false);
2272                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
2273                                         $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2274                                                 dbesc($xt->id),
2275                                                 intval($importer["importer_uid"])
2276                                         );
2277                                         if(count($i)) {
2278
2279                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2280
2281                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2282                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2283                                                 $author_copy = (($item["origin"]) ? true : false);
2284
2285                                                 if($owner_remove && $author_copy)
2286                                                         return;
2287                                                 if($author_remove || $owner_remove) {
2288                                                         $tags = explode(',',$i[0]["tag"]);
2289                                                         $newtags = array();
2290                                                         if(count($tags)) {
2291                                                                 foreach($tags as $tag)
2292                                                                         if(trim($tag) !== trim($xo->body))
2293                                                                                 $newtags[] = trim($tag);
2294                                                         }
2295                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2296                                                                 dbesc(implode(',',$newtags)),
2297                                                                 intval($i[0]["id"])
2298                                                         );
2299                                                         create_tags_from_item($i[0]["id"]);
2300                                                 }
2301                                         }
2302                                 }
2303                         }
2304
2305                         if($entrytype == DFRN_TOP_LEVEL) {
2306                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2307                                                 `body` = '', `title` = ''
2308                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2309                                                 dbesc($when),
2310                                                 dbesc(datetime_convert()),
2311                                                 dbesc($uri),
2312                                                 intval($importer["uid"])
2313                                         );
2314                                 create_tags_from_itemuri($uri, $importer["uid"]);
2315                                 create_files_from_itemuri($uri, $importer["uid"]);
2316                                 update_thread_uri($uri, $importer["uid"]);
2317                         } else {
2318                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2319                                                 `body` = '', `title` = ''
2320                                         WHERE `uri` = '%s' AND `uid` = %d",
2321                                                 dbesc($when),
2322                                                 dbesc(datetime_convert()),
2323                                                 dbesc($uri),
2324                                                 intval($importer["uid"])
2325                                         );
2326                                 create_tags_from_itemuri($uri, $importer["uid"]);
2327                                 create_files_from_itemuri($uri, $importer["uid"]);
2328                                 update_thread_uri($uri, $importer["importer_uid"]);
2329                                 if($item["last-child"]) {
2330                                         // ensure that last-child is set in case the comment that had it just got wiped.
2331                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2332                                                 dbesc(datetime_convert()),
2333                                                 dbesc($item["parent-uri"]),
2334                                                 intval($item["uid"])
2335                                         );
2336                                         // who is the last child now?
2337                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2338                                                 ORDER BY `created` DESC LIMIT 1",
2339                                                         dbesc($item["parent-uri"]),
2340                                                         intval($importer["uid"])
2341                                         );
2342                                         if(count($r)) {
2343                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2344                                                         intval($r[0]["id"])
2345                                                 );
2346                                         }
2347                                 }
2348                                 // if this is a relayed delete, propagate it to other recipients
2349
2350                                 if($entrytype == DFRN_REPLY_RC) {
2351                                         logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
2352                                         proc_run("php", "include/notifier.php","drop", $item["id"]);
2353                                 }
2354                         }
2355                 }
2356         }
2357
2358         /**
2359          * @brief Imports a DFRN message
2360          *
2361          * @param text $xml The DFRN message
2362          * @param array $importer Record of the importer user mixed with contact of the content
2363          * @param bool $sort_by_date Is used when feeds are polled
2364          */
2365         public static function import($xml,$importer, $sort_by_date = false) {
2366
2367                 if ($xml == "")
2368                         return;
2369
2370                 if($importer["readonly"]) {
2371                         // We aren't receiving stuff from this person. But we will quietly ignore them
2372                         // rather than a blatant "go away" message.
2373                         logger('ignoring contact '.$importer["id"]);
2374                         return;
2375                 }
2376
2377                 $doc = new DOMDocument();
2378                 @$doc->loadXML($xml);
2379
2380                 $xpath = new DomXPath($doc);
2381                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2382                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2383                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2384                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2385                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2386                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2387                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2388                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2389                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2390                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2391
2392                 $header = array();
2393                 $header["uid"] = $importer["uid"];
2394                 $header["network"] = NETWORK_DFRN;
2395                 $header["type"] = "remote";
2396                 $header["wall"] = 0;
2397                 $header["origin"] = 0;
2398                 $header["contact-id"] = $importer["id"];
2399
2400                 // Update the contact table if the data has changed
2401
2402                 // The "atom:author" is only present in feeds
2403                 if ($xpath->query("/atom:feed/atom:author")->length > 0)
2404                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2405
2406                 // Only the "dfrn:owner" in the head section contains all data
2407                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
2408                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2409
2410                 logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2411
2412                 // is it a public forum? Private forums aren't supported by now with this method
2413                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2414
2415                 if ($forum != $importer["forum"])
2416                         q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
2417                                 intval($forum), intval($forum),
2418                                 intval($importer["id"])
2419                         );
2420
2421                 $mails = $xpath->query("/atom:feed/dfrn:mail");
2422                 foreach ($mails AS $mail)
2423                         self::process_mail($xpath, $mail, $importer);
2424
2425                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2426                 foreach ($suggestions AS $suggestion)
2427                         self::process_suggestion($xpath, $suggestion, $importer);
2428
2429                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2430                 foreach ($relocations AS $relocation)
2431                         self::process_relocation($xpath, $relocation, $importer);
2432
2433                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2434                 foreach ($deletions AS $deletion)
2435                         self::process_deletion($xpath, $deletion, $importer);
2436
2437                 if (!$sort_by_date) {
2438                         $entries = $xpath->query("/atom:feed/atom:entry");
2439                         foreach ($entries AS $entry)
2440                                 self::process_entry($header, $xpath, $entry, $importer);
2441                 } else {
2442                         $newentries = array();
2443                         $entries = $xpath->query("/atom:feed/atom:entry");
2444                         foreach ($entries AS $entry) {
2445                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2446                                 $newentries[strtotime($created)] = $entry;
2447                         }
2448
2449                         // Now sort after the publishing date
2450                         ksort($newentries);
2451
2452                         foreach ($newentries AS $entry)
2453                                 self::process_entry($header, $xpath, $entry, $importer);
2454                 }
2455                 logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
2456         }
2457 }
2458 ?>