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