]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Remove the old hashtag functions, change it to the new functionality.
[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']) && intval(get_pconfig($importer['uid'],'system','post_newfriend'))) {
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         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
837         if($cnt) {
838                 foreach($matches as $mtch) {
839                         if(strlen($str_tags))
840                                 $str_tags .= ',';
841                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
842                 }
843         }
844
845         $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
846
847         $datarray['uid'] = $importer['uid'];
848         $datarray['contact-id'] = $contact['id'];
849         $datarray['wall'] = 0;
850         $datarray['network'] = NETWORK_DIASPORA;
851         $datarray['verb'] = ACTIVITY_POST;
852         $datarray['guid'] = $guid;
853         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
854         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
855         $datarray['private'] = $private;
856         $datarray['parent'] = 0;
857         $datarray['plink'] = $plink;
858         $datarray['owner-name'] = $contact['name'];
859         $datarray['owner-link'] = $contact['url'];
860         //$datarray['owner-avatar'] = $contact['thumb'];
861         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
862         $datarray['author-name'] = $contact['name'];
863         $datarray['author-link'] = $contact['url'];
864         $datarray['author-avatar'] = $contact['thumb'];
865         $datarray['body'] = $body;
866         $datarray['tag'] = $str_tags;
867         $datarray['app']  = 'Diaspora';
868
869         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
870
871         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
872
873         DiasporaFetchGuid($datarray);
874         $message_id = item_store($datarray);
875
876         return;
877
878 }
879
880 function DiasporaFetchGuid($item) {
881         preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
882                 function ($match) use ($item){
883                         return(DiasporaFetchGuidSub($match, $item));
884                 },$item["body"]);
885 }
886
887 function DiasporaFetchGuidSub($match, $item) {
888         $a = get_app();
889
890         $author = parse_url($item["author-link"]);
891         $authorserver = $author["scheme"]."://".$author["host"];
892
893         $owner = parse_url($item["owner-link"]);
894         $ownerserver = $owner["scheme"]."://".$owner["host"];
895
896         if (!diaspora_store_by_guid($match[1], $authorserver))
897                 diaspora_store_by_guid($match[1], $ownerserver);
898 }
899
900 function diaspora_store_by_guid($guid, $server) {
901         require_once("include/Contact.php");
902
903         logger("fetching item ".$guid." from ".$server, LOGGER_DEBUG);
904
905         $item = diaspora_fetch_message($guid, $server);
906
907         if (!$item)
908                 return false;
909
910         $body = $item["body"];
911         $str_tags = $item["tag"];
912         $app = $item["app"];
913         $created = $item["created"];
914         $author = $item["author"];
915         $guid = $item["guid"];
916         $private = $item["private"];
917
918         $message_id = $author.':'.$guid;
919         $r = q("SELECT `id` FROM `item` WHERE `uid` = 0 AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
920                 dbesc($message_id),
921                 dbesc($guid)
922         );
923         if(count($r))
924                 return $r[0]["id"];
925
926         $person = find_diaspora_person_by_handle($author);
927
928         $datarray = array();
929         $datarray['uid'] = 0;
930         $datarray['contact-id'] = get_contact($person['url'], 0);
931         $datarray['wall'] = 0;
932         $datarray['network']  = NETWORK_DIASPORA;
933         $datarray['guid'] = $guid;
934         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
935         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
936         $datarray['private'] = $private;
937         $datarray['parent'] = 0;
938         $datarray['plink'] = 'https://'.substr($author,strpos($author,'@')+1).'/posts/'.$guid;
939         $datarray['author-name'] = $person['name'];
940         $datarray['author-link'] = $person['url'];
941         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
942         $datarray['owner-name'] = $datarray['author-name'];
943         $datarray['owner-link'] = $datarray['author-link'];
944         $datarray['owner-avatar'] = $datarray['author-avatar'];
945         $datarray['body'] = $body;
946         $datarray['tag'] = $str_tags;
947         $datarray['app']  = $app;
948         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
949
950         DiasporaFetchGuid($datarray);
951         $message_id = item_store($datarray);
952
953         // To-Do:
954         // Looking if there is some subscribe mechanism in Diaspora to get all comments for this post
955
956         return $message_id;
957 }
958
959 function diaspora_fetch_message($guid, $server, $level = 0) {
960
961         if ($level > 5)
962                 return false;
963
964         $a = get_app();
965
966         // This will not work if the server is not a Diaspora server
967         $source_url = $server.'/p/'.$guid.'.xml';
968         $x = fetch_url($source_url);
969         if(!$x)
970                 return false;
971
972         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
973         $source_xml = parse_xml_string($x,false);
974
975         $item = array();
976         $item["app"] = 'Diaspora';
977         $item["guid"] = $guid;
978         $body = "";
979
980         if ($source_xml->post->status_message->created_at)
981                 $item["created"] = unxmlify($source_xml->post->status_message->created_at);
982
983         if ($source_xml->post->status_message->provider_display_name)
984                 $item["app"] = unxmlify($source_xml->post->status_message->provider_display_name);
985
986         if ($source_xml->post->status_message->diaspora_handle)
987                 $item["author"] = unxmlify($source_xml->post->status_message->diaspora_handle);
988
989         if ($source_xml->post->status_message->guid)
990                 $item["guid"] = unxmlify($source_xml->post->status_message->guid);
991
992         $item["private"] = (unxmlify($source_xml->post->status_message->public) == 'false');
993
994         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
995                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
996                 $body = scale_external_images($body,false);
997         } elseif($source_xml->post->asphoto->image_url) {
998                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
999                 $body = scale_external_images($body);
1000         } elseif($source_xml->post->status_message) {
1001                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
1002
1003                 // Checking for embedded pictures
1004                 if($source_xml->post->status_message->photo->remote_photo_path AND
1005                         $source_xml->post->status_message->photo->remote_photo_name) {
1006
1007                         $remote_photo_path = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_path));
1008                         $remote_photo_name = notags(unxmlify($source_xml->post->status_message->photo->remote_photo_name));
1009
1010                         $body = '[img]'.$remote_photo_path.$remote_photo_name.'[/img]'."\n".$body;
1011
1012                         logger('embedded picture link found: '.$body, LOGGER_DEBUG);
1013                 }
1014
1015                 $body = scale_external_images($body);
1016
1017                 // Add OEmbed and other information to the body
1018                 $body = add_page_info_to_body($body, false, true);
1019         } elseif($source_xml->post->reshare) {
1020                 // Reshare of a reshare
1021                 return diaspora_fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
1022         } else {
1023                 // Maybe it is a reshare of a photo that will be delivered at a later time (testing)
1024                 logger('no content found: '.print_r($source_xml,true));
1025                 $body = "";
1026         }
1027
1028         if ($body == "")
1029                 return false;
1030
1031         $item["tag"] = '';
1032         $item["body"] = $body;
1033
1034         return $item;
1035 }
1036
1037 function diaspora_reshare($importer,$xml,$msg) {
1038
1039         logger('diaspora_reshare: init: ' . print_r($xml,true));
1040
1041         $a = get_app();
1042         $guid = notags(unxmlify($xml->guid));
1043         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1044
1045
1046         if($diaspora_handle != $msg['author']) {
1047                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1048                 return 202;
1049         }
1050
1051         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1052         if(! $contact)
1053                 return;
1054
1055         if(! diaspora_post_allow($importer,$contact)) {
1056                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
1057                 return 202;
1058         }
1059
1060         $message_id = $diaspora_handle . ':' . $guid;
1061         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1062                 intval($importer['uid']),
1063                 dbesc($message_id),
1064                 dbesc($guid)
1065         );
1066         if(count($r)) {
1067                 logger('diaspora_reshare: message exists: ' . $guid);
1068                 return;
1069         }
1070
1071         $orig_author = notags(unxmlify($xml->root_diaspora_id));
1072         $orig_guid = notags(unxmlify($xml->root_guid));
1073
1074         $create_original_post = false;
1075
1076         // Do we already have this item?
1077         $r = q("SELECT `body`, `tag`, `app`, `author-link`, `plink` FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1078                 dbesc($orig_guid),
1079                 dbesc(NETWORK_DIASPORA)
1080         );
1081         if(count($r)) {
1082                 logger('reshared message '.orig_guid." reshared by ".$guid.' already exists on system: '.$orig_url);
1083
1084                 // Maybe it is already a reshared item?
1085                 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1086                 require_once('include/api.php');
1087                 if (api_share_as_retweet($r[0]))
1088                         $r = array();
1089                 else
1090                         $orig_url = $a->get_baseurl().'/display/'.$orig_guid;
1091         }
1092
1093         if (!count($r)) {
1094                 $body = "";
1095                 $str_tags = "";
1096                 $app = "";
1097
1098                 $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1099
1100                 $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1101                 logger('1st try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1102                 $item = diaspora_fetch_message($orig_guid, $server);
1103
1104                 if (!$item) {
1105                         $server = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1106                         logger('2nd try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1107                         $item = diaspora_fetch_message($orig_guid, $server);
1108                 }
1109                 if (!$item) {
1110                         $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1111                         logger('3rd try: reshared message '.$orig_guid." reshared by ".$guid.' will be fetched from original server: '.$server);
1112                         $item = diaspora_fetch_message($orig_guid, $server);
1113                 }
1114                 if (!$item) {
1115                         $server = 'http://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1);
1116                         logger('4th try: reshared message '.$orig_guid." reshared by ".$guid." will be fetched from sharer's server: ".$server);
1117                         $item = diaspora_fetch_message($orig_guid, $server);
1118                 }
1119
1120                 if ($item) {
1121                         $body = $item["body"];
1122                         $str_tags = $item["tag"];
1123                         $app = $item["app"];
1124                         $orig_created = $item["created"];
1125                         $orig_author = $item["author"];
1126                         $orig_guid = $item["guid"];
1127                         $create_original_post = ($body != "");
1128                         $orig_url = $a->get_baseurl()."/display/".$orig_guid;
1129                 }
1130         }
1131
1132         $person = find_diaspora_person_by_handle($orig_author);
1133
1134         // allocate a guid on our system - we aren't fixing any collisions.
1135         // we're ignoring them
1136
1137         $g = q("select * from guid where guid = '%s' limit 1",
1138                 dbesc($guid)
1139         );
1140         if(! count($g)) {
1141                 q("insert into guid ( guid ) values ( '%s' )",
1142                         dbesc($guid)
1143                 );
1144         }
1145
1146         $created = unxmlify($xml->created_at);
1147         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1148
1149         $datarray = array();
1150
1151         $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1152
1153         $datarray['uid'] = $importer['uid'];
1154         $datarray['contact-id'] = $contact['id'];
1155         $datarray['wall'] = 0;
1156         $datarray['network']  = NETWORK_DIASPORA;
1157         $datarray['guid'] = $guid;
1158         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1159         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1160         $datarray['private'] = $private;
1161         $datarray['parent'] = 0;
1162         $datarray['plink'] = $plink;
1163         $datarray['owner-name'] = $contact['name'];
1164         $datarray['owner-link'] = $contact['url'];
1165         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1166         if (!intval(get_config('system','wall-to-wall_share'))) {
1167                 $prefix = "[share author='".str_replace(array("'", "[", "]"), array("&#x27;", "&#x5B;", "&#x5D;"),$person['name']).
1168                                 "' profile='".$person['url'].
1169                                 "' avatar='".((x($person,'thumb')) ? $person['thumb'] : $person['photo']).
1170                                 "' link='".str_replace(array("'", "[", "]"), array("&#x27;", "&#x5B;", "&#x5D;"),$orig_url)."']";
1171                 $datarray['author-name'] = $contact['name'];
1172                 $datarray['author-link'] = $contact['url'];
1173                 $datarray['author-avatar'] = $contact['thumb'];
1174                 $datarray['body'] = $prefix.$body."[/share]";
1175         } else {
1176                 // Let reshared messages look like wall-to-wall posts
1177                 $datarray['author-name'] = $person['name'];
1178                 $datarray['author-link'] = $person['url'];
1179                 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1180                 $datarray['body'] = $body;
1181         }
1182
1183         $datarray['tag'] = $str_tags;
1184         $datarray['app']  = $app;
1185
1186         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible. (testing)
1187         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
1188
1189         // Store the original item of a reshare
1190         if ($create_original_post) {
1191                 require_once("include/Contact.php");
1192
1193                 $datarray2 = $datarray;
1194
1195                 $datarray2['uid'] = 0;
1196                 $datarray2['contact-id'] = get_contact($person['url'], 0);
1197                 $datarray2['guid'] = $orig_guid;
1198                 $datarray2['uri'] = $datarray2['parent-uri'] = $orig_author.':'.$orig_guid;
1199                 $datarray2['changed'] = $datarray2['created'] = $datarray2['edited'] = datetime_convert('UTC','UTC',$orig_created);
1200                 $datarray2['plink'] = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
1201
1202                 $datarray2['author-name'] = $person['name'];
1203                 $datarray2['author-link'] = $person['url'];
1204                 $datarray2['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1205                 $datarray2['owner-name'] = $datarray2['author-name'];
1206                 $datarray2['owner-link'] = $datarray2['author-link'];
1207                 $datarray2['owner-avatar'] = $datarray2['author-avatar'];
1208                 $datarray2['body'] = $body;
1209
1210                 DiasporaFetchGuid($datarray2);
1211                 $message_id = item_store($datarray2);
1212
1213                 logger("Store original item ".$orig_guid." under message id ".$message_id);
1214         }
1215
1216         DiasporaFetchGuid($datarray);
1217         $message_id = item_store($datarray);
1218
1219         return;
1220
1221 }
1222
1223
1224 function diaspora_asphoto($importer,$xml,$msg) {
1225         logger('diaspora_asphoto called');
1226
1227         $a = get_app();
1228         $guid = notags(unxmlify($xml->guid));
1229         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1230
1231         if($diaspora_handle != $msg['author']) {
1232                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1233                 return 202;
1234         }
1235
1236         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1237         if(! $contact)
1238                 return;
1239
1240         if(! diaspora_post_allow($importer,$contact)) {
1241                 logger('diaspora_asphoto: Ignoring this author.');
1242                 return 202;
1243         }
1244
1245         $message_id = $diaspora_handle . ':' . $guid;
1246         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1247                 intval($importer['uid']),
1248                 dbesc($message_id),
1249                 dbesc($guid)
1250         );
1251         if(count($r)) {
1252                 logger('diaspora_asphoto: message exists: ' . $guid);
1253                 return;
1254         }
1255
1256         // allocate a guid on our system - we aren't fixing any collisions.
1257         // we're ignoring them
1258
1259         $g = q("select * from guid where guid = '%s' limit 1",
1260                 dbesc($guid)
1261         );
1262         if(! count($g)) {
1263                 q("insert into guid ( guid ) values ( '%s' )",
1264                         dbesc($guid)
1265                 );
1266         }
1267
1268         $created = unxmlify($xml->created_at);
1269         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1270
1271         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1272                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1273                 $body = scale_external_images($body,false);
1274         }
1275         elseif($xml->image_url) {
1276                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1277                 $body = scale_external_images($body);
1278         }
1279         else {
1280                 logger('diaspora_asphoto: no photo url found.');
1281                 return;
1282         }
1283
1284         $plink = 'https://'.substr($diaspora_handle,strpos($diaspora_handle,'@')+1).'/posts/'.$guid;
1285
1286         $datarray = array();
1287
1288         $datarray['uid'] = $importer['uid'];
1289         $datarray['contact-id'] = $contact['id'];
1290         $datarray['wall'] = 0;
1291         $datarray['network']  = NETWORK_DIASPORA;
1292         $datarray['guid'] = $guid;
1293         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1294         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1295         $datarray['private'] = $private;
1296         $datarray['parent'] = 0;
1297         $datarray['plink'] = $plink;
1298         $datarray['owner-name'] = $contact['name'];
1299         $datarray['owner-link'] = $contact['url'];
1300         //$datarray['owner-avatar'] = $contact['thumb'];
1301         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1302         $datarray['author-name'] = $contact['name'];
1303         $datarray['author-link'] = $contact['url'];
1304         $datarray['author-avatar'] = $contact['thumb'];
1305         $datarray['body'] = $body;
1306
1307         $datarray['app']  = 'Diaspora/Cubbi.es';
1308
1309         DiasporaFetchGuid($datarray);
1310         $message_id = item_store($datarray);
1311
1312         //if($message_id) {
1313         //      q("update item set plink = '%s' where id = %d",
1314         //              dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1315         //              intval($message_id)
1316         //      );
1317         //}
1318
1319         return;
1320
1321 }
1322
1323
1324
1325
1326
1327
1328 function diaspora_comment($importer,$xml,$msg) {
1329
1330         $a = get_app();
1331         $guid = notags(unxmlify($xml->guid));
1332         $parent_guid = notags(unxmlify($xml->parent_guid));
1333         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1334         $target_type = notags(unxmlify($xml->target_type));
1335         $text = unxmlify($xml->text);
1336         $author_signature = notags(unxmlify($xml->author_signature));
1337
1338         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1339
1340         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1341         if(! $contact) {
1342                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1343                 return;
1344         }
1345
1346         if(! diaspora_post_allow($importer,$contact)) {
1347                 logger('diaspora_comment: Ignoring this author.');
1348                 return 202;
1349         }
1350
1351         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1352                 intval($importer['uid']),
1353                 dbesc($guid)
1354         );
1355         if(count($r)) {
1356                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1357                 return;
1358         }
1359
1360         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1361                 intval($importer['uid']),
1362                 dbesc($parent_guid)
1363         );
1364         if(! count($r)) {
1365                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1366                 return;
1367         }
1368         $parent_item = $r[0];
1369
1370
1371         /* How Diaspora performs comment signature checking:
1372
1373            - If an item has been sent by the comment author to the top-level post owner to relay on
1374              to the rest of the contacts on the top-level post, the top-level post owner should check
1375              the author_signature, then create a parent_author_signature before relaying the comment on
1376            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1377              check only the parent_author_signature. Basically, they trust that the top-level post
1378              owner has already verified the authenticity of anything he/she sends out
1379            - In either case, the signature that get checked is the signature created by the person
1380              who sent the salmon
1381         */
1382
1383         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1384         $key = $msg['key'];
1385
1386         if($parent_author_signature) {
1387                 // If a parent_author_signature exists, then we've received the comment
1388                 // relayed from the top-level post owner. There's no need to check the
1389                 // author_signature if the parent_author_signature is valid
1390
1391                 $parent_author_signature = base64_decode($parent_author_signature);
1392
1393                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1394                         logger('diaspora_comment: top-level owner verification failed.');
1395                         return;
1396                 }
1397         }
1398         else {
1399                 // If there's no parent_author_signature, then we've received the comment
1400                 // from the comment creator. In that case, the person is commenting on
1401                 // our post, so he/she must be a contact of ours and his/her public key
1402                 // should be in $msg['key']
1403
1404                 $author_signature = base64_decode($author_signature);
1405
1406                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1407                         logger('diaspora_comment: comment author verification failed.');
1408                         return;
1409                 }
1410         }
1411
1412         // Phew! Everything checks out. Now create an item.
1413
1414         // Find the original comment author information.
1415         // We need this to make sure we display the comment author
1416         // information (name and avatar) correctly.
1417         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1418                 $person = $contact;
1419         else {
1420                 $person = find_diaspora_person_by_handle($diaspora_handle);
1421
1422                 if(! is_array($person)) {
1423                         logger('diaspora_comment: unable to find author details');
1424                         return;
1425                 }
1426         }
1427
1428         $body = diaspora2bb($text);
1429         $message_id = $diaspora_handle . ':' . $guid;
1430
1431         $datarray = array();
1432
1433         $datarray['uid'] = $importer['uid'];
1434         $datarray['contact-id'] = $contact['id'];
1435         $datarray['type'] = 'remote-comment';
1436         $datarray['wall'] = $parent_item['wall'];
1437         $datarray['network']  = NETWORK_DIASPORA;
1438         $datarray['verb'] = ACTIVITY_POST;
1439         $datarray['gravity'] = GRAVITY_COMMENT;
1440         $datarray['guid'] = $guid;
1441         $datarray['uri'] = $message_id;
1442         $datarray['parent-uri'] = $parent_item['uri'];
1443
1444         // No timestamps for comments? OK, we'll the use current time.
1445         $datarray['changed'] = $datarray['created'] = $datarray['edited'] = datetime_convert();
1446         $datarray['private'] = $parent_item['private'];
1447
1448         $datarray['owner-name'] = $parent_item['owner-name'];
1449         $datarray['owner-link'] = $parent_item['owner-link'];
1450         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1451
1452         $datarray['author-name'] = $person['name'];
1453         $datarray['author-link'] = $person['url'];
1454         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1455         $datarray['body'] = $body;
1456
1457         // We can't be certain what the original app is if the message is relayed.
1458         if(($parent_item['origin']) && (! $parent_author_signature))
1459                 $datarray['app']  = 'Diaspora';
1460
1461         DiasporaFetchGuid($datarray);
1462         $message_id = item_store($datarray);
1463
1464         //if($message_id) {
1465                 //q("update item set plink = '%s' where id = %d",
1466                 //      //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1467                 //      dbesc($a->get_baseurl().'/display/'.$datarray['guid']),
1468                 //      intval($message_id)
1469                 //);
1470         //}
1471
1472         if(($parent_item['origin']) && (! $parent_author_signature)) {
1473                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1474                         intval($message_id),
1475                         dbesc($signed_data),
1476                         dbesc(base64_encode($author_signature)),
1477                         dbesc($diaspora_handle)
1478                 );
1479
1480                 // if the message isn't already being relayed, notify others
1481                 // the existence of parent_author_signature means the parent_author or owner
1482                 // is already relaying.
1483
1484                 proc_run('php','include/notifier.php','comment-import',$message_id);
1485         }
1486
1487         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1488                 dbesc($parent_item['uri']),
1489                 intval($importer['uid'])
1490         );
1491
1492         if(count($myconv)) {
1493                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1494
1495                 foreach($myconv as $conv) {
1496
1497                         // now if we find a match, it means we're in this conversation
1498
1499                         if(! link_compare($conv['author-link'],$importer_url))
1500                                 continue;
1501
1502                         require_once('include/enotify.php');
1503
1504                         $conv_parent = $conv['parent'];
1505
1506                         notification(array(
1507                                 'type'         => NOTIFY_COMMENT,
1508                                 'notify_flags' => $importer['notify-flags'],
1509                                 'language'     => $importer['language'],
1510                                 'to_name'      => $importer['username'],
1511                                 'to_email'     => $importer['email'],
1512                                 'uid'          => $importer['uid'],
1513                                 'item'         => $datarray,
1514                                 'link'             => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
1515                                 'source_name'  => $datarray['author-name'],
1516                                 'source_link'  => $datarray['author-link'],
1517                                 'source_photo' => $datarray['author-avatar'],
1518                                 'verb'         => ACTIVITY_POST,
1519                                 'otype'        => 'item',
1520                                 'parent'       => $conv_parent,
1521                                 'parent_uri'   => $parent_uri
1522                         ));
1523
1524                         // only send one notification
1525                         break;
1526                 }
1527         }
1528         return;
1529 }
1530
1531
1532
1533
1534 function diaspora_conversation($importer,$xml,$msg) {
1535
1536         $a = get_app();
1537
1538         $guid = notags(unxmlify($xml->guid));
1539         $subject = notags(unxmlify($xml->subject));
1540         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1541         $participant_handles = notags(unxmlify($xml->participant_handles));
1542         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1543
1544         $parent_uri = $diaspora_handle . ':' . $guid;
1545  
1546         $messages = $xml->message;
1547
1548         if(! count($messages)) {
1549                 logger('diaspora_conversation: empty conversation');
1550                 return;
1551         }
1552
1553         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1554         if(! $contact) {
1555                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1556                 return;
1557         }
1558
1559         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1560                 logger('diaspora_conversation: Ignoring this author.');
1561                 return 202;
1562         }
1563
1564         $conversation = null;
1565
1566         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1567                 intval($importer['uid']),
1568                 dbesc($guid)
1569         );
1570         if(count($c))
1571                 $conversation = $c[0];
1572         else {
1573                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1574                         intval($importer['uid']),
1575                         dbesc($guid),
1576                         dbesc($diaspora_handle),
1577                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1578                         dbesc(datetime_convert()),
1579                         dbesc($subject),
1580                         dbesc($participant_handles)
1581                 );
1582                 if($r)
1583                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1584                 intval($importer['uid']),
1585             dbesc($guid)
1586         );
1587             if(count($c))
1588             $conversation = $c[0];
1589         }
1590         if(! $conversation) {
1591                 logger('diaspora_conversation: unable to create conversation.');
1592                 return;
1593         }
1594
1595         foreach($messages as $mesg) {
1596
1597                 $reply = 0;
1598
1599                 $msg_guid = notags(unxmlify($mesg->guid));
1600                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1601                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1602                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1603                 $msg_text = unxmlify($mesg->text);
1604                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1605                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1606                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1607                 if($msg_conversation_guid != $guid) {
1608                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1609                         continue;
1610                 }
1611
1612                 $body = diaspora2bb($msg_text);
1613                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1614
1615                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1616
1617                 $author_signature = base64_decode($msg_author_signature);
1618
1619                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1620                         $person = $contact;
1621                         $key = $msg['key'];
1622                 }
1623                 else {
1624                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1625
1626                         if(is_array($person) && x($person,'pubkey'))
1627                                 $key = $person['pubkey'];
1628                         else {
1629                                 logger('diaspora_conversation: unable to find author details');
1630                                 continue;
1631                         }
1632                 }
1633
1634                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1635                         logger('diaspora_conversation: verification failed.');
1636                         continue;
1637                 }
1638
1639                 if($msg_parent_author_signature) {
1640                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1641
1642                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1643
1644                         $key = $msg['key'];
1645
1646                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1647                                 logger('diaspora_conversation: owner verification failed.');
1648                                 continue;
1649                         }
1650                 }
1651
1652                 $r = q("select id from mail where `uri` = '%s' limit 1",
1653                         dbesc($message_id)
1654                 );
1655                 if(count($r)) {
1656                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1657                         continue;
1658                 }
1659
1660                 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')",
1661                         intval($importer['uid']),
1662                         dbesc($msg_guid),
1663                         intval($conversation['id']),
1664                         dbesc($person['name']),
1665                         dbesc($person['photo']),
1666                         dbesc($person['url']),
1667                         intval($contact['id']),  
1668                         dbesc($subject),
1669                         dbesc($body),
1670                         0,
1671                         0,
1672                         dbesc($message_id),
1673                         dbesc($parent_uri),
1674                         dbesc($msg_created_at)
1675                 );
1676
1677                 q("update conv set updated = '%s' where id = %d",
1678                         dbesc(datetime_convert()),
1679                         intval($conversation['id'])
1680                 );
1681
1682                 require_once('include/enotify.php');
1683                 notification(array(
1684                         'type' => NOTIFY_MAIL,
1685                         'notify_flags' => $importer['notify-flags'],
1686                         'language' => $importer['language'],
1687                         'to_name' => $importer['username'],
1688                         'to_email' => $importer['email'],
1689                         'uid' =>$importer['importer_uid'],
1690                         'item' => array('subject' => $subject, 'body' => $body),
1691                         'source_name' => $person['name'],
1692                         'source_link' => $person['url'],
1693                         'source_photo' => $person['thumb'],
1694                         'verb' => ACTIVITY_POST,
1695                         'otype' => 'mail'
1696                 ));
1697         }
1698
1699         return;
1700 }
1701
1702 function diaspora_message($importer,$xml,$msg) {
1703
1704         $a = get_app();
1705
1706         $msg_guid = notags(unxmlify($xml->guid));
1707         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1708         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1709         $msg_author_signature = notags(unxmlify($xml->author_signature));
1710         $msg_text = unxmlify($xml->text);
1711         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1712         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1713         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1714
1715         $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1716  
1717         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1718         if(! $contact) {
1719                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1720                 return;
1721         }
1722
1723         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1724                 logger('diaspora_message: Ignoring this author.');
1725                 return 202;
1726         }
1727
1728         $conversation = null;
1729
1730         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1731                 intval($importer['uid']),
1732                 dbesc($msg_conversation_guid)
1733         );
1734         if(count($c))
1735                 $conversation = $c[0];
1736         else {
1737                 logger('diaspora_message: conversation not available.');
1738                 return;
1739         }
1740
1741         $reply = 0;
1742
1743         $body = diaspora2bb($msg_text);
1744         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1745
1746         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1747
1748
1749         $author_signature = base64_decode($msg_author_signature);
1750
1751         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1752         if(is_array($person) && x($person,'pubkey'))
1753                 $key = $person['pubkey'];
1754         else {
1755                 logger('diaspora_message: unable to find author details');
1756                 return;
1757         }
1758
1759         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1760                 logger('diaspora_message: verification failed.');
1761                 return;
1762         }
1763
1764         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1765                 dbesc($message_id),
1766                 intval($importer['uid'])
1767         );
1768         if(count($r)) {
1769                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1770                 return;
1771         }
1772
1773         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')",
1774                 intval($importer['uid']),
1775                 dbesc($msg_guid),
1776                 intval($conversation['id']),
1777                 dbesc($person['name']),
1778                 dbesc($person['photo']),
1779                 dbesc($person['url']),
1780                 intval($contact['id']),  
1781                 dbesc($conversation['subject']),
1782                 dbesc($body),
1783                 0,
1784                 1,
1785                 dbesc($message_id),
1786                 dbesc($parent_uri),
1787                 dbesc($msg_created_at)
1788         );
1789
1790         q("update conv set updated = '%s' where id = %d",
1791                 dbesc(datetime_convert()),
1792                 intval($conversation['id'])
1793         );
1794
1795         return;
1796 }
1797
1798
1799 function diaspora_photo($importer,$xml,$msg,$attempt=1) {
1800
1801         $a = get_app();
1802
1803         logger('diaspora_photo: init',LOGGER_DEBUG);
1804
1805         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1806
1807         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1808
1809         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1810
1811         $guid = notags(unxmlify($xml->guid));
1812
1813         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1814
1815         $public = notags(unxmlify($xml->public));
1816
1817         $created_at = notags(unxmlify($xml_created_at));
1818
1819         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1820
1821         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1822         if(! $contact) {
1823                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1824                 return;
1825         }
1826
1827         if(! diaspora_post_allow($importer,$contact)) {
1828                 logger('diaspora_photo: Ignoring this author.');
1829                 return 202;
1830         }
1831
1832         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1833                 intval($importer['uid']),
1834                 dbesc($status_message_guid)
1835         );
1836         if(! count($r)) {
1837                 if($attempt <= 3) {
1838                         q("INSERT INTO dsprphotoq (uid, msg, attempt) VALUES (%d, '%s', %d)",
1839                            intval($importer['uid']),
1840                            dbesc(serialize($msg)),
1841                            intval($attempt + 1)
1842                         );
1843                 }
1844                 logger('diaspora_photo: attempt = ' . $attempt . '; status message not found: ' . $status_message_guid . ' for photo: ' . $guid);
1845                 return;
1846         }
1847
1848         $parent_item = $r[0];
1849
1850         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1851
1852         $link_text = scale_external_images($link_text, true,
1853                                            array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1854
1855         if(strpos($parent_item['body'],$link_text) === false) {
1856                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d",
1857                         dbesc($link_text . $parent_item['body']),
1858                         intval($parent_item['id']),
1859                         intval($parent_item['uid'])
1860                 );
1861         }
1862
1863         return;
1864 }
1865
1866
1867
1868
1869 function diaspora_like($importer,$xml,$msg) {
1870
1871         $a = get_app();
1872         $guid = notags(unxmlify($xml->guid));
1873         $parent_guid = notags(unxmlify($xml->parent_guid));
1874         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1875         $target_type = notags(unxmlify($xml->target_type));
1876         $positive = notags(unxmlify($xml->positive));
1877         $author_signature = notags(unxmlify($xml->author_signature));
1878
1879         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1880
1881         // likes on comments not supported here and likes on photos not supported by Diaspora
1882
1883 //      if($target_type !== 'Post')
1884 //              return;
1885
1886         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1887         if(! $contact) {
1888                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1889                 return;
1890         }
1891
1892         if(! diaspora_post_allow($importer,$contact)) {
1893                 logger('diaspora_like: Ignoring this author.');
1894                 return 202;
1895         }
1896
1897         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1898                 intval($importer['uid']),
1899                 dbesc($parent_guid)
1900         );
1901         if(! count($r)) {
1902                 logger('diaspora_like: parent item not found: ' . $guid);
1903                 return;
1904         }
1905
1906         $parent_item = $r[0];
1907
1908         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1909                 intval($importer['uid']),
1910                 dbesc($guid)
1911         );
1912         if(count($r)) {
1913                 if($positive === 'true') {
1914                         logger('diaspora_like: duplicate like: ' . $guid);
1915                         return;
1916                 }
1917                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1918                 // It looks like "RelayableRetractions" are used for "unlike" instead
1919                 if($positive === 'false') {
1920                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
1921 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d",
1922                                 intval($r[0]['id']),
1923                                 intval($importer['uid'])
1924                         );*/
1925                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1926                         //  send notification via proc_run()
1927                         return;
1928                 }
1929         }
1930         // Note: I don't think "Like" objects with positive = "false" are ever actually used
1931         // It looks like "RelayableRetractions" are used for "unlike" instead
1932         if($positive === 'false') {
1933                 logger('diaspora_like: received a like with positive set to "false"');
1934                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1935                 return; 
1936         }
1937
1938
1939         /* How Diaspora performs "like" signature checking:
1940
1941            - If an item has been sent by the like author to the top-level post owner to relay on
1942              to the rest of the contacts on the top-level post, the top-level post owner should check
1943              the author_signature, then create a parent_author_signature before relaying the like on
1944            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1945              check only the parent_author_signature. Basically, they trust that the top-level post
1946              owner has already verified the authenticity of anything he/she sends out
1947            - In either case, the signature that get checked is the signature created by the person
1948              who sent the salmon
1949         */
1950
1951         $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1952         $key = $msg['key'];
1953
1954         if($parent_author_signature) {
1955                 // If a parent_author_signature exists, then we've received the like
1956                 // relayed from the top-level post owner. There's no need to check the
1957                 // author_signature if the parent_author_signature is valid
1958
1959                 $parent_author_signature = base64_decode($parent_author_signature);
1960
1961                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1962                         if (intval(get_config('system','ignore_diaspora_like_signature')))
1963                                 logger('diaspora_like: top-level owner verification failed. Proceeding anyway.');
1964                         else {
1965                                 logger('diaspora_like: top-level owner verification failed.');
1966                                 return;
1967                         }
1968                 }
1969         }
1970         else {
1971                 // If there's no parent_author_signature, then we've received the like
1972                 // from the like creator. In that case, the person is "like"ing
1973                 // our post, so he/she must be a contact of ours and his/her public key
1974                 // should be in $msg['key']
1975
1976                 $author_signature = base64_decode($author_signature);
1977
1978                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1979                         if (intval(get_config('system','ignore_diaspora_like_signature')))
1980                                 logger('diaspora_like: like creator verification failed. Proceeding anyway');
1981                         else {
1982                                 logger('diaspora_like: like creator verification failed.');
1983                                 return;
1984                         }
1985                 }
1986         }
1987
1988         // Phew! Everything checks out. Now create an item.
1989
1990         // Find the original comment author information.
1991         // We need this to make sure we display the comment author
1992         // information (name and avatar) correctly.
1993         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1994                 $person = $contact;
1995         else {
1996                 $person = find_diaspora_person_by_handle($diaspora_handle);
1997
1998                 if(! is_array($person)) {
1999                         logger('diaspora_like: unable to find author details');
2000                         return;
2001                 }
2002         }
2003
2004         $uri = $diaspora_handle . ':' . $guid;
2005
2006         $activity = ACTIVITY_LIKE;
2007         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
2008         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
2009         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
2010         $body = $parent_item['body'];
2011
2012         $obj = <<< EOT
2013
2014         <object>
2015                 <type>$objtype</type>
2016                 <local>1</local>
2017                 <id>{$parent_item['uri']}</id>
2018                 <link>$link</link>
2019                 <title></title>
2020                 <content>$body</content>
2021         </object>
2022 EOT;
2023         $bodyverb = t('%1$s likes %2$s\'s %3$s');
2024
2025         $arr = array();
2026
2027         $arr['uri'] = $uri;
2028         $arr['uid'] = $importer['uid'];
2029         $arr['guid'] = $guid;
2030         $arr['network']  = NETWORK_DIASPORA;
2031         $arr['contact-id'] = $contact['id'];
2032         $arr['type'] = 'activity';
2033         $arr['wall'] = $parent_item['wall'];
2034         $arr['gravity'] = GRAVITY_LIKE;
2035         $arr['parent'] = $parent_item['id'];
2036         $arr['parent-uri'] = $parent_item['uri'];
2037
2038         $arr['owner-name'] = $parent_item['name'];
2039         $arr['owner-link'] = $parent_item['url'];
2040         //$arr['owner-avatar'] = $parent_item['thumb'];
2041         $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
2042
2043         $arr['author-name'] = $person['name'];
2044         $arr['author-link'] = $person['url'];
2045         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
2046
2047         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
2048         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
2049         //$plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
2050         $plink = '[url='.$a->get_baseurl().'/display/'.urlencode($guid).']'.$post_type.'[/url]';
2051         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
2052
2053         $arr['app']  = 'Diaspora';
2054
2055         $arr['private'] = $parent_item['private'];
2056         $arr['verb'] = $activity;
2057         $arr['object-type'] = $objtype;
2058         $arr['object'] = $obj;
2059         $arr['visible'] = 1;
2060         $arr['unseen'] = 1;
2061         $arr['last-child'] = 0;
2062
2063         $message_id = item_store($arr);
2064
2065
2066         //if($message_id) {
2067         //      q("update item set plink = '%s' where id = %d",
2068         //              //dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
2069         //              dbesc($a->get_baseurl().'/display/'.$guid),
2070         //              intval($message_id)
2071         //      );
2072         //}
2073
2074         if(! $parent_author_signature) {
2075                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2076                         intval($message_id),
2077                         dbesc($signed_data),
2078                         dbesc(base64_encode($author_signature)),
2079                         dbesc($diaspora_handle)
2080                 );
2081         }
2082
2083         // if the message isn't already being relayed, notify others
2084         // the existence of parent_author_signature means the parent_author or owner
2085         // is already relaying. The parent_item['origin'] indicates the message was created on our system
2086
2087         if(($parent_item['origin']) && (! $parent_author_signature))
2088                 proc_run('php','include/notifier.php','comment-import',$message_id);
2089
2090         return;
2091 }
2092
2093 function diaspora_retraction($importer,$xml) {
2094
2095
2096         $guid = notags(unxmlify($xml->guid));
2097         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2098         $type = notags(unxmlify($xml->type));
2099
2100         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2101         if(! $contact)
2102                 return;
2103
2104         if($type === 'Person') {
2105                 require_once('include/Contact.php');
2106                 contact_remove($contact['id']);
2107         }
2108         elseif($type === 'Post') {
2109                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2110                         dbesc('guid'),
2111                         intval($importer['uid'])
2112                 );
2113                 if(count($r)) {
2114                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2115                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d",
2116                                         dbesc(datetime_convert()),
2117                                         intval($r[0]['id'])
2118                                 );
2119                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2120                         }
2121                 }
2122         }
2123
2124         return 202;
2125         // NOTREACHED
2126 }
2127
2128 function diaspora_signed_retraction($importer,$xml,$msg) {
2129
2130
2131         $guid = notags(unxmlify($xml->target_guid));
2132         $diaspora_handle = notags(unxmlify($xml->sender_handle));
2133         $type = notags(unxmlify($xml->target_type));
2134         $sig = notags(unxmlify($xml->target_author_signature));
2135
2136         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
2137
2138         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2139         if(! $contact) {
2140                 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
2141                 return;
2142         }
2143
2144
2145         $signed_data = $guid . ';' . $type ;
2146         $key = $msg['key'];
2147
2148         /* How Diaspora performs relayable_retraction signature checking:
2149
2150            - If an item has been sent by the item author to the top-level post owner to relay on
2151              to the rest of the contacts on the top-level post, the top-level post owner checks
2152              the author_signature, then creates a parent_author_signature before relaying the item on
2153            - If an item has been relayed on by the top-level post owner, the contacts who receive it
2154              check only the parent_author_signature. Basically, they trust that the top-level post
2155              owner has already verified the authenticity of anything he/she sends out
2156            - In either case, the signature that get checked is the signature created by the person
2157              who sent the salmon
2158         */
2159
2160         if($parent_author_signature) {
2161
2162                 $parent_author_signature = base64_decode($parent_author_signature);
2163
2164                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2165                         logger('diaspora_signed_retraction: top-level post owner verification failed');
2166                         return;
2167                 }
2168
2169         }
2170         else {
2171
2172                 $sig_decode = base64_decode($sig);
2173
2174                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2175                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2176                         return;
2177                 }
2178         }
2179
2180         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2181                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2182                         dbesc($guid),
2183                         intval($importer['uid'])
2184                 );
2185                 if(count($r)) {
2186                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2187                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d",
2188                                         dbesc(datetime_convert()),
2189                                         dbesc(datetime_convert()),
2190                                         intval($r[0]['id'])
2191                                 );
2192                                 delete_thread($r[0]['id'], $r[0]['parent-uri']);
2193
2194                                 // Now check if the retraction needs to be relayed by us
2195                                 //
2196                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2197                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2198                                 // The only item with `parent` and `id` as the parent id is the parent item.
2199                                 $p = q("select origin from item where parent = %d and id = %d limit 1",
2200                                         $r[0]['parent'],
2201                                         $r[0]['parent']
2202                                 );
2203                                 if(count($p)) {
2204                                         if(($p[0]['origin']) && (! $parent_author_signature)) {
2205                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2206                                                         $r[0]['id'],
2207                                                         dbesc($signed_data),
2208                                                         dbesc($sig),
2209                                                         dbesc($diaspora_handle)
2210                                                 );
2211
2212                                                 // the existence of parent_author_signature would have meant the parent_author or owner
2213                                                 // is already relaying.
2214                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
2215
2216                                                 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2217                                         }
2218                                 }
2219                         }
2220                 }
2221         }
2222         else
2223                 logger('diaspora_signed_retraction: unknown type: ' . $type);
2224
2225         return 202;
2226         // NOTREACHED
2227 }
2228
2229 function diaspora_profile($importer,$xml,$msg) {
2230
2231         $a = get_app();
2232         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2233
2234
2235         if($diaspora_handle != $msg['author']) {
2236                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2237                 return 202;
2238         }
2239
2240         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2241         if(! $contact)
2242                 return;
2243
2244         if($contact['blocked']) {
2245                 logger('diaspora_post: Ignoring this author.');
2246                 return 202;
2247         }
2248
2249         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2250         $image_url = unxmlify($xml->image_url);
2251         $birthday = unxmlify($xml->birthday);
2252         $location = diaspora2bb(unxmlify($xml->location));
2253         $about = diaspora2bb(unxmlify($xml->bio));
2254         $gender = unxmlify($xml->gender);
2255         $tags = unxmlify($xml->tag_string);
2256
2257         $tags = explode("#", $tags);
2258
2259         $keywords = array();
2260         foreach ($tags as $tag) {
2261                 $tag = trim(strtolower($tag));
2262                 if ($tag != "")
2263                         $keywords[] = $tag;
2264         }
2265
2266         $keywords = implode(", ", $keywords);
2267
2268         $handle_parts = explode("@", $diaspora_handle);
2269         if($name === '') {
2270                 $name = $handle_parts[0];
2271         }
2272
2273         if( preg_match("|^https?://|", $image_url) === 0) {
2274                 $image_url = "http://" . $handle_parts[1] . $image_url;
2275         }
2276
2277 /*      $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2278                 intval($importer['uid']),
2279                 intval($contact['id'])
2280         );
2281         $oldphotos = ((count($r)) ? $r : null);*/
2282
2283         require_once('include/Photo.php');
2284
2285         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2286
2287         // Generic birthday. We don't know the timezone. The year is irrelevant.
2288
2289         $birthday = str_replace('1000','1901',$birthday);
2290
2291         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2292
2293         // this is to prevent multiple birthday notifications in a single year
2294         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2295
2296         if(substr($birthday,5) === substr($contact['bd'],5))
2297                 $birthday = $contact['bd'];
2298
2299         // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2300         // Not doing this currently because D* protocol is scheduled for revision soon.
2301
2302         $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",
2303                 dbesc($name),
2304                 dbesc(datetime_convert()),
2305                 dbesc($images[0]),
2306                 dbesc($images[1]),
2307                 dbesc($images[2]),
2308                 dbesc(datetime_convert()),
2309                 dbesc($birthday),
2310                 dbesc($location),
2311                 dbesc($about),
2312                 dbesc($keywords),
2313                 dbesc($gender),
2314                 intval($contact['id']),
2315                 intval($importer['uid'])
2316         );
2317
2318         if (unxmlify($xml->searchable) == "true") {
2319                 require_once('include/socgraph.php');
2320                 poco_check($contact['url'], $name, NETWORK_DIASPORA, $images[0], $about, $location, $gender, $keywords, "",
2321                         datetime_convert(), 2, $contact['id'], $importer['uid']);
2322         }
2323
2324         $profileurl = "";
2325         $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
2326                         dbesc(normalise_link($contact['url'])));
2327
2328         if (count($author) == 0) {
2329                 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`, `location`, `about`) VALUES ('%s', '%s', '%s', '%s', '%s')",
2330                         dbesc(normalise_link($contact['url'])), dbesc($name), dbesc($location), dbesc($about), dbesc($images[0]));
2331
2332                 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
2333                         dbesc(normalise_link($contact['url'])));
2334         } else if (normalise_link($contact['url']).$name.$location.$about != normalise_link($author[0]["url"]).$author[0]["name"].$author[0]["location"].$author[0]["about"]) {
2335                 q("UPDATE unique_contacts SET name = '%s', avatar = '%s', `location` = '%s', `about` = '%s' WHERE url = '%s'",
2336                 dbesc($name), dbesc($images[0]), dbesc($location), dbesc($about), dbesc(normalise_link($contact['url'])));
2337         }
2338
2339 /*      if($r) {
2340                 if($oldphotos) {
2341                         foreach($oldphotos as $ph) {
2342                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2343                                         intval($importer['uid']),
2344                                         intval($contact['id']),
2345                                         dbesc($ph['resource-id'])
2346                                 );
2347                         }
2348                 }
2349         }       */
2350
2351         return;
2352
2353 }
2354
2355 function diaspora_share($me,$contact) {
2356         $a = get_app();
2357         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2358         $theiraddr = $contact['addr'];
2359
2360         $tpl = get_markup_template('diaspora_share.tpl');
2361         $msg = replace_macros($tpl, array(
2362                 '$sender' => $myaddr,
2363                 '$recipient' => $theiraddr
2364         ));
2365
2366         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2367         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2368
2369         return(diaspora_transmit($owner,$contact,$slap, false));
2370 }
2371
2372 function diaspora_unshare($me,$contact) {
2373
2374         $a = get_app();
2375         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2376
2377         $tpl = get_markup_template('diaspora_retract.tpl');
2378         $msg = replace_macros($tpl, array(
2379                 '$guid'   => $me['guid'],
2380                 '$type'   => 'Person',
2381                 '$handle' => $myaddr
2382         ));
2383
2384         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2385         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2386
2387         return(diaspora_transmit($owner,$contact,$slap, false));
2388
2389 }
2390
2391
2392 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2393
2394         $a = get_app();
2395         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2396         $theiraddr = $contact['addr'];
2397
2398         $images = array();
2399
2400         $title = $item['title'];
2401         $body = $item['body'];
2402
2403 /*
2404         // We're trying to match Diaspora's split message/photo protocol but
2405         // all the photos are displayed on D* as links and not img's - even
2406         // though we're sending pretty much precisely what they send us when
2407         // doing the same operation.  
2408         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2409         // which seems to get through intact.
2410
2411         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2412         if($cnt) {
2413                 foreach($matches as $mtch) {
2414                         $detail = array();
2415                         $detail['str'] = $mtch[0];
2416                         $detail['path'] = dirname($mtch[1]) . '/';
2417                         $detail['file'] = basename($mtch[1]);
2418                         $detail['guid'] = $item['guid'];
2419                         $detail['handle'] = $myaddr;
2420                         $images[] = $detail;
2421                         $body = str_replace($detail['str'],$mtch[1],$body);
2422                 }
2423         }
2424 */
2425
2426         //if(strlen($title))
2427         //      $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2428
2429         // convert to markdown
2430         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2431         //$body = bb2diaspora($body);
2432
2433         // Adding the title
2434         if(strlen($title))
2435                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2436
2437         if($item['attach']) {
2438                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2439                 if(cnt) {
2440                         $body .= "\n" . t('Attachments:') . "\n";
2441                         foreach($matches as $mtch) {
2442                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2443                         }
2444                 }
2445         }
2446
2447
2448         $public = (($item['private']) ? 'false' : 'true');
2449
2450         require_once('include/datetime.php');
2451         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2452
2453         // Detect a share element and do a reshare
2454         // see: https://github.com/Raven24/diaspora-federation/blob/master/lib/diaspora-federation/entities/reshare.rb
2455         if (!$item['private'] AND ($ret = diaspora_is_reshare($item["body"]))) {
2456                 $tpl = get_markup_template('diaspora_reshare.tpl');
2457                 $msg = replace_macros($tpl, array(
2458                         '$root_handle' => xmlify($ret['root_handle']),
2459                         '$root_guid' => $ret['root_guid'],
2460                         '$guid' => $item['guid'],
2461                         '$handle' => xmlify($myaddr),
2462                         '$public' => $public,
2463                         '$created' => $created,
2464                         '$provider' => $item["app"]
2465                 ));
2466         } else {
2467                 $tpl = get_markup_template('diaspora_post.tpl');
2468                 $msg = replace_macros($tpl, array(
2469                         '$body' => $body,
2470                         '$guid' => $item['guid'],
2471                         '$handle' => xmlify($myaddr),
2472                         '$public' => $public,
2473                         '$created' => $created,
2474                         '$provider' => $item["app"]
2475                 ));
2476         }
2477
2478         logger('diaspora_send_status: '.$owner['username'].' -> '.$contact['name'].' base message: '.$msg, LOGGER_DATA);
2479
2480         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2481         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2482
2483         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2484
2485         logger('diaspora_send_status: guid: '.$item['guid'].' result '.$return_code, LOGGER_DEBUG);
2486
2487         if(count($images)) {
2488                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2489         }
2490
2491         return $return_code;
2492 }
2493
2494 function diaspora_is_reshare($body) {
2495         $body = trim($body);
2496
2497         // Skip if it isn't a pure repeated messages
2498         // Does it start with a share?
2499         if (strpos($body, "[share") > 0)
2500                 return(false);
2501
2502         // Does it end with a share?
2503         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2504                 return(false);
2505
2506         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2507         // Skip if there is no shared message in there
2508         if ($body == $attributes)
2509                 return(false);
2510
2511         $profile = "";
2512         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2513         if ($matches[1] != "")
2514                 $profile = $matches[1];
2515
2516         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2517         if ($matches[1] != "")
2518                 $profile = $matches[1];
2519
2520         $ret= array();
2521
2522         $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2523         if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2524                 return(false);
2525
2526         $link = "";
2527         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2528         if ($matches[1] != "")
2529                 $link = $matches[1];
2530
2531         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2532         if ($matches[1] != "")
2533                 $link = $matches[1];
2534
2535         $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2536         if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2537                 return(false);
2538
2539         return($ret);
2540 }
2541
2542 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2543         $a = get_app();
2544         if(! count($images))
2545                 return;
2546         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2547
2548         $tpl = get_markup_template('diaspora_photo.tpl');
2549         foreach($images as $image) {
2550                 if(! stristr($image['path'],$mysite))
2551                         continue;
2552                 $resource = str_replace('.jpg','',$image['file']);
2553                 $resource = substr($resource,0,strpos($resource,'-'));
2554
2555                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2556                         dbesc($resource),
2557                         intval($owner['uid'])
2558                 );
2559                 if(! count($r))
2560                         continue;
2561                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2562                 $msg = replace_macros($tpl,array(
2563                         '$path' => xmlify($image['path']),
2564                         '$filename' => xmlify($image['file']),
2565                         '$msg_guid' => xmlify($image['guid']),
2566                         '$guid' => xmlify($r[0]['guid']),
2567                         '$handle' => xmlify($image['handle']),
2568                         '$public' => xmlify($public),
2569                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2570                 ));
2571
2572
2573                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2574                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2575                 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2576
2577                 diaspora_transmit($owner,$contact,$slap,$public_batch);
2578         }
2579
2580 }
2581
2582 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2583
2584         $a = get_app();
2585         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2586 //      $theiraddr = $contact['addr'];
2587
2588         // Diaspora doesn't support threaded comments, but some
2589         // versions of Diaspora (i.e. Diaspora-pistos) support
2590         // likes on comments
2591         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2592                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2593                         dbesc($item['thr-parent'])
2594                       );
2595         }
2596         else {
2597                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2598                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2599                 // The only item with `parent` and `id` as the parent id is the parent item.
2600                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2601                         intval($item['parent']),
2602                         intval($item['parent'])
2603                 );
2604         }
2605         if(count($p))
2606                 $parent = $p[0];
2607         else
2608                 return;
2609
2610         if($item['verb'] === ACTIVITY_LIKE) {
2611                 $tpl = get_markup_template('diaspora_like.tpl');
2612                 $like = true;
2613                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2614 //              $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2615 //              $positive = (($item['deleted']) ? 'false' : 'true');
2616                 $positive = 'true';
2617
2618                 if(($item['deleted']))
2619                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2620         }
2621         else {
2622                 $tpl = get_markup_template('diaspora_comment.tpl');
2623                 $like = false;
2624         }
2625
2626         $text = html_entity_decode(bb2diaspora($item['body']));
2627
2628         // sign it
2629
2630         if($like)
2631                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2632         else
2633                 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2634
2635         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2636
2637         $msg = replace_macros($tpl,array(
2638                 '$guid' => xmlify($item['guid']),
2639                 '$parent_guid' => xmlify($parent['guid']),
2640                 '$target_type' =>xmlify($target_type),
2641                 '$authorsig' => xmlify($authorsig),
2642                 '$body' => xmlify($text),
2643                 '$positive' => xmlify($positive),
2644                 '$handle' => xmlify($myaddr)
2645         ));
2646
2647         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2648
2649         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2650         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2651
2652         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2653 }
2654
2655
2656 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2657
2658
2659         $a = get_app();
2660         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2661 //      $theiraddr = $contact['addr'];
2662
2663         $body = $item['body'];
2664         $text = html_entity_decode(bb2diaspora($body));
2665
2666         // Diaspora doesn't support threaded comments, but some
2667         // versions of Diaspora (i.e. Diaspora-pistos) support
2668         // likes on comments
2669         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2670                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2671                         dbesc($item['thr-parent'])
2672                       );
2673         }
2674         else {
2675                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2676                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2677                 // The only item with `parent` and `id` as the parent id is the parent item.
2678                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2679                        intval($item['parent']),
2680                        intval($item['parent'])
2681                       );
2682         }
2683         if(count($p))
2684                 $parent = $p[0];
2685         else
2686                 return;
2687
2688         $like = false;
2689         $relay_retract = false;
2690         $sql_sign_id = 'iid';
2691         if( $item['deleted']) {
2692                 $relay_retract = true;
2693
2694                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2695
2696                 $sql_sign_id = 'retract_iid';
2697                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2698         }
2699         elseif($item['verb'] === ACTIVITY_LIKE) {
2700                 $like = true;
2701
2702                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2703 //              $positive = (($item['deleted']) ? 'false' : 'true');
2704                 $positive = 'true';
2705
2706                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2707         }
2708         else { // item is a comment
2709                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2710         }
2711
2712
2713         // fetch the original signature if the relayable was created by a Diaspora
2714         // or DFRN user. Relayables for other networks are not supported.
2715
2716 /*      $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2717                 intval($item['id'])
2718         );
2719         if(count($r)) { 
2720                 $orig_sign = $r[0];
2721                 $signed_text = $orig_sign['signed_text'];
2722                 $authorsig = $orig_sign['signature'];
2723                 $handle = $orig_sign['signer'];
2724         }
2725         else {
2726
2727                 // Author signature information (for likes, comments, and retractions of likes or comments,
2728                 // whether from Diaspora or Friendica) must be placed in the `sign` table before this 
2729                 // function is called
2730                 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2731                 return;
2732         }*/
2733
2734         /* Since the author signature is only checked by the parent, not by the relay recipients,
2735          * I think it may not be necessary for us to do so much work to preserve all the original
2736          * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2737          * Let's just generate that and forget about all the original author signature stuff.
2738          *
2739          * Note: this might be more of an problem if we want to support likes on comments for older
2740          * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2741          * doing that, let's ignore it for now.
2742          *
2743          * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2744          * been done yet
2745          */
2746
2747         $handle = diaspora_handle_from_contact($item['contact-id']);
2748         if(! $handle)
2749                 return;
2750
2751
2752         if($relay_retract)
2753                 $sender_signed_text = $item['guid'] . ';' . $target_type;
2754         elseif($like)
2755                 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2756         else
2757                 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2758
2759         // Sign the relayable with the top-level owner's signature
2760         //
2761         // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2762         // stored in the database, because that provides the best chance that Diaspora will
2763         // be able to reconstruct the signed text the same way we did. This is particularly a
2764         // concern for the comment, whose signed text includes the text of the comment. The
2765         // smallest change in the text of the comment, including removing whitespace, will
2766         // make the signature verification fail. Since we translate from BB code to Diaspora's
2767         // markup at the top of this function, which is AFTER we placed the original $signed_text
2768         // in the database, it's hazardous to trust the original $signed_text.
2769
2770         $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2771
2772         $msg = replace_macros($tpl,array(
2773                 '$guid' => xmlify($item['guid']),
2774                 '$parent_guid' => xmlify($parent['guid']),
2775                 '$target_type' =>xmlify($target_type),
2776                 '$authorsig' => xmlify($authorsig),
2777                 '$parentsig' => xmlify($parentauthorsig),
2778                 '$body' => xmlify($text),
2779                 '$positive' => xmlify($positive),
2780                 '$handle' => xmlify($handle)
2781         ));
2782
2783         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2784
2785
2786         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2787         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2788
2789         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2790
2791 }
2792
2793
2794
2795 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2796
2797         $a = get_app();
2798         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2799
2800         // Check whether the retraction is for a top-level post or whether it's a relayable
2801         if( $item['uri'] !== $item['parent-uri'] ) {
2802
2803                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2804                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2805         }
2806         else {
2807                 
2808                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2809                 $target_type = 'StatusMessage';
2810         }
2811
2812         $signed_text = $item['guid'] . ';' . $target_type;
2813
2814         $msg = replace_macros($tpl, array(
2815                 '$guid'   => xmlify($item['guid']),
2816                 '$type'   => xmlify($target_type),
2817                 '$handle' => xmlify($myaddr),
2818                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2819         ));
2820
2821         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2822         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2823
2824         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2825 }
2826
2827 function diaspora_send_mail($item,$owner,$contact) {
2828
2829         $a = get_app();
2830         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2831
2832         $r = q("select * from conv where id = %d and uid = %d limit 1",
2833                 intval($item['convid']),
2834                 intval($item['uid'])
2835         );
2836
2837         if(! count($r)) {
2838                 logger('diaspora_send_mail: conversation not found.');
2839                 return;
2840         }
2841         $cnv = $r[0];
2842
2843         $conv = array(
2844                 'guid' => xmlify($cnv['guid']),
2845                 'subject' => xmlify($cnv['subject']),
2846                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2847                 'diaspora_handle' => xmlify($cnv['creator']),
2848                 'participant_handles' => xmlify($cnv['recips'])
2849         );
2850
2851         $body = bb2diaspora($item['body']);
2852         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2853  
2854         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';' 
2855                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2856
2857         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2858
2859         $msg = array(
2860                 'guid' => xmlify($item['guid']),
2861                 'parent_guid' => xmlify($cnv['guid']),
2862                 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2863                 'author_signature' => xmlify($sig),
2864                 'text' => xmlify($body),
2865                 'created_at' => xmlify($created),
2866                 'diaspora_handle' => xmlify($myaddr),
2867                 'conversation_guid' => xmlify($cnv['guid'])
2868         );
2869
2870         if($item['reply']) {
2871                 $tpl = get_markup_template('diaspora_message.tpl');
2872                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2873         }
2874         else {
2875                 $conv['messages'] = array($msg);
2876                 $tpl = get_markup_template('diaspora_conversation.tpl');
2877                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2878         }
2879
2880         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2881
2882         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2883         //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2884
2885         return(diaspora_transmit($owner,$contact,$slap,false));
2886
2887
2888 }
2889
2890 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2891
2892         $enabled = intval(get_config('system','diaspora_enabled'));
2893         if(! $enabled) {
2894                 return 200;
2895         }
2896
2897         $a = get_app();
2898         $logid = random_string(4);
2899         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2900         if(! $dest_url) {
2901                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2902                 return 0;
2903         } 
2904
2905         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2906
2907         if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2908                 $return_code = 0;
2909         }
2910         else {
2911                 if (!intval(get_config('system','diaspora_test'))) {
2912                         post_url($dest_url . '/', $slap);
2913                         $return_code = $a->get_curl_code();
2914                 } else {
2915                         logger('diaspora_transmit: test_mode');
2916                         return 200;
2917                 }
2918         }
2919
2920         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2921
2922         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2923                 logger('diaspora_transmit: queue message');
2924
2925                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2926                         intval($contact['id']),
2927                         dbesc(NETWORK_DIASPORA),
2928                         dbesc($slap),
2929                         intval($public_batch)
2930                 );
2931                 if(count($r)) {
2932                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2933                 }
2934                 else {
2935                         // queue message for redelivery
2936                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2937                 }
2938         }
2939
2940
2941         return(($return_code) ? $return_code : (-1));
2942 }
2943
2944