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