]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge pull request #1750 from annando/1507-contact-update
[friendica.git] / include / diaspora.php
1 <?php
2
3 /*
4 To-Do:
5 - GET /people/9aed8882b9f64896/stream
6 */
7
8 require_once('include/crypto.php');
9 require_once('include/items.php');
10 require_once('include/bb2diaspora.php');
11 require_once('include/contact_selectors.php');
12 require_once('include/queue_fn.php');
13 require_once('include/lock.php');
14 require_once('include/threads.php');
15 require_once('mod/share.php');
16
17 function diaspora_dispatch_public($msg) {
18
19         $enabled = intval(get_config('system','diaspora_enabled'));
20         if(! $enabled) {
21                 logger('mod-diaspora: disabled');
22                 return;
23         }
24
25         $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
26                 ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' )
27                 AND `account_expired` = 0 AND `account_removed` = 0 ",
28                 dbesc(NETWORK_DIASPORA),
29                 dbesc($msg['author'])
30         );
31         if(count($r)) {
32                 foreach($r as $rr) {
33                         logger('diaspora_public: delivering to: ' . $rr['username']);
34                         diaspora_dispatch($rr,$msg);
35                 }
36         }
37         else
38                 logger('diaspora_public: no subscribers');
39 }
40
41
42
43 function diaspora_dispatch($importer,$msg,$attempt=1) {
44
45         $ret = 0;
46
47         $enabled = intval(get_config('system','diaspora_enabled'));
48         if(! $enabled) {
49                 logger('mod-diaspora: disabled');
50                 return;
51         }
52
53         // php doesn't like dashes in variable names
54
55         $msg['message'] = str_replace(
56                         array('<activity_streams-photo>','</activity_streams-photo>'),
57                         array('<asphoto>','</asphoto>'),
58                         $msg['message']);
59
60
61         $parsed_xml = parse_xml_string($msg['message'],false);
62
63         $xmlbase = $parsed_xml->post;
64
65         logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
66
67
68         if($xmlbase->request) {
69                 $ret = diaspora_request($importer,$xmlbase->request);
70         }
71         elseif($xmlbase->status_message) {
72                 $ret = diaspora_post($importer,$xmlbase->status_message,$msg);
73         }
74         elseif($xmlbase->profile) {
75                 $ret = diaspora_profile($importer,$xmlbase->profile,$msg);
76         }
77         elseif($xmlbase->comment) {
78                 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
79         }
80         elseif($xmlbase->like) {
81                 $ret = diaspora_like($importer,$xmlbase->like,$msg);
82         }
83         elseif($xmlbase->asphoto) {
84                 $ret = diaspora_asphoto($importer,$xmlbase->asphoto,$msg);
85         }
86         elseif($xmlbase->reshare) {
87                 $ret = diaspora_reshare($importer,$xmlbase->reshare,$msg);
88         }
89         elseif($xmlbase->retraction) {
90                 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
91         }
92         elseif($xmlbase->signed_retraction) {
93                 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
94         }
95         elseif($xmlbase->relayable_retraction) {
96                 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
97         }
98         elseif($xmlbase->photo) {
99                 $ret = diaspora_photo($importer,$xmlbase->photo,$msg,$attempt);
100         }
101         elseif($xmlbase->conversation) {
102                 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
103         }
104         elseif($xmlbase->message) {
105                 $ret = diaspora_message($importer,$xmlbase->message,$msg);
106         }
107         else {
108                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
109         }
110         return $ret;
111 }
112
113 function diaspora_handle_from_contact($contact_id) {
114         $handle = False;
115
116         logger("diaspora_handle_from_contact: contact id is " . $contact_id, LOGGER_DEBUG);
117
118         $r = q("SELECT network, addr, self, url, nick FROM contact WHERE id = %d",
119                intval($contact_id)
120         );
121         if($r) {
122                 $contact = $r[0];
123
124                 logger("diaspora_handle_from_contact: contact 'self' = " . $contact['self'] . " 'url' = " . $contact['url'], LOGGER_DEBUG);
125
126                 if($contact['network'] === NETWORK_DIASPORA) {
127                         $handle = $contact['addr'];
128
129 //                      logger("diaspora_handle_from_contact: contact id is a Diaspora person, handle = " . $handle, LOGGER_DEBUG);
130                 }
131                 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
132                         $baseurl_start = strpos($contact['url'],'://') + 3;
133                         $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
134                         $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
135                         $handle = $contact['nick'] . '@' . $baseurl;
136
137 //                      logger("diaspora_handle_from_contact: contact id is a DFRN person, handle = " . $handle, LOGGER_DEBUG);
138                 }
139         }
140
141         return $handle;
142 }
143
144 function diaspora_get_contact_by_handle($uid,$handle) {
145         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
146                 dbesc(NETWORK_DIASPORA),
147                 intval($uid),
148                 dbesc($handle)
149         );
150         if($r && count($r))
151                 return $r[0];
152
153         $handle_parts = explode("@", $handle);
154         $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
155         $r = q("SELECT * FROM contact WHERE network = '%s' AND uid = %d AND nurl LIKE '%s' LIMIT 1",
156                dbesc(NETWORK_DFRN),
157                intval($uid),
158                dbesc($nurl_sql)
159         );
160         if($r && count($r))
161                 return $r[0];
162
163         return false;
164 }
165
166 function find_diaspora_person_by_handle($handle) {
167
168         $person = false;
169         $update = false;
170         $got_lock = false;
171
172         $endlessloop = 0;
173         $maxloops = 10;
174
175         do {
176                 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
177                         dbesc(NETWORK_DIASPORA),
178                         dbesc($handle)
179                 );
180                 if(count($r)) {
181                         $person = $r[0];
182                         logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
183
184                         // update record occasionally so it doesn't get stale
185                         $d = strtotime($person['updated'] . ' +00:00');
186                         if($d < strtotime('now - 14 days'))
187                                 $update = true;
188                 }
189
190
191                 // FETCHING PERSON INFORMATION FROM REMOTE SERVER
192                 //
193                 // If the person isn't in our 'fcontact' table, or if he/she is but
194                 // his/her information hasn't been updated for more than 14 days, then
195                 // we want to fetch the person's information from the remote server.
196                 //
197                 // Note that $person isn't changed by this block of code unless the
198                 // person's information has been successfully fetched from the remote
199                 // server. So if $person was 'false' to begin with (because he/she wasn't
200                 // in the local cache), it'll stay false, and if $person held the local
201                 // cache information to begin with, it'll keep that information. That way
202                 // if there's a problem with the remote fetch, we can at least use our
203                 // cached information--it's better than nothing.
204
205                 if((! $person) || ($update))  {
206                         // Lock the function to prevent race conditions if multiple items
207                         // come in at the same time from a person who doesn't exist in
208                         // fcontact
209                         //
210                         // Don't loop forever. On the last loop, try to create the contact
211                         // whether the function is locked or not. Maybe the locking thread
212                         // has died or something. At any rate, a duplicate in 'fcontact'
213                         // is a much smaller problem than a deadlocked thread
214                         $got_lock = lock_function('find_diaspora_person_by_handle', false);
215                         if(($endlessloop + 1) >= $maxloops)
216                                 $got_lock = true;
217
218                         if($got_lock) {
219                                 logger('find_diaspora_person_by_handle: create or refresh', LOGGER_DEBUG);
220                                 require_once('include/Scrape.php');
221                                 $r = probe_url($handle, PROBE_DIASPORA);
222
223                                 // Note that Friendica contacts can return a "Diaspora person"
224                                 // if Diaspora connectivity is enabled on their server
225                                 if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
226                                         add_fcontact($r,$update);
227                                         $person = ($r);
228                                 }
229
230                                 unlock_function('find_diaspora_person_by_handle');
231                         }
232                         else {
233                                 logger('find_diaspora_person_by_handle: couldn\'t lock function', LOGGER_DEBUG);
234                                 if(! $person)
235                                         block_on_function_lock('find_diaspora_person_by_handle');
236                         }
237                 }
238         } while((! $person) && (! $got_lock) && (++$endlessloop < $maxloops));
239         // We need to try again if the person wasn't in 'fcontact' but the function was locked.
240         // The fact that the function was locked may mean that another process was creating the
241         // person's record. It could also mean another process was creating or updating an unrelated
242         // person.
243         //
244         // At any rate, we need to keep trying until we've either got the person or had a chance to
245         // try to fetch his/her remote information. But we don't want to block on locking the
246         // function, because if the other process is creating the record, then when we acquire the lock
247         // we'll dive right into creating another, duplicate record. We DO want to at least wait
248         // until the lock is released, so we don't flood the database with requests.
249         //
250         // If the person was in the 'fcontact' table, don't try again. It's not worth the time, since
251         // we do have some information for the person
252
253         return $person;
254 }
255
256
257 function get_diaspora_key($uri) {
258         logger('Fetching diaspora key for: ' . $uri);
259
260         $r = find_diaspora_person_by_handle($uri);
261         if($r)
262                 return $r['pubkey'];
263         return '';
264 }
265
266
267 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
268         $a = get_app();
269
270         logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
271
272
273         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
274
275 //      $b64_data = base64_encode($msg);
276 //      $b64url_data = base64url_encode($b64_data);
277
278         $b64url_data = base64url_encode($msg);
279
280         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
281
282         $type = 'application/xml';
283         $encoding = 'base64url';
284         $alg = 'RSA-SHA256';
285
286         $signable_data = $data  . '.' . base64url_encode($type) . '.'
287                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
288
289         $signature = rsa_sign($signable_data,$prvkey);
290         $sig = base64url_encode($signature);
291
292 $magic_env = <<< EOT
293 <?xml version='1.0' encoding='UTF-8'?>
294 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
295   <header>
296     <author_id>$handle</author_id>
297   </header>
298   <me:env>
299     <me:encoding>base64url</me:encoding>
300     <me:alg>RSA-SHA256</me:alg>
301     <me:data type="application/xml">$data</me:data>
302     <me:sig>$sig</me:sig>
303   </me:env>
304 </diaspora>
305 EOT;
306
307         logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
308         return $magic_env;
309
310 }
311
312
313
314
315 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
316         $a = get_app();
317
318         if($public)
319                 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
320
321         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
322
323         // without a public key nothing will work
324
325         if(! $pubkey) {
326                 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
327                 return '';
328         }
329
330         $inner_aes_key = random_string(32);
331         $b_inner_aes_key = base64_encode($inner_aes_key);
332         $inner_iv = random_string(16);
333         $b_inner_iv = base64_encode($inner_iv);
334
335         $outer_aes_key = random_string(32);
336         $b_outer_aes_key = base64_encode($outer_aes_key);
337         $outer_iv = random_string(16);
338         $b_outer_iv = base64_encode($outer_iv);
339
340         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
341
342         $padded_data = pkcs5_pad($msg,16);
343         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
344
345         $b64_data = base64_encode($inner_encrypted);
346
347
348         $b64url_data = base64url_encode($b64_data);
349         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
350
351         $type = 'application/xml';
352         $encoding = 'base64url';
353         $alg = 'RSA-SHA256';
354
355         $signable_data = $data  . '.' . base64url_encode($type) . '.'
356                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
357
358         $signature = rsa_sign($signable_data,$prvkey);
359         $sig = base64url_encode($signature);
360
361 $decrypted_header = <<< EOT
362 <decrypted_header>
363   <iv>$b_inner_iv</iv>
364   <aes_key>$b_inner_aes_key</aes_key>
365   <author_id>$handle</author_id>
366 </decrypted_header>
367 EOT;
368
369         $decrypted_header = pkcs5_pad($decrypted_header,16);
370
371         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
372
373         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
374
375         $encrypted_outer_key_bundle = '';
376         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
377
378         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
379
380         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
381
382         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
383                 'ciphertext' => base64_encode($ciphertext)));
384         $cipher_json = base64_encode($encrypted_header_json_object);
385
386         $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
387
388 $magic_env = <<< EOT
389 <?xml version='1.0' encoding='UTF-8'?>
390 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
391   $encrypted_header
392   <me:env>
393     <me:encoding>base64url</me:encoding>
394     <me:alg>RSA-SHA256</me:alg>
395     <me:data type="application/xml">$data</me:data>
396     <me:sig>$sig</me:sig>
397   </me:env>
398 </diaspora>
399 EOT;
400
401         logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
402         return $magic_env;
403
404 }
405
406 /**
407  *
408  * diaspora_decode($importer,$xml)
409  *   array $importer -> from user table
410  *   string $xml -> urldecoded Diaspora salmon 
411  *
412  * Returns array
413  * 'message' -> decoded Diaspora XML message
414  * 'author' -> author diaspora handle
415  * 'key' -> author public key (converted to pkcs#8)
416  *
417  * Author and key are used elsewhere to save a lookup for verifying replies and likes
418  */
419
420
421 function diaspora_decode($importer,$xml) {
422
423         $public = false;
424         $basedom = parse_xml_string($xml);
425
426         $children = $basedom->children('https://joindiaspora.com/protocol');
427
428         if($children->header) {
429                 $public = true;
430                 $author_link = str_replace('acct:','',$children->header->author_id);
431         }
432         else {
433
434                 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
435
436                 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
437                 $ciphertext = base64_decode($encrypted_header->ciphertext);
438
439                 $outer_key_bundle = '';
440                 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
441
442                 $j_outer_key_bundle = json_decode($outer_key_bundle);
443
444                 $outer_iv = base64_decode($j_outer_key_bundle->iv);
445                 $outer_key = base64_decode($j_outer_key_bundle->key);
446
447                 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
448
449
450                 $decrypted = pkcs5_unpad($decrypted);
451
452                 /**
453                  * $decrypted now contains something like
454                  *
455                  *  <decrypted_header>
456                  *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
457                  *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
458
459 ***** OBSOLETE
460
461                  *     <author>
462                  *       <name>Ryan Hughes</name>
463                  *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
464                  *     </author>
465
466 ***** CURRENT
467
468                  *     <author_id>galaxor@diaspora.priateship.org</author_id>
469
470 ***** END DIFFS
471
472                  *  </decrypted_header>
473                  */
474
475                 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
476                 $idom = parse_xml_string($decrypted,false);
477
478                 $inner_iv = base64_decode($idom->iv);
479                 $inner_aes_key = base64_decode($idom->aes_key);
480
481                 $author_link = str_replace('acct:','',$idom->author_id);
482
483         }
484
485         $dom = $basedom->children(NAMESPACE_SALMON_ME);
486
487         // figure out where in the DOM tree our data is hiding
488
489         if($dom->provenance->data)
490                 $base = $dom->provenance;
491         elseif($dom->env->data)
492                 $base = $dom->env;
493         elseif($dom->data)
494                 $base = $dom;
495
496         if(! $base) {
497                 logger('mod-diaspora: unable to locate salmon data in xml ');
498                 http_status_exit(400);
499         }
500
501
502         // Stash the signature away for now. We have to find their key or it won't be good for anything.
503         $signature = base64url_decode($base->sig);
504
505         // unpack the  data
506
507         // strip whitespace so our data element will return to one big base64 blob
508         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
509
510
511         // stash away some other stuff for later
512
513         $type = $base->data[0]->attributes()->type[0];
514         $keyhash = $base->sig[0]->attributes()->keyhash[0];
515         $encoding = $base->encoding;
516         $alg = $base->alg;
517
518
519         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
520
521
522         // decode the data
523         $data = base64url_decode($data);
524
525
526         if($public) {
527                 $inner_decrypted = $data;
528         }
529         else {
530
531                 // Decode the encrypted blob
532
533                 $inner_encrypted = base64_decode($data);
534                 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
535                 $inner_decrypted = pkcs5_unpad($inner_decrypted);
536         }
537
538         if(! $author_link) {
539                 logger('mod-diaspora: Could not retrieve author URI.');
540                 http_status_exit(400);
541         }
542
543         // Once we have the author URI, go to the web and try to find their public key
544         // (first this will look it up locally if it is in the fcontact cache)
545         // This will also convert diaspora public key from pkcs#1 to pkcs#8
546
547         logger('mod-diaspora: Fetching key for ' . $author_link );
548         $key = get_diaspora_key($author_link);
549
550         if(! $key) {
551                 logger('mod-diaspora: Could not retrieve author key.');
552                 http_status_exit(400);
553         }
554
555         $verify = rsa_verify($signed_data,$signature,$key);
556
557         if(! $verify) {
558                 logger('mod-diaspora: Message did not verify. Discarding.');
559                 http_status_exit(400);
560         }
561
562         logger('mod-diaspora: Message verified.');
563
564         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
565
566 }
567
568
569 function diaspora_request($importer,$xml) {
570
571         $a = get_app();
572
573         $sender_handle = unxmlify($xml->sender_handle);
574         $recipient_handle = unxmlify($xml->recipient_handle);
575
576         if(! $sender_handle || ! $recipient_handle)
577                 return;
578
579         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
580
581         if($contact) {
582
583                 // perhaps we were already sharing with this person. Now they're sharing with us.
584                 // That makes us friends.
585
586                 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
587                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
588                                 intval(CONTACT_IS_FRIEND),
589                                 intval($contact['id']),
590                                 intval($importer['uid'])
591                         );
592                 }
593                 // send notification
594
595                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
596                         intval($importer['uid'])
597                 );
598
599                 if((count($r)) && (!$r[0]['hide-friends']) && (!$contact['hidden']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
600                         require_once('include/items.php');
601
602                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
603                                 intval($importer['uid'])
604                         );
605
606                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
607
608                         if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
609
610                                 $arr = array();
611                                 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']);
612                                 $arr['uid'] = $importer['uid'];
613                                 $arr['contact-id'] = $self[0]['id'];
614                                 $arr['wall'] = 1;
615                                 $arr['type'] = 'wall';
616                                 $arr['gravity'] = 0;
617                                 $arr['origin'] = 1;
618                                 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
619                                 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
620                                 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
621                                 $arr['verb'] = ACTIVITY_FRIEND;
622                                 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
623
624                                 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
625                                 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
626                                 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
627                                 $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
628
629                                 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
630                                         . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
631                                 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
632                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
633                                 $arr['object'] .= '</link></object>' . "\n";
634                                 $arr['last-child'] = 1;
635
636                                 $arr['allow_cid'] = $user[0]['allow_cid'];
637                                 $arr['allow_gid'] = $user[0]['allow_gid'];
638                                 $arr['deny_cid']  = $user[0]['deny_cid'];
639                                 $arr['deny_gid']  = $user[0]['deny_gid'];
640
641                                 $i = item_store($arr);
642                                 if($i)
643                                 proc_run('php',"include/notifier.php","activity","$i");
644
645                         }
646
647                 }
648
649                 return;
650         }
651
652         $ret = find_diaspora_person_by_handle($sender_handle);
653
654
655         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
656                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
657                 return;
658         }
659
660         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
661
662
663
664         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
665                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
666                 intval($importer['uid']),
667                 dbesc($ret['network']),
668                 dbesc($ret['addr']),
669                 datetime_convert(),
670                 dbesc($ret['url']),
671                 dbesc(normalise_link($ret['url'])),
672                 dbesc($batch),
673                 dbesc($ret['name']),
674                 dbesc($ret['nick']),
675                 dbesc($ret['photo']),
676                 dbesc($ret['pubkey']),
677                 dbesc($ret['notify']),
678                 dbesc($ret['poll']),
679                 1,
680                 2
681         );
682
683         // find the contact record we just created
684
685         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
686
687         if(! $contact_record) {
688                 logger('diaspora_request: unable to locate newly created contact record.');
689                 return;
690         }
691
692         $g = q("select def_gid from user where uid = %d limit 1",
693                 intval($importer['uid'])
694         );
695         if($g && intval($g[0]['def_gid'])) {
696                 require_once('include/group.php');
697                 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
698         }
699
700         if($importer['page-flags'] == PAGE_NORMAL) {
701
702                 $hash = random_string() . (string) time();   // Generate a confirm_key
703
704                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
705                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
706                         intval($importer['uid']),
707                         intval($contact_record['id']),
708                         0,
709                         0,
710                         dbesc( t('Sharing notification from Diaspora network')),
711                         dbesc($hash),
712                         dbesc(datetime_convert())
713                 );
714         }
715         else {
716
717                 // automatic friend approval
718
719                 require_once('include/Photo.php');
720
721                 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
722
723                 // technically they are sharing with us (CONTACT_IS_SHARING),
724                 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
725                 // we are going to change the relationship and make them a follower.
726
727                 if($importer['page-flags'] == PAGE_FREELOVE)
728                         $new_relation = CONTACT_IS_FRIEND;
729                 else
730                         $new_relation = CONTACT_IS_FOLLOWER;
731
732                 $r = q("UPDATE `contact` SET
733                         `photo` = '%s',
734                         `thumb` = '%s',
735                         `micro` = '%s',
736                         `rel` = %d,
737                         `name-date` = '%s',
738                         `uri-date` = '%s',
739                         `avatar-date` = '%s',
740                         `blocked` = 0,
741                         `pending` = 0,
742                         `writable` = 1
743                         WHERE `id` = %d
744                         ",
745                         dbesc($photos[0]),
746                         dbesc($photos[1]),
747                         dbesc($photos[2]),
748                         intval($new_relation),
749                         dbesc(datetime_convert()),
750                         dbesc(datetime_convert()),
751                         dbesc(datetime_convert()),
752                         intval($contact_record['id'])
753                 );
754
755                 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
756                 if($u)
757                         $ret = diaspora_share($u[0],$contact_record);
758         }
759
760         return;
761 }
762
763 function diaspora_post_allow($importer,$contact) {
764
765         // perhaps we were already sharing with this person. Now they're sharing with us.
766         // That makes us friends.
767         // Normally this should have handled by getting a request - but this could get lost
768         if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
769                 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
770                         intval(CONTACT_IS_FRIEND),
771                         intval($contact['id']),
772                         intval($importer['uid'])
773                 );
774                 $contact['rel'] = CONTACT_IS_FRIEND;
775                 logger('diaspora_post_allow: defining user '.$contact["nick"].' as friend');
776         }
777
778         if(($contact['blocked']) || ($contact['readonly']) || ($contact['archive']))
779                 return false;
780         if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
781                 return true;
782         if($contact['rel'] == CONTACT_IS_FOLLOWER)
783                 if($importer['page-flags'] == PAGE_COMMUNITY)
784                         return true;
785         return false;
786 }
787
788 function diaspora_is_redmatrix($url) {
789         return(strstr($url, "/channel/"));
790 }
791
792 function diaspora_plink($addr, $guid) {
793         $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", $addr);
794
795         // Fallback
796         if (!$r)
797                 return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
798
799         // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
800         // So we try another way as well.
801         $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
802         if ($s)
803                 $r[0]["network"] = $s[0]["network"];
804
805         if ($r[0]["network"] == NETWORK_DFRN)
806                 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
807
808         if (diaspora_is_redmatrix($r[0]["url"]))
809                 return $r[0]["url"]."/?f=&mid=".$guid;
810
811         return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
812 }
813
814 function diaspora_post($importer,$xml,$msg) {
815
816         $a = get_app();
817         $guid = notags(unxmlify($xml->guid));
818         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
819
820         if($diaspora_handle != $msg['author']) {
821                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
822                 return 202;
823         }
824
825         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
826         if(! $contact)
827                 return;
828
829         if(! diaspora_post_allow($importer,$contact)) {
830                 logger('diaspora_post: Ignoring this author.');
831                 return 202;
832         }
833
834         $message_id = $diaspora_handle . ':' . $guid;
835         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
836                 intval($importer['uid']),
837                 dbesc($message_id),
838                 dbesc($guid)
839         );
840         if(count($r)) {
841                 logger('diaspora_post: message exists: ' . $guid);
842                 return;
843         }
844
845         $created = unxmlify($xml->created_at);
846         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
847
848         $body = diaspora2bb($xml->raw_message);
849
850         $datarray = array();
851
852         $datarray["object"] = json_encode($xml);
853
854         if($xml->photo->remote_photo_path AND $xml->photo->remote_photo_name)
855                 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
856         else {
857                 $datarray['object-type'] = ACTIVITY_OBJ_NOTE;
858                 // Add OEmbed and other information to the body
859                 if (!diaspora_is_redmatrix($contact['url']))
860                         $body = add_page_info_to_body($body, false, true);
861         }
862
863         $str_tags = '';
864
865         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
866         if($cnt) {
867                 foreach($matches as $mtch) {
868                         if(strlen($str_tags))
869                                 $str_tags .= ',';
870                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
871                 }
872         }
873
874         $plink = diaspora_plink($diaspora_handle, $guid);
875
876         $datarray['uid'] = $importer['uid'];
877         $datarray['contact-id'] = $contact['id'];
878         $datarray['wall'] = 0;
879         $datarray['network'] = NETWORK_DIASPORA;
880         $datarray['verb'] = ACTIVITY_POST;
881         $datarray['guid'] = $guid;
882         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
883         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
884         $datarray['private'] = $private;
885         $datarray['parent'] = 0;
886         $datarray['plink'] = $plink;
887         $datarray['owner-name'] = $contact['name'];
888         $datarray['owner-link'] = $contact['url'];
889         //$datarray['owner-avatar'] = $contact['thumb'];
890         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
891         $datarray['author-name'] = $contact['name'];
892         $datarray['author-link'] = $contact['url'];
893         $datarray['author-avatar'] = $contact['thumb'];
894         $datarray['body'] = $body;
895         $datarray['tag'] = $str_tags;
896         if ($xml->provider_display_name)
897                 $datarray["app"] = unxmlify($xml->provider_display_name);
898         else
899                 $datarray['app']  = 'Diaspora';
900
901         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
902
903         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
904
905         DiasporaFetchGuid($datarray);
906         $message_id = item_store($datarray);
907
908         return;
909
910 }
911
912 function DiasporaFetchGuid($item) {
913         preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
914                 function ($match) use ($item){
915                         return(DiasporaFetchGuidSub($match, $item));
916                 },$item["body"]);
917 }
918
919 function DiasporaFetchGuidSub($match, $item) {
920         $a = get_app();
921
922         if (!diaspora_store_by_guid($match[1], $item["author-link"]))
923                 diaspora_store_by_guid($match[1], $item["owner-link"]);
924 }
925
926 function diaspora_store_by_guid($guid, $server, $uid = 0) {
927         require_once("include/Contact.php");
928
929         $serverparts = parse_url($server);
930         $server = $serverparts["scheme"]."://".$serverparts["host"];
931
932         logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
933
934         $item = diaspora_fetch_message($guid, $server);
935
936         if (!$item)
937                 return false;
938
939         logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
940
941         $body = $item["body"];
942         $str_tags = $item["tag"];
943         $app = $item["app"];
944         $created = $item["created"];
945         $author = $item["author"];
946         $guid = $item["guid"];
947         $private = $item["private"];
948         $object = $item["object"];
949         $objecttype = $item["object-type"];
950
951         $message_id = $author.':'.$guid;
952         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
953                 intval($uid),
954                 dbesc($message_id),
955                 dbesc($guid)
956         );
957         if(count($r))
958                 return $r[0]["id"];
959
960         $person = find_diaspora_person_by_handle($author);
961
962         $datarray = array();
963         $datarray['uid'] = $uid;
964         $datarray['contact-id'] = get_contact($person['url'], $uid);
965         $datarray['wall'] = 0;
966         $datarray['network']  = NETWORK_DIASPORA;
967         $datarray['guid'] = $guid;
968         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
969         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
970         $datarray['private'] = $private;
971         $datarray['parent'] = 0;
972         $datarray['plink'] = diaspora_plink($author, $guid);
973         $datarray['author-name'] = $person['name'];
974         $datarray['author-link'] = $person['url'];
975         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
976         $datarray['owner-name'] = $datarray['author-name'];
977         $datarray['owner-link'] = $datarray['author-link'];
978         $datarray['owner-avatar'] = $datarray['author-avatar'];
979         $datarray['body'] = $body;
980         $datarray['tag'] = $str_tags;
981         $datarray['app']  = $app;
982         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
983         $datarray['object'] = $object;
984         $datarray['object-type'] = $objecttype;
985
986         if ($datarray['contact-id'] == 0)
987                 return false;
988
989         DiasporaFetchGuid($datarray);
990         $message_id = item_store($datarray);
991
992         // To-Do:
993         // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
994
995         return $message_id;
996 }
997
998 function diaspora_fetch_message($guid, $server, $level = 0) {
999
1000         if ($level > 5)
1001                 return false;
1002
1003         $a = get_app();
1004
1005         // This will not work if the server is not a Diaspora server
1006         $source_url = $server.'/p/'.$guid.'.xml';
1007         $x = fetch_url($source_url);
1008         if(!$x)
1009                 return false;
1010
1011         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
1012         $source_xml = parse_xml_string($x,false);
1013
1014         $item = array();
1015         $item["app"] = 'Diaspora';
1016         $item["guid"] = $guid;
1017         $body = "";
1018
1019         if ($source_xml->post->status_message->created_at)
1020                 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
1021
1022         if ($source_xml->post->status_message->provider_display_name)
1023                 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
1024
1025         if ($source_xml->post->status_message->diaspora_handle)
1026                 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
1027
1028         if ($source_xml->post->status_message->guid)
1029                 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
1030
1031         $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
1032         $item["object"] = json_encode($source_xml->post);
1033
1034         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
1035                 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1036                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
1037                 $body = scale_external_images($body,false);
1038         } elseif($source_xml->post->asphoto->image_url) {
1039                 $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1040                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
1041                 $body = scale_external_images($body);
1042         } elseif($source_xml->post->status_message) {
1043                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1044
1045                 // Checking for embedded pictures
1046                 if($source_xml->post->status_message->photo->remote_photo_path AND
1047                         $source_xml->post->status_message->photo->remote_photo_name) {
1048
1049                         $item["object-type"] = ACTIVITY_OBJ_PHOTO;
1050
1051                         $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1052                         $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1053
1054                         $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1055
1056                         logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1057                 } else
1058                         $item["object-type"] = ACTIVITY_OBJ_NOTE;
1059
1060                 $body = scale_external_images($body);
1061
1062                 // Add OEmbed and other information to the body
1063                 // To-Do: It could be a repeated redmatrix item
1064                 // Then we shouldn't add further data to it
1065                 if ($item["object-type"] == ACTIVITY_OBJ_NOTE)
1066                         $body = add_page_info_to_body($body, false, true);
1067
1068         } elseif($source_xml->post->reshare) {
1069                 // Reshare of a reshare
1070                 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1071         } else {
1072                 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1073                 logger('no content found: '.print_r($source_xml,true));
1074                 return false;
1075         }
1076
1077         if (trim($body) == "")
1078                 return false;
1079
1080         $item["tag"] = '';
1081         $item["body"] = $body;
1082
1083         return $item;
1084 }
1085
1086 function diaspora_reshare($importer,$xml,$msg) {
1087
1088         logger('diaspora_reshare: init: ' . print_r($xml,true));
1089
1090         $a = get_app();
1091         $guid = notags(unxmlify($xml->guid));
1092         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1093
1094
1095         if($diaspora_handle != $msg['author']) {
1096                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1097                 return 202;
1098         }
1099
1100         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1101         if(! $contact)
1102                 return;
1103
1104         if(! diaspora_post_allow($importer,$contact)) {
1105                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1106                 return 202;
1107         }
1108
1109         $message_id = $diaspora_handle . ':' . $guid;
1110         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1111                 intval($importer['uid']),
1112                 dbesc($message_id),
1113                 dbesc($guid)
1114         );
1115         if(count($r)) {
1116                 logger('diaspora_reshare: message exists: ' . $guid);
1117                 return;
1118         }
1119
1120         $orig_author = notags(unxmlify($xml->root_diaspora_id));
1121         $orig_guid = notags(unxmlify($xml->root_guid));
1122         $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1123
1124         $create_original_post = false;
1125
1126         // Do we already have this item?
1127         $r = q("SELECT `body`, `tag`, `app`, `created`, `plink`, `object`, `object-type`, `uri` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1128                 dbesc($orig_guid),
1129                 dbesc(NETWORK_DIASPORA)
1130         );
1131         if(count($r)) {
1132                 logger('reshared message '.$orig_guid." reshared by ".$guid.' already exists on system.');
1133
1134                 // Maybe it is already a reshared item?
1135                 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1136                 require_once('include/api.php');
1137                 if (api_share_as_retweet($r[0]))
1138                         $r = array();
1139                 else {
1140                         $body = $r[0]["body"];
1141                         $str_tags = $r[0]["tag"];
1142                         $app = $r[0]["app"];
1143                         $orig_created = $r[0]["created"];
1144                         $orig_plink = $r[0]["plink"];
1145                         $orig_uri = $r[0]["uri"];
1146                         $object = $r[0]["object"];
1147                         $objecttype = $r[0]["object-type"];
1148                 }
1149         }
1150
1151         if (!count($r)) {
1152                 $body = "";
1153                 $str_tags = "";
1154                 $app = "";
1155
1156                 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1157                 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1158                 $item = diaspora_fetch_message($orig_guid, $server);
1159
1160                 if (!$item) {
1161                         $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1162                         logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1163                         $item = diaspora_fetch_message($orig_guid, $server);
1164                 }
1165                 if (!$item) {
1166                         $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1167                         logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1168                         $item = diaspora_fetch_message($orig_guid, $server);
1169                 }
1170                 if (!$item) {
1171                         $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1172                         logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1173                         $item = diaspora_fetch_message($orig_guid, $server);
1174                 }
1175
1176                 if ($item) {
1177                         $body = $item["body"];
1178                         $str_tags = $item["tag"];
1179                         $app = $item["app"];
1180                         $orig_created = $item["created"];
1181                         $orig_author = $item["author"];
1182                         $orig_guid = $item["guid"];
1183                         $orig_plink = diaspora_plink($orig_author, $orig_guid);
1184                         $orig_uri = $orig_author.':'.$orig_guid;
1185                         $create_original_post = ($body != "");
1186                         $object = $item["object"];
1187                         $objecttype = $item["object-type"];
1188                 }
1189         }
1190
1191         $plink = diaspora_plink($diaspora_handle, $guid);
1192
1193         $person = find_diaspora_person_by_handle($orig_author);
1194
1195         $created = unxmlify($xml->created_at);
1196         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1197
1198         $datarray = array();
1199
1200         $datarray['uid'] = $importer['uid'];
1201         $datarray['contact-id'] = $contact['id'];
1202         $datarray['wall'] = 0;
1203         $datarray['network']  = NETWORK_DIASPORA;
1204         $datarray['guid'] = $guid;
1205         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1206         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1207         $datarray['private'] = $private;
1208         $datarray['parent'] = 0;
1209         $datarray['plink'] = $plink;
1210         $datarray['owner-name'] = $contact['name'];
1211         $datarray['owner-link'] = $contact['url'];
1212         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1213         if (!intval(get_config('system','wall-to-wall_share'))) {
1214                 $prefix = share_header($person['name'], $person['url'], ((x($person,'thumb')) ? $person['thumb'] : $person['photo']), $orig_guid, $orig_created, $orig_url);
1215
1216                 $datarray['author-name'] = $contact['name'];
1217                 $datarray['author-link'] = $contact['url'];
1218                 $datarray['author-avatar'] = $contact['thumb'];
1219                 $datarray['body'] = $prefix.$body."[/share]";
1220         } else {
1221                 // Let reshared messages look like wall-to-wall posts
1222                 $datarray['author-name'] = $person['name'];
1223                 $datarray['author-link'] = $person['url'];
1224                 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1225                 $datarray['body'] = $body;
1226         }
1227
1228         $datarray["object"] = json_encode($xml);
1229         $datarray['object-type'] = $objecttype;
1230
1231         $datarray['tag'] = $str_tags;
1232         $datarray['app']  = $app;
1233
1234         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1235         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1236
1237         // Store the original item of a reshare
1238         if ($create_original_post) {
1239                 require_once("include/Contact.php");
1240
1241                 $datarray2 = $datarray;
1242
1243                 $datarray2['uid'] = 0;
1244                 $datarray2['contact-id'] = get_contact($person['url'], 0);
1245                 $datarray2['guid'] = $orig_guid;
1246                 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_uri;
1247                 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = $datarray2['commented'] = $datarray2['received'] = datetime_convert('UTC','UTC',$orig_created);
1248                 $datarray2['parent'] = 0;
1249                 $datarray2['plink'] = $orig_plink;
1250
1251                 $datarray2['author-name'] = $person['name'];
1252                 $datarray2['author-link'] = $person['url'];
1253                 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1254                 $datarray2['owner-name'] = $datarray2['author-name'];
1255                 $datarray2['owner-link'] = $datarray2['author-link'];
1256                 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1257                 $datarray2['body'] = $body;
1258                 $datarray2["object"] = $object;
1259
1260                 DiasporaFetchGuid($datarray2);
1261                 $message_id = item_store($datarray2);
1262
1263                 logger("Store original item ".$orig_guid." under message id ".$message_id);
1264         }
1265
1266         DiasporaFetchGuid($datarray);
1267         $message_id = item_store($datarray);
1268
1269         return;
1270
1271 }
1272
1273
1274 function diaspora_asphoto($importer,$xml,$msg) {
1275         logger('diaspora_asphoto called');
1276
1277         $a = get_app();
1278         $guid = notags(unxmlify($xml->guid));
1279         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1280
1281         if($diaspora_handle != $msg['author']) {
1282                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1283                 return 202;
1284         }
1285
1286         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1287         if(! $contact)
1288                 return;
1289
1290         if(! diaspora_post_allow($importer,$contact)) {
1291                 logger('diaspora_asphoto: Ignoring this author.');
1292                 return 202;
1293         }
1294
1295         $message_id = $diaspora_handle . ':' . $guid;
1296         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1297                 intval($importer['uid']),
1298                 dbesc($message_id),
1299                 dbesc($guid)
1300         );
1301         if(count($r)) {
1302                 logger('diaspora_asphoto: message exists: ' . $guid);
1303                 return;
1304         }
1305
1306         $created = unxmlify($xml->created_at);
1307         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1308
1309         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1310                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1311                 $body = scale_external_images($body,false);
1312         }
1313         elseif($xml->image_url) {
1314                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1315                 $body = scale_external_images($body);
1316         }
1317         else {
1318                 logger('diaspora_asphoto: no photo url found.');
1319                 return;
1320         }
1321
1322         $plink = diaspora_plink($diaspora_handle, $guid);
1323
1324         $datarray = array();
1325
1326         $datarray['uid'] = $importer['uid'];
1327         $datarray['contact-id'] = $contact['id'];
1328         $datarray['wall'] = 0;
1329         $datarray['network']  = NETWORK_DIASPORA;
1330         $datarray['guid'] = $guid;
1331         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1332         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1333         $datarray['private'] = $private;
1334         $datarray['parent'] = 0;
1335         $datarray['plink'] = $plink;
1336         $datarray['owner-name'] = $contact['name'];
1337         $datarray['owner-link'] = $contact['url'];
1338         //$datarray['owner-avatar'] = $contact['thumb'];
1339         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1340         $datarray['author-name'] = $contact['name'];
1341         $datarray['author-link'] = $contact['url'];
1342         $datarray['author-avatar'] = $contact['thumb'];
1343         $datarray['body'] = $body;
1344         $datarray["object"] = json_encode($xml);
1345         $datarray['object-type'] = ACTIVITY_OBJ_PHOTO;
1346
1347         $datarray['app']  = 'Diaspora/Cubbi.es';
1348
1349         DiasporaFetchGuid($datarray);
1350         $message_id = item_store($datarray);
1351
1352         //if($message_id) {
1353         //      q("update item set plink = '%s' where id = %d",
1354         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1355         //              intval($message_id)
1356         //      );
1357         //}
1358
1359         return;
1360
1361 }
1362
1363
1364
1365
1366
1367
1368 function diaspora_comment($importer,$xml,$msg) {
1369
1370         $a = get_app();
1371         $guid = notags(unxmlify($xml->guid));
1372         $parent_guid = notags(unxmlify($xml->parent_guid));
1373         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1374         $target_type = notags(unxmlify($xml->target_type));
1375         $text = unxmlify($xml->text);
1376         $author_signature = notags(unxmlify($xml->author_signature));
1377
1378         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1379
1380         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1381         if(! $contact) {
1382                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1383                 return;
1384         }
1385
1386         if(! diaspora_post_allow($importer,$contact)) {
1387                 logger('diaspora_comment: Ignoring this author.');
1388                 return 202;
1389         }
1390
1391         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1392                 intval($importer['uid']),
1393                 dbesc($guid)
1394         );
1395         if(count($r)) {
1396                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1397                 return;
1398         }
1399
1400         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1401                 intval($importer['uid']),
1402                 dbesc($parent_guid)
1403         );
1404
1405         if(!count($r)) {
1406                 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1407
1408                 if (!$result) {
1409                         $person = find_diaspora_person_by_handle($diaspora_handle);
1410                         $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1411                 }
1412
1413                 if ($result) {
1414                         logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1415
1416                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1417                                 intval($importer['uid']),
1418                                 dbesc($parent_guid)
1419                         );
1420                 }
1421         }
1422
1423         if(! count($r)) {
1424                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1425                 return;
1426         }
1427         $parent_item = $r[0];
1428
1429
1430         /* How Diaspora performs comment signature checking:
1431
1432            - If an item has been sent by the comment author to the top-level post owner to relay on
1433              to the rest of the contacts on the top-level post, the top-level post owner should check
1434              the author_signature, then create a parent_author_signature before relaying the comment on
1435            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1436              check only the parent_author_signature. Basically, they trust that the top-level post
1437              owner has already verified the authenticity of anything he/she sends out
1438            - In either case, the signature that get checked is the signature created by the person
1439              who sent the salmon
1440         */
1441
1442         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1443         $key = $msg['key'];
1444
1445         if($parent_author_signature) {
1446                 // If a parent_author_signature exists, then we've received the comment
1447                 // relayed from the top-level post owner. There's no need to check the
1448                 // author_signature if the parent_author_signature is valid
1449
1450                 $parent_author_signature = base64_decode($parent_author_signature);
1451
1452                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1453                         logger('diaspora_comment: top-level owner verification failed.');
1454                         return;
1455                 }
1456         }
1457         else {
1458                 // If there's no parent_author_signature, then we've received the comment
1459                 // from the comment creator. In that case, the person is commenting on
1460                 // our post, so he/she must be a contact of ours and his/her public key
1461                 // should be in $msg['key']
1462
1463                 $author_signature = base64_decode($author_signature);
1464
1465                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1466                         logger('diaspora_comment: comment author verification failed.');
1467                         return;
1468                 }
1469         }
1470
1471         // Phew! Everything checks out. Now create an item.
1472
1473         // Find the original comment author information.
1474         // We need this to make sure we display the comment author
1475         // information (name and avatar) correctly.
1476         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1477                 $person = $contact;
1478         else {
1479                 $person = find_diaspora_person_by_handle($diaspora_handle);
1480
1481                 if(! is_array($person)) {
1482                         logger('diaspora_comment: unable to find author details');
1483                         return;
1484                 }
1485         }
1486
1487         $body = diaspora2bb($text);
1488         $message_id = $diaspora_handle . ':' . $guid;
1489
1490         $datarray = array();
1491
1492         $datarray['uid'] = $importer['uid'];
1493         $datarray['contact-id'] = $contact['id'];
1494         $datarray['type'] = 'remote-comment';
1495         $datarray['wall'] = $parent_item['wall'];
1496         $datarray['network']  = NETWORK_DIASPORA;
1497         $datarray['verb'] = ACTIVITY_POST;
1498         $datarray['gravity'] = GRAVITY_COMMENT;
1499         $datarray['guid'] = $guid;
1500         $datarray['uri'] = $message_id;
1501         $datarray['parent-uri'] = $parent_item['uri'];
1502
1503         // No timestamps for comments? OK, we'll the use current time.
1504         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1505         $datarray['private'] = $parent_item['private'];
1506
1507         $datarray['owner-name'] = $parent_item['owner-name'];
1508         $datarray['owner-link'] = $parent_item['owner-link'];
1509         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1510
1511         $datarray['author-name'] = $person['name'];
1512         $datarray['author-link'] = $person['url'];
1513         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1514         $datarray['body'] = $body;
1515         $datarray["object"] = json_encode($xml);
1516         $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1517
1518         // We can't be certain what the original app is if the message is relayed.
1519         if(($parent_item['origin']) && (! $parent_author_signature))
1520                 $datarray['app']  = 'Diaspora';
1521
1522         DiasporaFetchGuid($datarray);
1523         $message_id = item_store($datarray);
1524
1525         $datarray['id'] = $message_id;
1526
1527         //if($message_id) {
1528                 //q("update item set plink = '%s' where id = %d",
1529                 //      //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1530                 //      dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1531                 //      intval($message_id)
1532                 //);
1533         //}
1534
1535         if(($parent_item['origin']) && (! $parent_author_signature)) {
1536                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1537                         intval($message_id),
1538                         dbesc($signed_data),
1539                         dbesc(base64_encode($author_signature)),
1540                         dbesc($diaspora_handle)
1541                 );
1542
1543                 // if the message isn't already being relayed, notify others
1544                 // the existence of parent_author_signature means the parent_author or owner
1545                 // is already relaying.
1546
1547                 proc_run('php','include/notifier.php','comment-import',$message_id);
1548         }
1549
1550         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1551                 dbesc($parent_item['uri']),
1552                 intval($importer['uid'])
1553         );
1554
1555         if(count($myconv)) {
1556                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1557
1558                 foreach($myconv as $conv) {
1559
1560                         // now if we find a match, it means we're in this conversation
1561
1562                         if(! link_compare($conv['author-link'],$importer_url))
1563                                 continue;
1564
1565                         require_once('include/enotify.php');
1566
1567                         $conv_parent = $conv['parent'];
1568
1569                         notification(array(
1570                                 'type'         => NOTIFY_COMMENT,
1571                                 'notify_flags' => $importer['notify-flags'],
1572                                 'language'     => $importer['language'],
1573                                 'to_name'      => $importer['username'],
1574                                 'to_email'     => $importer['email'],
1575                                 'uid'          => $importer['uid'],
1576                                 'item'         => $datarray,
1577                                 'link'             => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1578                                 'source_name'  => $datarray['author-name'],
1579                                 'source_link'  => $datarray['author-link'],
1580                                 'source_photo' => $datarray['author-avatar'],
1581                                 'verb'         => ACTIVITY_POST,
1582                                 'otype'        => 'item',
1583                                 'parent'       => $conv_parent,
1584                                 'parent_uri'   => $parent_uri
1585                         ));
1586
1587                         // only send one notification
1588                         break;
1589                 }
1590         }
1591         return;
1592 }
1593
1594
1595
1596
1597 function diaspora_conversation($importer,$xml,$msg) {
1598
1599         $a = get_app();
1600
1601         $guid = notags(unxmlify($xml->guid));
1602         $subject = notags(unxmlify($xml->subject));
1603         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1604         $participant_handles = notags(unxmlify($xml->participant_handles));
1605         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1606
1607         $parent_uri = $diaspora_handle . ':' . $guid;
1608  
1609         $messages = $xml->message;
1610
1611         if(! count($messages)) {
1612                 logger('diaspora_conversation: empty conversation');
1613                 return;
1614         }
1615
1616         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1617         if(! $contact) {
1618                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1619                 return;
1620         }
1621
1622         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1623                 logger('diaspora_conversation: Ignoring this author.');
1624                 return 202;
1625         }
1626
1627         $conversation = null;
1628
1629         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1630                 intval($importer['uid']),
1631                 dbesc($guid)
1632         );
1633         if(count($c))
1634                 $conversation = $c[0];
1635         else {
1636                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1637                         intval($importer['uid']),
1638                         dbesc($guid),
1639                         dbesc($diaspora_handle),
1640                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1641                         dbesc(datetime_convert()),
1642                         dbesc($subject),
1643                         dbesc($participant_handles)
1644                 );
1645                 if($r)
1646                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1647                 intval($importer['uid']),
1648             dbesc($guid)
1649         );
1650             if(count($c))
1651             $conversation = $c[0];
1652         }
1653         if(! $conversation) {
1654                 logger('diaspora_conversation: unable to create conversation.');
1655                 return;
1656         }
1657
1658         foreach($messages as $mesg) {
1659
1660                 $reply = 0;
1661
1662                 $msg_guid = notags(unxmlify($mesg->guid));
1663                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1664                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1665                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1666                 $msg_text = unxmlify($mesg->text);
1667                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1668                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1669                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1670                 if($msg_conversation_guid != $guid) {
1671                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1672                         continue;
1673                 }
1674
1675                 $body = diaspora2bb($msg_text);
1676                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1677
1678                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1679
1680                 $author_signature = base64_decode($msg_author_signature);
1681
1682                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1683                         $person = $contact;
1684                         $key = $msg['key'];
1685                 }
1686                 else {
1687                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1688
1689                         if(is_array($person) && x($person,'pubkey'))
1690                                 $key = $person['pubkey'];
1691                         else {
1692                                 logger('diaspora_conversation: unable to find author details');
1693                                 continue;
1694                         }
1695                 }
1696
1697                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1698                         logger('diaspora_conversation: verification failed.');
1699                         continue;
1700                 }
1701
1702                 if($msg_parent_author_signature) {
1703                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1704
1705                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1706
1707                         $key = $msg['key'];
1708
1709                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1710                                 logger('diaspora_conversation: owner verification failed.');
1711                                 continue;
1712                         }
1713                 }
1714
1715                 $r = q("select id from mail where `uri` = '%s' limit 1",
1716                         dbesc($message_id)
1717                 );
1718                 if(count($r)) {
1719                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1720                         continue;
1721                 }
1722
1723                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1724                         intval($importer['uid']),
1725                         dbesc($msg_guid),
1726                         intval($conversation['id']),
1727                         dbesc($person['name']),
1728                         dbesc($person['photo']),
1729                         dbesc($person['url']),
1730                         intval($contact['id']),
1731                         dbesc($subject),
1732                         dbesc($body),
1733                         0,
1734                         0,
1735                         dbesc($message_id),
1736                         dbesc($parent_uri),
1737                         dbesc($msg_created_at)
1738                 );
1739
1740                 q("update conv set updated = '%s' where id = %d",
1741                         dbesc(datetime_convert()),
1742                         intval($conversation['id'])
1743                 );
1744
1745                 require_once('include/enotify.php');
1746                 notification(array(
1747                         'type' => NOTIFY_MAIL,
1748                         'notify_flags' => $importer['notify-flags'],
1749                         'language' => $importer['language'],
1750                         'to_name' => $importer['username'],
1751                         'to_email' => $importer['email'],
1752                         'uid' =>$importer['uid'],
1753                         'item' => array('subject' => $subject, 'body' => $body),
1754                         'source_name' => $person['name'],
1755                         'source_link' => $person['url'],
1756                         'source_photo' => $person['thumb'],
1757                         'verb' => ACTIVITY_POST,
1758                         'otype' => 'mail'
1759                 ));
1760         }
1761
1762         return;
1763 }
1764
1765 function diaspora_message($importer,$xml,$msg) {
1766
1767         $a = get_app();
1768
1769         $msg_guid = notags(unxmlify($xml->guid));
1770         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1771         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1772         $msg_author_signature = notags(unxmlify($xml->author_signature));
1773         $msg_text = unxmlify($xml->text);
1774         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1775         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1776         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1777
1778         $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1779  
1780         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1781         if(! $contact) {
1782                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1783                 return;
1784         }
1785
1786         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1787                 logger('diaspora_message: Ignoring this author.');
1788                 return 202;
1789         }
1790
1791         $conversation = null;
1792
1793         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1794                 intval($importer['uid']),
1795                 dbesc($msg_conversation_guid)
1796         );
1797         if(count($c))
1798                 $conversation = $c[0];
1799         else {
1800                 logger('diaspora_message: conversation not available.');
1801                 return;
1802         }
1803
1804         $reply = 0;
1805
1806         $body = diaspora2bb($msg_text);
1807         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1808
1809         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1810
1811
1812         $author_signature = base64_decode($msg_author_signature);
1813
1814         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1815         if(is_array($person) && x($person,'pubkey'))
1816                 $key = $person['pubkey'];
1817         else {
1818                 logger('diaspora_message: unable to find author details');
1819                 return;
1820         }
1821
1822         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1823                 logger('diaspora_message: verification failed.');
1824                 return;
1825         }
1826
1827         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1828                 dbesc($message_id),
1829                 intval($importer['uid'])
1830         );
1831         if(count($r)) {
1832                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1833                 return;
1834         }
1835
1836         q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1837                 intval($importer['uid']),
1838                 dbesc($msg_guid),
1839                 intval($conversation['id']),
1840                 dbesc($person['name']),
1841                 dbesc($person['photo']),
1842                 dbesc($person['url']),
1843                 intval($contact['id']),
1844                 dbesc($conversation['subject']),
1845                 dbesc($body),
1846                 0,
1847                 1,
1848                 dbesc($message_id),
1849                 dbesc($parent_uri),
1850                 dbesc($msg_created_at)
1851         );
1852
1853         q("update conv set updated = '%s' where id = %d",
1854                 dbesc(datetime_convert()),
1855                 intval($conversation['id'])
1856         );
1857
1858         return;
1859 }
1860
1861
1862 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1863
1864         $a = get_app();
1865
1866         logger('diaspora_photo: init',LOGGER_DEBUG);
1867
1868         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1869
1870         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1871
1872         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1873
1874         $guid = notags(unxmlify($xml->guid));
1875
1876         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1877
1878         $public = notags(unxmlify($xml->public));
1879
1880         $created_at = notags(unxmlify($xml_created_at));
1881
1882         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1883
1884         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1885         if(! $contact) {
1886                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1887                 return;
1888         }
1889
1890         if(! diaspora_post_allow($importer,$contact)) {
1891                 logger('diaspora_photo: Ignoring this author.');
1892                 return 202;
1893         }
1894
1895         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1896                 intval($importer['uid']),
1897                 dbesc($status_message_guid)
1898         );
1899
1900 /*      deactivated by now since it can lead to multiplicated pictures in posts.
1901         if(!count($r)) {
1902                 $result = diaspora_store_by_guid($status_message_guid, $contact['url'], $importer['uid']);
1903
1904                 if (!$result) {
1905                         $person = find_diaspora_person_by_handle($diaspora_handle);
1906                         $result = diaspora_store_by_guid($status_message_guid, $person['url'], $importer['uid']);
1907                 }
1908
1909                 if ($result) {
1910                         logger("Fetched missing item ".$status_message_guid." - result: ".$result, LOGGER_DEBUG);
1911
1912                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1913                                 intval($importer['uid']),
1914                                 dbesc($status_message_guid)
1915                         );
1916                 }
1917         }
1918 */
1919         if(!count($r)) {
1920                 if($attempt <= 3) {
1921                         q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1922                            intval($importer['uid']),
1923                            dbesc(serialize($msg)),
1924                            intval($attempt + 1)
1925                         );
1926                 }
1927
1928                 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1929                 return;
1930         }
1931
1932         $parent_item = $r[0];
1933
1934         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1935
1936         $link_text = scale_external_images($link_text, true,
1937                                            array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1938
1939         if(strpos($parent_item['body'],$link_text) === false) {
1940                 $r = q("UPDATE `item` SET `body` = '%s', `visible` = 1 WHERE `id` = %d AND `uid` = %d",
1941                         dbesc($link_text . $parent_item['body']),
1942                         intval($parent_item['id']),
1943                         intval($parent_item['uid'])
1944                 );
1945                 update_thread($parent_item['id']);
1946         }
1947
1948         return;
1949 }
1950
1951
1952
1953
1954 function diaspora_like($importer,$xml,$msg) {
1955
1956         $a = get_app();
1957         $guid = notags(unxmlify($xml->guid));
1958         $parent_guid = notags(unxmlify($xml->parent_guid));
1959         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1960         $target_type = notags(unxmlify($xml->target_type));
1961         $positive = notags(unxmlify($xml->positive));
1962         $author_signature = notags(unxmlify($xml->author_signature));
1963
1964         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1965
1966         // likes on comments not supported here and likes on photos not supported by Diaspora
1967
1968 //      if($target_type !== 'Post')
1969 //              return;
1970
1971         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1972         if(! $contact) {
1973                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1974                 return;
1975         }
1976
1977         if(! diaspora_post_allow($importer,$contact)) {
1978                 logger('diaspora_like: Ignoring this author.');
1979                 return 202;
1980         }
1981
1982         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1983                 intval($importer['uid']),
1984                 dbesc($parent_guid)
1985         );
1986
1987         if(!count($r)) {
1988                 $result = diaspora_store_by_guid($parent_guid, $contact['url'], $importer['uid']);
1989
1990                 if (!$result) {
1991                         $person = find_diaspora_person_by_handle($diaspora_handle);
1992                         $result = diaspora_store_by_guid($parent_guid, $person['url'], $importer['uid']);
1993                 }
1994
1995                 if ($result) {
1996                         logger("Fetched missing item ".$parent_guid." - result: ".$result, LOGGER_DEBUG);
1997
1998                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1999                                 intval($importer['uid']),
2000                                 dbesc($parent_guid)
2001                         );
2002                 }
2003         }
2004
2005         if(! count($r)) {
2006                 logger('diaspora_like: parent item not found: ' . $guid);
2007                 return;
2008         }
2009
2010         $parent_item = $r[0];
2011
2012         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2013                 intval($importer['uid']),
2014                 dbesc($guid)
2015         );
2016         if(count($r)) {
2017                 if($positive === 'true') {
2018                         logger('diaspora_like: duplicate like: ' . $guid);
2019                         return;
2020                 }
2021                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
2022                 // It looks like "RelayableRetractions" are used for "unlike" instead
2023                 if($positive === 'false') {
2024                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
2025 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
2026                                 intval($r[0]['id']),
2027                                 intval($importer['uid'])
2028                         );*/
2029                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
2030                         //  send notification via proc_run()
2031                         return;
2032                 }
2033         }
2034         // Note: I don't think "Like" objects with positive = "false" are ever actually used
2035         // It looks like "RelayableRetractions" are used for "unlike" instead
2036         if($positive === 'false') {
2037                 logger('diaspora_like: received a like with positive set to "false"');
2038                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
2039                 return;
2040         }
2041
2042
2043         /* How Diaspora performs "like" signature checking:
2044
2045            - If an item has been sent by the like author to the top-level post owner to relay on
2046              to the rest of the contacts on the top-level post, the top-level post owner should check
2047              the author_signature, then create a parent_author_signature before relaying the like on
2048            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2049              check only the parent_author_signature. Basically, they trust that the top-level post
2050              owner has already verified the authenticity of anything he/she sends out
2051            - In either case, the signature that get checked is the signature created by the person
2052              who sent the salmon
2053         */
2054
2055         // Diaspora has changed the way they are signing the likes.
2056         // Just to make sure that we don't miss any likes we will check the old and the current way.
2057         $old_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
2058
2059         $signed_data = $positive . ';' . $guid . ';' . $target_type . ';' . $parent_guid . ';' . $diaspora_handle;
2060
2061         $key = $msg['key'];
2062
2063         if ($parent_author_signature) {
2064                 // If a parent_author_signature exists, then we've received the like
2065                 // relayed from the top-level post owner. There's no need to check the
2066                 // author_signature if the parent_author_signature is valid
2067
2068                 $parent_author_signature = base64_decode($parent_author_signature);
2069
2070                 if (!rsa_verify($signed_data,$parent_author_signature,$key,'sha256') AND
2071                         !rsa_verify($old_signed_data,$parent_author_signature,$key,'sha256')) {
2072
2073                         logger('diaspora_like: top-level owner verification failed.');
2074                         return;
2075                 }
2076         } else {
2077                 // If there's no parent_author_signature, then we've received the like
2078                 // from the like creator. In that case, the person is "like"ing
2079                 // our post, so he/she must be a contact of ours and his/her public key
2080                 // should be in $msg['key']
2081
2082                 $author_signature = base64_decode($author_signature);
2083
2084                 if (!rsa_verify($signed_data,$author_signature,$key,'sha256') AND
2085                         !rsa_verify($old_signed_data,$author_signature,$key,'sha256')) {
2086
2087                         logger('diaspora_like: like creator verification failed.');
2088                         return;
2089                 }
2090         }
2091
2092         // Phew! Everything checks out. Now create an item.
2093
2094         // Find the original comment author information.
2095         // We need this to make sure we display the comment author
2096         // information (name and avatar) correctly.
2097         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
2098                 $person = $contact;
2099         else {
2100                 $person = find_diaspora_person_by_handle($diaspora_handle);
2101
2102                 if(! is_array($person)) {
2103                         logger('diaspora_like: unable to find author details');
2104                         return;
2105                 }
2106         }
2107
2108         $uri = $diaspora_handle . ':' . $guid;
2109
2110         $activity = ACTIVITY_LIKE;
2111         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2112         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE );
2113         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2114         $body = $parent_item['body'];
2115
2116         $obj = <<< EOT
2117
2118         <object>
2119                 <type>$objtype</type>
2120                 <local>1</local>
2121                 <id>{$parent_item['uri']}</id>
2122                 <link>$link</link>
2123                 <title></title>
2124                 <content>$body</content>
2125         </object>
2126 EOT;
2127         $bodyverb = t('%1$s likes %2$s\'s %3$s');
2128
2129         $arr = array();
2130
2131         $arr['uri'] = $uri;
2132         $arr['uid'] = $importer['uid'];
2133         $arr['guid'] = $guid;
2134         $arr['network']  = NETWORK_DIASPORA;
2135         $arr['contact-id'] = $contact['id'];
2136         $arr['type'] = 'activity';
2137         $arr['wall'] = $parent_item['wall'];
2138         $arr['gravity'] = GRAVITY_LIKE;
2139         $arr['parent'] = $parent_item['id'];
2140         $arr['parent-uri'] = $parent_item['uri'];
2141
2142         $arr['owner-name'] = $parent_item['name'];
2143         $arr['owner-link'] = $parent_item['url'];
2144         //$arr['owner-avatar'] = $parent_item['thumb'];
2145         $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2146
2147         $arr['author-name'] = $person['name'];
2148         $arr['author-link'] = $person['url'];
2149         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2150
2151         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2152         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2153         //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2154         $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2155         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
2156
2157         $arr['app']  = 'Diaspora';
2158
2159         $arr['private'] = $parent_item['private'];
2160         $arr['verb'] = $activity;
2161         $arr['object-type'] = $objtype;
2162         $arr['object'] = $obj;
2163         $arr['visible'] = 1;
2164         $arr['unseen'] = 1;
2165         $arr['last-child'] = 0;
2166
2167         $message_id = item_store($arr);
2168
2169
2170         //if($message_id) {
2171         //      q("update item set plink = '%s' where id = %d",
2172         //              //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2173         //              dbesc($a->get_baseurl().'/display/'.$guid),
2174         //              intval($message_id)
2175         //      );
2176         //}
2177
2178         if(! $parent_author_signature) {
2179                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2180                         intval($message_id),
2181                         dbesc($signed_data),
2182                         dbesc(base64_encode($author_signature)),
2183                         dbesc($diaspora_handle)
2184                 );
2185         }
2186
2187         // if the message isn't already being relayed, notify others
2188         // the existence of parent_author_signature means the parent_author or owner
2189         // is already relaying. The parent_item['origin'] indicates the message was created on our system
2190
2191         if(($parent_item['origin']) && (! $parent_author_signature))
2192                 proc_run('php','include/notifier.php','comment-import',$message_id);
2193
2194         return;
2195 }
2196
2197 function diaspora_retraction($importer,$xml) {
2198
2199
2200         $guid = notags(unxmlify($xml->guid));
2201         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2202         $type = notags(unxmlify($xml->type));
2203
2204         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2205         if(! $contact)
2206                 return;
2207
2208         if($type === 'Person') {
2209                 require_once('include/Contact.php');
2210                 contact_remove($contact['id']);
2211         }
2212         elseif($type === 'Post') {
2213                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2214                         dbesc('guid'),
2215                         intval($importer['uid'])
2216                 );
2217                 if(count($r)) {
2218                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2219                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2220                                         dbesc(datetime_convert()),
2221                                         intval($r[0]['id'])
2222                                 );
2223                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2224                         }
2225                 }
2226         }
2227
2228         return 202;
2229         // NOTREACHED
2230 }
2231
2232 function diaspora_signed_retraction($importer,$xml,$msg) {
2233
2234
2235         $guid = notags(unxmlify($xml->target_guid));
2236         $diaspora_handle = notags(unxmlify($xml->sender_handle));
2237         $type = notags(unxmlify($xml->target_type));
2238         $sig = notags(unxmlify($xml->target_author_signature));
2239
2240         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2241
2242         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2243         if(! $contact) {
2244                 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2245                 return;
2246         }
2247
2248
2249         $signed_data = $guid . ';' . $type ;
2250         $key = $msg['key'];
2251
2252         /* How Diaspora performs relayable_retraction signature checking:
2253
2254            - If an item has been sent by the item author to the top-level post owner to relay on
2255              to the rest of the contacts on the top-level post, the top-level post owner checks
2256              the author_signature, then creates a parent_author_signature before relaying the item on
2257            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2258              check only the parent_author_signature. Basically, they trust that the top-level post
2259              owner has already verified the authenticity of anything he/she sends out
2260            - In either case, the signature that get checked is the signature created by the person
2261              who sent the salmon
2262         */
2263
2264         if($parent_author_signature) {
2265
2266                 $parent_author_signature = base64_decode($parent_author_signature);
2267
2268                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2269                         logger('diaspora_signed_retraction: top-level post owner verification failed');
2270                         return;
2271                 }
2272
2273         }
2274         else {
2275
2276                 $sig_decode = base64_decode($sig);
2277
2278                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2279                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2280                         return;
2281                 }
2282         }
2283
2284         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2285                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2286                         dbesc($guid),
2287                         intval($importer['uid'])
2288                 );
2289                 if(count($r)) {
2290                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2291                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2292                                         dbesc(datetime_convert()),
2293                                         dbesc(datetime_convert()),
2294                                         intval($r[0]['id'])
2295                                 );
2296                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2297
2298                                 // Now check if the retraction needs to be relayed by us
2299                                 //
2300                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2301                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2302                                 // The only item with `parent` and `id` as the parent id is the parent item.
2303                                 $p = q("select origin from item where parent = %d and id = %d limit 1",
2304                                         $r[0]['parent'],
2305                                         $r[0]['parent']
2306                                 );
2307                                 if(count($p)) {
2308                                         if(($p[0]['origin']) && (! $parent_author_signature)) {
2309                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2310                                                         $r[0]['id'],
2311                                                         dbesc($signed_data),
2312                                                         dbesc($sig),
2313                                                         dbesc($diaspora_handle)
2314                                                 );
2315
2316                                                 // the existence of parent_author_signature would have meant the parent_author or owner
2317                                                 // is already relaying.
2318                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
2319
2320                                                 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2321                                         }
2322                                 }
2323                         }
2324                 }
2325         }
2326         else
2327                 logger('diaspora_signed_retraction: unknown type: ' . $type);
2328
2329         return 202;
2330         // NOTREACHED
2331 }
2332
2333 function diaspora_profile($importer,$xml,$msg) {
2334
2335         $a = get_app();
2336         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2337
2338
2339         if($diaspora_handle != $msg['author']) {
2340                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2341                 return 202;
2342         }
2343
2344         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2345         if(! $contact)
2346                 return;
2347
2348         if($contact['blocked']) {
2349                 logger('diaspora_post: Ignoring this author.');
2350                 return 202;
2351         }
2352
2353         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2354         $image_url = unxmlify($xml->image_url);
2355         $birthday = unxmlify($xml->birthday);
2356         $location = diaspora2bb(unxmlify($xml->location));
2357         $about = diaspora2bb(unxmlify($xml->bio));
2358         $gender = unxmlify($xml->gender);
2359         $tags = unxmlify($xml->tag_string);
2360
2361         $tags = explode("#", $tags);
2362
2363         $keywords = array();
2364         foreach ($tags as $tag) {
2365                 $tag = trim(strtolower($tag));
2366                 if ($tag != "")
2367                         $keywords[] = $tag;
2368         }
2369
2370         $keywords = implode(", ", $keywords);
2371
2372         $handle_parts = explode("@", $diaspora_handle);
2373         if($name === '') {
2374                 $name = $handle_parts[0];
2375         }
2376
2377         if( preg_match("|^https?://|", $image_url) === 0) {
2378                 $image_url = "http://" . $handle_parts[1] . $image_url;
2379         }
2380
2381 /*      $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2382                 intval($importer['uid']),
2383                 intval($contact['id'])
2384         );
2385         $oldphotos = ((count($r)) ? $r : null);*/
2386
2387         require_once('include/Photo.php');
2388
2389         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2390
2391         // Generic birthday. We don't know the timezone. The year is irrelevant.
2392
2393         $birthday = str_replace('1000','1901',$birthday);
2394
2395         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2396
2397         // this is to prevent multiple birthday notifications in a single year
2398         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2399
2400         if(substr($birthday,5) === substr($contact['bd'],5))
2401                 $birthday = $contact['bd'];
2402
2403         // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2404         // Not doing this currently because D* protocol is scheduled for revision soon.
2405
2406         $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2407                 dbesc($name),
2408                 dbesc(datetime_convert()),
2409                 dbesc($images[0]),
2410                 dbesc($images[1]),
2411                 dbesc($images[2]),
2412                 dbesc(datetime_convert()),
2413                 dbesc($birthday),
2414                 dbesc($location),
2415                 dbesc($about),
2416                 dbesc($keywords),
2417                 dbesc($gender),
2418                 intval($contact['id']),
2419                 intval($importer['uid'])
2420         );
2421
2422         if (unxmlify($xml->searchable) == "true") {
2423                 require_once('include/socgraph.php');
2424                 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2425                         datetime_convert(), 2, $contact['id'], $importer['uid']);
2426         }
2427
2428         $profileurl = "";
2429         $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2430                         dbesc(normalise_link($contact['url'])));
2431
2432         if (count($author) == 0) {
2433                 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2434                         dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2435
2436                 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2437                         dbesc(normalise_link($contact['url'])));
2438         } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2439                 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2440                 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2441         }
2442
2443 /*      if($r) {
2444                 if($oldphotos) {
2445                         foreach($oldphotos as $ph) {
2446                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2447                                         intval($importer['uid']),
2448                                         intval($contact['id']),
2449                                         dbesc($ph['resource-id'])
2450                                 );
2451                         }
2452                 }
2453         }       */
2454
2455         return;
2456
2457 }
2458
2459 function diaspora_share($me,$contact) {
2460         $a = get_app();
2461         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2462         $theiraddr = $contact['addr'];
2463
2464         $tpl = get_markup_template('diaspora_share.tpl');
2465         $msg = replace_macros($tpl, array(
2466                 '$sender' => $myaddr,
2467                 '$recipient' => $theiraddr
2468         ));
2469
2470         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2471         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2472
2473         return(diaspora_transmit($owner,$contact,$slap, false));
2474 }
2475
2476 function diaspora_unshare($me,$contact) {
2477
2478         $a = get_app();
2479         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2480
2481         $tpl = get_markup_template('diaspora_retract.tpl');
2482         $msg = replace_macros($tpl, array(
2483                 '$guid'   => $me['guid'],
2484                 '$type'   => 'Person',
2485                 '$handle' => $myaddr
2486         ));
2487
2488         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2489         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2490
2491         return(diaspora_transmit($owner,$contact,$slap, false));
2492
2493 }
2494
2495
2496 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2497
2498         $a = get_app();
2499         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2500         $theiraddr = $contact['addr'];
2501
2502         $images = array();
2503
2504         $title = $item['title'];
2505         $body = $item['body'];
2506
2507 /*
2508         // We're trying to match Diaspora's split message/photo protocol but
2509         // all the photos are displayed on D* as links and not img's - even
2510         // though we're sending pretty much precisely what they send us when
2511         // doing the same operation.  
2512         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2513         // which seems to get through intact.
2514
2515         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2516         if($cnt) {
2517                 foreach($matches as $mtch) {
2518                         $detail = array();
2519                         $detail['str'] = $mtch[0];
2520                         $detail['path'] = dirname($mtch[1]) . '/';
2521                         $detail['file'] = basename($mtch[1]);
2522                         $detail['guid'] = $item['guid'];
2523                         $detail['handle'] = $myaddr;
2524                         $images[] = $detail;
2525                         $body = str_replace($detail['str'],$mtch[1],$body);
2526                 }
2527         }
2528 */
2529
2530         //if(strlen($title))
2531         //      $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2532
2533         // convert to markdown
2534         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2535         //$body = bb2diaspora($body);
2536
2537         // Adding the title
2538         if(strlen($title))
2539                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2540
2541         if($item['attach']) {
2542                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2543                 if(cnt) {
2544                         $body .= "\n" . t('Attachments:') . "\n";
2545                         foreach($matches as $mtch) {
2546                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2547                         }
2548                 }
2549         }
2550
2551
2552         $public = (($item['private']) ? 'false' : 'true');
2553
2554         require_once('include/datetime.php');
2555         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2556
2557         // Detect a share element and do a reshare
2558         // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2559         if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2560                 $tpl = get_markup_template('diaspora_reshare.tpl');
2561                 $msg = replace_macros($tpl, array(
2562                         '$root_handle' => xmlify($ret['root_handle']),
2563                         '$root_guid' => $ret['root_guid'],
2564                         '$guid' => $item['guid'],
2565                         '$handle' => xmlify($myaddr),
2566                         '$public' => $public,
2567                         '$created' => $created,
2568                         '$provider' => $item["app"]
2569                 ));
2570         } else {
2571                 $tpl = get_markup_template('diaspora_post.tpl');
2572                 $msg = replace_macros($tpl, array(
2573                         '$body' => $body,
2574                         '$guid' => $item['guid'],
2575                         '$handle' => xmlify($myaddr),
2576                         '$public' => $public,
2577                         '$created' => $created,
2578                         '$provider' => $item["app"]
2579                 ));
2580         }
2581
2582         logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2583
2584         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2585         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2586
2587         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2588
2589         logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2590
2591         if(count($images)) {
2592                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2593         }
2594
2595         return $return_code;
2596 }
2597
2598 function diaspora_is_reshare($body) {
2599         $body = trim($body);
2600
2601         // Skip if it isn't a pure repeated messages
2602         // Does it start with a share?
2603         if (strpos($body, "[share") > 0)
2604                 return(false);
2605
2606         // Does it end with a share?
2607         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2608                 return(false);
2609
2610         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2611         // Skip if there is no shared message in there
2612         if ($body == $attributes)
2613                 return(false);
2614
2615         $guid = "";
2616         preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2617         if ($matches[1] != "")
2618                 $guid = $matches[1];
2619
2620         preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2621         if ($matches[1] != "")
2622                 $guid = $matches[1];
2623
2624         if ($guid != "") {
2625                 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2626                         dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2627                 if ($r) {
2628                         $ret= array();
2629                         $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
2630                         $ret["root_guid"] = $guid;
2631                         return($ret);
2632                 }
2633         }
2634
2635         $profile = "";
2636         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2637         if ($matches[1] != "")
2638                 $profile = $matches[1];
2639
2640         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2641         if ($matches[1] != "")
2642                 $profile = $matches[1];
2643
2644         $ret= array();
2645
2646         $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2647         if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2648                 return(false);
2649
2650         $link = "";
2651         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2652         if ($matches[1] != "")
2653                 $link = $matches[1];
2654
2655         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2656         if ($matches[1] != "")
2657                 $link = $matches[1];
2658
2659         $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2660         if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2661                 return(false);
2662
2663         return($ret);
2664 }
2665
2666 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2667         $a = get_app();
2668         if(! count($images))
2669                 return;
2670         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2671
2672         $tpl = get_markup_template('diaspora_photo.tpl');
2673         foreach($images as $image) {
2674                 if(! stristr($image['path'],$mysite))
2675                         continue;
2676                 $resource = str_replace('.jpg','',$image['file']);
2677                 $resource = substr($resource,0,strpos($resource,'-'));
2678
2679                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2680                         dbesc($resource),
2681                         intval($owner['uid'])
2682                 );
2683                 if(! count($r))
2684                         continue;
2685                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2686                 $msg = replace_macros($tpl,array(
2687                         '$path' => xmlify($image['path']),
2688                         '$filename' => xmlify($image['file']),
2689                         '$msg_guid' => xmlify($image['guid']),
2690                         '$guid' => xmlify($r[0]['guid']),
2691                         '$handle' => xmlify($image['handle']),
2692                         '$public' => xmlify($public),
2693                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2694                 ));
2695
2696
2697                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2698                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2699                 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2700
2701                 diaspora_transmit($owner,$contact,$slap,$public_batch);
2702         }
2703
2704 }
2705
2706 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2707
2708         $a = get_app();
2709         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2710 //      $theiraddr = $contact['addr'];
2711
2712         // Diaspora doesn't support threaded comments, but some
2713         // versions of Diaspora (i.e. Diaspora-pistos) support
2714         // likes on comments
2715         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2716                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2717                         dbesc($item['thr-parent'])
2718                       );
2719         }
2720         else {
2721                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2722                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2723                 // The only item with `parent` and `id` as the parent id is the parent item.
2724                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2725                         intval($item['parent']),
2726                         intval($item['parent'])
2727                 );
2728         }
2729         if(count($p))
2730                 $parent = $p[0];
2731         else
2732                 return;
2733
2734         if($item['verb'] === ACTIVITY_LIKE) {
2735                 $tpl = get_markup_template('diaspora_like.tpl');
2736                 $like = true;
2737                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2738 //              $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2739 //              $positive = (($item['deleted']) ? 'false' : 'true');
2740                 $positive = 'true';
2741
2742                 if(($item['deleted']))
2743                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2744         }
2745         else {
2746                 $tpl = get_markup_template('diaspora_comment.tpl');
2747                 $like = false;
2748         }
2749
2750         $text = html_entity_decode(bb2diaspora($item['body']));
2751
2752         // sign it
2753
2754         if($like)
2755                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2756         else
2757                 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2758
2759         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2760
2761         $msg = replace_macros($tpl,array(
2762                 '$guid' => xmlify($item['guid']),
2763                 '$parent_guid' => xmlify($parent['guid']),
2764                 '$target_type' =>xmlify($target_type),
2765                 '$authorsig' => xmlify($authorsig),
2766                 '$body' => xmlify($text),
2767                 '$positive' => xmlify($positive),
2768                 '$handle' => xmlify($myaddr)
2769         ));
2770
2771         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2772
2773         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2774         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2775
2776         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2777 }
2778
2779
2780 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2781
2782
2783         $a = get_app();
2784         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2785 //      $theiraddr = $contact['addr'];
2786
2787         $body = $item['body'];
2788         $text = html_entity_decode(bb2diaspora($body));
2789
2790         // Diaspora doesn't support threaded comments, but some
2791         // versions of Diaspora (i.e. Diaspora-pistos) support
2792         // likes on comments
2793         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2794                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2795                         dbesc($item['thr-parent'])
2796                       );
2797         }
2798         else {
2799                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2800                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2801                 // The only item with `parent` and `id` as the parent id is the parent item.
2802                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2803                        intval($item['parent']),
2804                        intval($item['parent'])
2805                       );
2806         }
2807         if(count($p))
2808                 $parent = $p[0];
2809         else
2810                 return;
2811
2812         $like = false;
2813         $relay_retract = false;
2814         $sql_sign_id = 'iid';
2815         if( $item['deleted']) {
2816                 $relay_retract = true;
2817
2818                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2819
2820                 $sql_sign_id = 'retract_iid';
2821                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2822         }
2823         elseif($item['verb'] === ACTIVITY_LIKE) {
2824                 $like = true;
2825
2826                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2827 //              $positive = (($item['deleted']) ? 'false' : 'true');
2828                 $positive = 'true';
2829
2830                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2831         }
2832         else { // item is a comment
2833                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2834         }
2835
2836
2837         // fetch the original signature if the relayable was created by a Diaspora
2838         // or DFRN user. Relayables for other networks are not supported.
2839
2840 /*      $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2841                 intval($item['id'])
2842         );
2843         if(count($r)) { 
2844                 $orig_sign = $r[0];
2845                 $signed_text = $orig_sign['signed_text'];
2846                 $authorsig = $orig_sign['signature'];
2847                 $handle = $orig_sign['signer'];
2848         }
2849         else {
2850
2851                 // Author signature information (for likes, comments, and retractions of likes or comments,
2852                 // whether from Diaspora or Friendica) must be placed in the `sign` table before this 
2853                 // function is called
2854                 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2855                 return;
2856         }*/
2857
2858         /* Since the author signature is only checked by the parent, not by the relay recipients,
2859          * I think it may not be necessary for us to do so much work to preserve all the original
2860          * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2861          * Let's just generate that and forget about all the original author signature stuff.
2862          *
2863          * Note: this might be more of an problem if we want to support likes on comments for older
2864          * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2865          * doing that, let's ignore it for now.
2866          *
2867          * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2868          * been done yet
2869          */
2870
2871         $handle = diaspora_handle_from_contact($item['contact-id']);
2872         if(! $handle)
2873                 return;
2874
2875
2876         if($relay_retract)
2877                 $sender_signed_text = $item['guid'] . ';' . $target_type;
2878         elseif($like)
2879                 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2880         else
2881                 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2882
2883         // Sign the relayable with the top-level owner's signature
2884         //
2885         // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2886         // stored in the database, because that provides the best chance that Diaspora will
2887         // be able to reconstruct the signed text the same way we did. This is particularly a
2888         // concern for the comment, whose signed text includes the text of the comment. The
2889         // smallest change in the text of the comment, including removing whitespace, will
2890         // make the signature verification fail. Since we translate from BB code to Diaspora's
2891         // markup at the top of this function, which is AFTER we placed the original $signed_text
2892         // in the database, it's hazardous to trust the original $signed_text.
2893
2894         $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2895
2896         $msg = replace_macros($tpl,array(
2897                 '$guid' => xmlify($item['guid']),
2898                 '$parent_guid' => xmlify($parent['guid']),
2899                 '$target_type' =>xmlify($target_type),
2900                 '$authorsig' => xmlify($authorsig),
2901                 '$parentsig' => xmlify($parentauthorsig),
2902                 '$body' => xmlify($text),
2903                 '$positive' => xmlify($positive),
2904                 '$handle' => xmlify($handle)
2905         ));
2906
2907         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2908
2909
2910         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2911         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2912
2913         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2914
2915 }
2916
2917
2918
2919 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2920
2921         $a = get_app();
2922         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2923
2924         // Check whether the retraction is for a top-level post or whether it's a relayable
2925         if( $item['uri'] !== $item['parent-uri'] ) {
2926
2927                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2928                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2929         }
2930         else {
2931
2932                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2933                 $target_type = 'StatusMessage';
2934         }
2935
2936         $signed_text = $item['guid'] . ';' . $target_type;
2937
2938         $msg = replace_macros($tpl, array(
2939                 '$guid'   => xmlify($item['guid']),
2940                 '$type'   => xmlify($target_type),
2941                 '$handle' => xmlify($myaddr),
2942                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2943         ));
2944
2945         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2946         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2947
2948         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2949 }
2950
2951 function diaspora_send_mail($item,$owner,$contact) {
2952
2953         $a = get_app();
2954         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2955
2956         $r = q("select * from conv where id = %d and uid = %d limit 1",
2957                 intval($item['convid']),
2958                 intval($item['uid'])
2959         );
2960
2961         if(! count($r)) {
2962                 logger('diaspora_send_mail: conversation not found.');
2963                 return;
2964         }
2965         $cnv = $r[0];
2966
2967         $conv = array(
2968                 'guid' => xmlify($cnv['guid']),
2969                 'subject' => xmlify($cnv['subject']),
2970                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2971                 'diaspora_handle' => xmlify($cnv['creator']),
2972                 'participant_handles' => xmlify($cnv['recips'])
2973         );
2974
2975         $body = bb2diaspora($item['body']);
2976         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2977
2978         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';' 
2979                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2980
2981         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2982
2983         $msg = array(
2984                 'guid' => xmlify($item['guid']),
2985                 'parent_guid' => xmlify($cnv['guid']),
2986                 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2987                 'author_signature' => xmlify($sig),
2988                 'text' => xmlify($body),
2989                 'created_at' => xmlify($created),
2990                 'diaspora_handle' => xmlify($myaddr),
2991                 'conversation_guid' => xmlify($cnv['guid'])
2992         );
2993
2994         if($item['reply']) {
2995                 $tpl = get_markup_template('diaspora_message.tpl');
2996                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2997         }
2998         else {
2999                 $conv['messages'] = array($msg);
3000                 $tpl = get_markup_template('diaspora_conversation.tpl');
3001                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
3002         }
3003
3004         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
3005
3006         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
3007         //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
3008
3009         return(diaspora_transmit($owner,$contact,$slap,false));
3010
3011
3012 }
3013
3014 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
3015
3016         $enabled = intval(get_config('system','diaspora_enabled'));
3017         if(! $enabled) {
3018                 return 200;
3019         }
3020
3021         $a = get_app();
3022         $logid = random_string(4);
3023         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
3024         if(! $dest_url) {
3025                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
3026                 return 0;
3027         } 
3028
3029         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
3030
3031         if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
3032                 $return_code = 0;
3033         }
3034         else {
3035                 if (!intval(get_config('system','diaspora_test'))) {
3036                         post_url($dest_url . '/', $slap);
3037                         $return_code = $a->get_curl_code();
3038                 } else {
3039                         logger('diaspora_transmit: test_mode');
3040                         return 200;
3041                 }
3042         }
3043
3044         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
3045
3046         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
3047                 logger('diaspora_transmit: queue message');
3048
3049                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
3050                         intval($contact['id']),
3051                         dbesc(NETWORK_DIASPORA),
3052                         dbesc($slap),
3053                         intval($public_batch)
3054                 );
3055                 if(count($r)) {
3056                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
3057                 }
3058                 else {
3059                         // queue message for redelivery
3060                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
3061                 }
3062         }
3063
3064
3065         return(($return_code) ? $return_code : (-1));
3066 }