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