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