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