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