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