]> git.mxchange.org Git - friendica-addons.git/blob - fbsync/fbsync.php
app.net, acebook, pumpio, statusnet, twitter: Support for the new database fields...
[friendica-addons.git] / fbsync / fbsync.php
1 <?php
2 /**
3  * Name: Facebook Sync
4  * Description: Synchronizes the Facebook Newsfeed
5  * Version: 1.0
6  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
7  */
8
9 /* To-Do
10 FBSync:
11 - B: Threading for incoming comments
12 - C: Receiving likes for comments
13
14 FBPost:
15 - A: Posts to pages currently have the page as sender - not the user
16 - B: Sending likes for comments
17 - C: Threading for sent comments
18 */
19
20 require_once("addon/fbpost/fbpost.php");
21
22 define('FBSYNC_DEFAULT_POLL_INTERVAL', 5); // given in minutes
23
24 function fbsync_install() {
25         register_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
26         register_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
27         register_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
28         register_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
29         register_hook('expire', 'addon/fbsync/fbsync.php', 'fbsync_expire');
30 }
31
32 function fbsync_uninstall() {
33         unregister_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
34         unregister_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
35         unregister_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
36         unregister_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
37         unregister_hook('expire', 'addon/fbsync/fbsync.php', 'fbsync_expire');
38 }
39
40 function fbsync_follow($a, &$contact) {
41
42         logger("fbsync_follow: Check if contact is facebook contact. ".$contact["url"], LOGGER_DEBUG);
43
44         if (!strstr($contact["url"], "://www.facebook.com") AND !strstr($contact["url"], "://facebook.com") AND !strstr($contact["url"], "@facebook.com"))
45                 return;
46
47         // contact seems to be a facebook contact, so continue
48         $nickname = preg_replace("=https?://.*facebook.com/([\w.]*).*=ism", "$1", $contact["url"]);
49         $nickname = str_replace("@facebook.com", "", $nickname);
50
51         $uid = $a->user["uid"];
52
53         $access_token = get_pconfig($uid,'facebook','access_token');
54
55         $fql = array(
56                         "profile" => "SELECT id, pic_square, url, username, name FROM profile WHERE username = '$nickname'",
57                         "avatar" => "SELECT url FROM square_profile_pic WHERE id IN (SELECT id FROM #profile) AND size = 256");
58
59         $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
60
61         $feed = fetch_url($url);
62         $data = json_decode($feed);
63
64         $id = 0;
65
66         logger("fbsync_follow: Query id for nickname ".$nickname, LOGGER_DEBUG);
67
68         if (!is_array($data->data))
69                 return;
70
71         $contactdata = new stdClass;
72
73         foreach($data->data AS $query) {
74                 switch ($query->name) {
75                         case "profile":
76                                 $contactdata->id =  number_format($query->fql_result_set[0]->id, 0, '', '');
77                                 $contactdata->pic_square = $query->fql_result_set[0]->pic_square;
78                                 $contactdata->url = $query->fql_result_set[0]->url;
79                                 $contactdata->username = $query->fql_result_set[0]->username;
80                                 $contactdata->name = $query->fql_result_set[0]->name;
81                                 break;
82
83                         case "avatar":
84                                 $contactdata->pic_square = $query->fql_result_set[0]->url;
85                                 break;
86                 }
87         }
88
89         logger("fbsync_follow: Got contact for nickname ".$nickname." ".print_r($contactdata, true), LOGGER_DEBUG);
90
91         // Create contact
92         fbsync_fetch_contact($uid, $contactdata, true);
93
94         $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
95                 FROM `contact` WHERE `uid` = %d AND `alias` = '%s'",
96                                 intval($uid),
97                                 dbesc("facebook::".$contactdata->id));
98         if (count($r))
99                 $contact["contact"] = $r[0];
100 }
101
102
103 function fbsync_settings(&$a,&$s) {
104
105         // Settings are done inside the fbpost addon
106         return;
107
108         if(! local_user())
109                 return;
110
111         /* Add our stylesheet to the page so we can make our settings look nice */
112
113         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
114
115         /* Get the current state of our config variables */
116
117         $enabled = get_pconfig(local_user(),'fbsync','sync');
118
119         $checked = (($enabled) ? ' checked="checked" ' : '');
120
121         $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
122
123         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
124
125         /* Add some HTML to the existing form */
126
127         $s .= '<span id="settings_fbsync_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
128         $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
129         $s .= '</span>';
130         $s .= '<div id="settings_fbsync_expanded" class="settings-block" style="display: none;">';
131         $s .= '<span class="fakelink" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
132         $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
133         $s .= '</span>';
134
135         $s .= '<div id="fbsync-enable-wrapper">';
136         $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
137         $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
138         $s .= '</div><div class="clear"></div>';
139
140         $s .= '<div id="fbsync-create_user-wrapper">';
141         $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
142         $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
143         $s .= '</div><div class="clear"></div>';
144
145         /* provide a submit button */
146
147         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
148
149 }
150
151 function fbsync_settings_post(&$a,&$b) {
152
153         if(x($_POST,'fbsync-submit')) {
154                 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
155                 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
156         }
157 }
158
159 function fbsync_cron($a,$b) {
160         $last = get_config('fbsync','last_poll');
161
162         $poll_interval = intval(get_config('fbsync','poll_interval'));
163         if(! $poll_interval)
164                 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
165
166         if($last) {
167                 $next = $last + ($poll_interval * 60);
168                 if($next > time()) {
169                         logger('fbsync_cron: poll intervall not reached');
170                         return;
171                 }
172         }
173         logger('fbsync_cron: cron_start');
174
175         $abandon_days = intval(get_config('system','account_abandon_days'));
176         if ($abandon_days < 1)
177                 $abandon_days = 0;
178
179         $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
180
181         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
182         if(count($r)) {
183                 foreach($r as $rr) {
184
185                         if ($abandon_days != 0) {
186                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
187                                 if (!count($user)) {
188                                         logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
189                                         continue;
190                                 }
191                         }
192
193                         fbsync_get_self($rr['uid']);
194
195                         logger('fbsync_cron: importing timeline from user '.$rr['uid']);
196                         fbsync_fetchfeed($a, $rr['uid']);
197                 }
198         }
199
200         logger('fbsync_cron: cron_end');
201
202         set_config('fbsync','last_poll', time());
203 }
204
205 function fbsync_expire($a,$b) {
206
207         $days = get_config('fbsync', 'expire');
208
209         if ($days == 0)
210                 return;
211
212         $r = q("DELETE FROM `item` WHERE `deleted` AND `network` = '%s'", dbesc(NETWORK_FACEBOOK));
213
214         require_once("include/items.php");
215
216         logger('fbsync_expire: expire_start');
217
218         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
219         if(count($r)) {
220                 foreach($r as $rr) {
221                         logger('fbsync_expire: user '.$rr['uid']);
222                         item_expire($rr['uid'], $days, NETWORK_FACEBOOK, true);
223                 }
224         }
225
226         logger('fbsync_expire: expire_end');
227 }
228
229 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
230
231         $access_token = get_pconfig($uid,'facebook','access_token');
232
233         require_once("include/oembed.php");
234         require_once("include/network.php");
235         require_once("include/items.php");
236
237         // check if it was already imported
238         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
239                 intval($uid),
240                 dbesc('fb::'.$post->post_id)
241         );
242         if(count($r))
243                 return;
244
245         $postarray = array();
246         $postarray['gravity'] = 0;
247         $postarray['uid'] = $uid;
248         $postarray['wall'] = 0;
249
250         $postarray['verb'] = ACTIVITY_POST;
251         $postarray['object-type'] = ACTIVITY_OBJ_NOTE; // default value - is maybe changed later when media is attached
252         $postarray['network'] =  dbesc(NETWORK_FACEBOOK);
253
254         $postarray['uri'] = "fb::".$post->post_id;
255         $postarray['thr-parent'] = $postarray['uri'];
256         $postarray['parent-uri'] = $postarray['uri'];
257         $postarray['plink'] = $post->permalink;
258
259         $postarray['author-name'] = $contacts[$post->actor_id]->name;
260         $postarray['author-link'] = $contacts[$post->actor_id]->url;
261         $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
262
263         $postarray['owner-name'] = $contacts[$post->source_id]->name;
264         $postarray['owner-link'] = $contacts[$post->source_id]->url;
265         $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
266
267         $contact_id = 0;
268
269         if (($post->parent_post_id != "") AND ($post->actor_id == $post->source_id)) {
270                 $pos = strpos($post->parent_post_id, "_");
271
272                 if ($pos != 0) {
273                         $user_id = substr($post->parent_post_id, 0, $pos);
274
275                         $userdata = fbsync_fetchuser($a, $uid, $user_id);
276
277                         $contact_id = $userdata["contact-id"];
278
279                         $postarray['contact-id'] = $contact_id;
280
281                         if (array_key_exists("name", $userdata) AND ($userdata["name"] != "") AND !link_compare($userdata["link"], $postarray['author-link'])) {
282                                 $postarray['owner-name'] = $userdata["name"];
283                                 $postarray['owner-link'] = $userdata["link"];
284                                 $postarray['owner-avatar'] = $userdata["avatar"];
285
286                                 if (!intval(get_config('system','wall-to-wall_share'))) {
287
288                                         $prebody = "[share author='".$postarray['author-name'].
289                                                 "' profile='".$postarray['author-link'].
290                                                 "' avatar='".$postarray['author-avatar']."']";
291
292                                         $postarray['author-name'] = $postarray['owner-name'];
293                                         $postarray['author-link'] = $postarray['owner-link'];
294                                         $postarray['author-avatar'] = $postarray['owner-avatar'];
295                                 }
296                         }
297                 }
298         }
299
300         if ($contact_id <= 0) {
301                 if ($post->actor_id != $post->source_id) {
302                         // Testing if we know the source or the actor
303                         $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], false);
304
305                         if (($contact_id == 0) and array_key_exists($post->actor_id, $contacts))
306                                 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->actor_id], false);
307
308                         // If we don't know anyone, we guess we should know the source. Could be the wrong decision
309                         if ($contact_id == 0)
310                                 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
311                 } else
312                         $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
313
314
315                 if ($contact_id == -1) {
316                         logger('fbsync_createpost: Contact is blocked. Post not imported '.print_r($post, true), LOGGER_DEBUG);
317                         return;
318                 } elseif (($contact_id <= 0) AND !$create_user) {
319                         logger('fbsync_createpost: No matching contact found. Post not imported '.print_r($post, true), LOGGER_DEBUG);
320                         return;
321                 } elseif ($contact_id == 0) {
322                         // This case should never happen
323                         logger('fbsync_createpost: No matching contact found. Using own id. (Should never happen) '.print_r($post, true), LOGGER_DEBUG);
324                         $contact_id = $self[0]["id"];
325                 }
326
327                 $postarray['contact-id'] = $contact_id;
328         }
329
330         $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
331
332         $msgdata = fbsync_convertmsg($a, $postarray["body"]);
333
334         $postarray["body"] = $msgdata["body"];
335         $postarray["tag"] = $msgdata["tags"];
336
337         // Change the object type when an attachment is present
338         if (isset($post->attachment->fb_object_type))
339                 logger('fb_object_type: '.$post->attachment->fb_object_type." ".print_r($post->attachment, true), LOGGER_DEBUG);
340                 switch ($post->attachment->fb_object_type) {
341                         case 'photo':
342                                 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE; // photo is deprecated: http://activitystrea.ms/head/activity-schema.html#image
343                                 break;
344                         case 'video':
345                                 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
346                                 break;
347                         case '':
348                                 //$postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
349                                 break;
350                         default:
351                                 logger('Unknown object type '.$post->attachment->fb_object_type, LOGGER_DEBUG);
352                                 break;
353                 }
354
355         $pagedata = array();
356         $content = "";
357         $pagedata["type"] = "";
358
359         if (isset($post->attachment->name) and isset($post->attachment->href)) {
360                 $post->attachment->href = original_url($post->attachment->href);
361                 $oembed_data = oembed_fetch_url($post->attachment->href);
362                 $pagedata["type"] = $oembed_data->type;
363                 if ($pagedata["type"] == "rich")
364                         $pagedata["type"] = "link";
365
366                 $pagedata["url"] = $post->attachment->href;
367                 $pagedata["title"] = $post->attachment->name;
368                 $content = "[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
369
370                 // If a link is not only attached but also added in the body, look if it can be removed in the body.
371                 $removedlink = trim(str_replace($post->attachment->href, "", $postarray["body"]));
372
373                 if (($removedlink == "") OR strstr($postarray["body"], $removedlink))
374                         $postarray["body"] = $removedlink;
375
376         } elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
377                 $content = "[b]" . $post->attachment->name."[/b]";
378
379         $pagedata["text"] = "";
380         if (isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
381                 $pagedata["text"] = $post->attachment->description;
382
383         if (isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
384                 $pagedata["text"] = $post->attachment->caption;
385
386         if ($pagedata["text"].$post->attachment->href.$content.$postarray["body"] == "")
387                 return;
388
389         if (isset($post->attachment->media) AND (($pagedata["type"] == "") OR ($pagedata["type"] == "link"))) {
390                 foreach ($post->attachment->media AS $media) {
391
392                         if (isset($media->type))
393                                 $pagedata["type"] = $media->type;
394
395                         if (isset($media->src))
396                                 $pagedata["images"][0]["src"] = $media->src;
397
398                         if (isset($media->photo)) {
399                                 if (isset($media->photo->images) AND (count($media->photo->images) > 1))
400                                         $pagedata["images"][0]["src"] = $media->photo->images[1]->src;
401
402                                 if (isset($media->photo->fbid)) {
403                                         logger('fbsync_createpost: fetching fbid '.$media->photo->fbid, LOGGER_DEBUG);
404                                         $url = "https://graph.facebook.com/".$media->photo->fbid."?access_token=".$access_token;
405                                         $feed = fetch_url($url);
406                                         $data = json_decode($feed);
407                                         if (isset($data->images)) {
408                                                 $pagedata["images"][0]["src"] = $data->images[0]->source;
409                                                 logger('fbsync_createpost: got fbid '.$media->photo->fbid.' image '.$pagedata["images"][0]["src"], LOGGER_DEBUG);
410                                         } else
411                                                 logger('fbsync_createpost: error fetching fbid '.$media->photo->fbid.' '.print_r($data, true), LOGGER_DEBUG);
412                                 }
413                         }
414
415                         $pagedata["images"][0]["src"] = fbpost_cleanpicture($pagedata["images"][0]["src"]);
416
417                         if (isset($media->href) AND ($pagedata["images"][0]["src"] != "") AND ($media->href != "")) {
418                                 $media->href = original_url($media->href);
419                                 $pagedata["url"] = $media->href;
420                                 $content .= "\n".'[url='.$media->href.'][img]'.$pagedata["images"][0]["src"].'[/img][/url]';
421                         } else {
422                                 if ($pagedata["images"][0]["src"] != "")
423                                         $content .= "\n".'[img]'.$pagedata["images"][0]["src"].'[/img]';
424
425                                 // if just a link, it may be a wall photo - check
426                                 if (isset($post->link))
427                                         $content .= fbpost_get_photo($media->href);
428                         }
429                 }
430         }
431
432         if ($pagedata["type"] != "") {
433                 if ($pagedata["type"] == "link")
434                         $postarray["object-type"] = ACTIVITY_OBJ_BOOKMARK;
435
436                 $postarray["body"] .= add_page_info_data($pagedata);
437         } else {
438                 if ($content)
439                         $postarray["body"] .= "\n".trim($content);
440
441                 if ($pagedata["text"])
442                         $postarray["body"] .= "\n[quote]".trim($pagedata["text"])."[/quote]";
443
444                 $postarray["body"] = trim($postarray["body"]);
445         }
446
447         if (trim($postarray["body"]) == "")
448                 return;
449
450         if ($prebody != "")
451                 $postarray["body"] = $prebody.$postarray["body"]."[/share]";
452
453         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
454         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
455
456         $postarray['app'] = $applications[$post->app_id]->display_name;
457
458         if ($postarray['app'] == "")
459                 $postarray['app'] = "Facebook";
460
461         if(isset($post->privacy) && $post->privacy->value !== '') {
462                 $postarray['private'] = 1;
463                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
464         }
465
466         /*
467         $postarray["location"] = $post->place->name;
468         postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
469         */
470
471         //$types = array(46, 80, 237, 247, 308);
472         //if (!in_array($post->type, $types))
473         //      $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
474         //print_r($post);
475         //print_r($postarray);
476         $item = item_store($postarray);
477         logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
478 }
479
480 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
481
482         // check if it was already imported
483         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
484                 intval($uid),
485                 dbesc('fb::'.$comment->id)
486         );
487         if(count($r))
488                 return;
489
490         // check if it was an own post (separate posting for performance reasons)
491         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
492                 intval($uid),
493                 dbesc('fb::'.$comment->id)
494         );
495         if(count($r))
496                 return;
497
498         $parent_uri = "";
499         $parent_contact = 0;
500         $parent_nick = "";
501
502         // Fetch the parent uri (Checking if the parent exists)
503         $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
504                 intval($uid),
505                 dbesc('fb::'.$comment->post_id)
506         );
507         if(count($r)) {
508                 $parent_uri = $r[0]["uri"];
509                 $parent_contact = $r[0]["contact-id"];
510         }
511
512         // check if it is a reply to an own post (separate posting for performance reasons)
513         $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
514                 intval($uid),
515                 dbesc('fb::'.$comment->post_id)
516         );
517         if(count($r)) {
518                 $parent_uri = $r[0]["uri"];
519                 $parent_contact = $r[0]["contact-id"];
520         }
521
522         // No parent? Then quit
523         if ($parent_uri == "")
524                 return;
525
526         //logger("fbsync_createcomment: Checking if parent contact is blocked: ".$parent_contact." - ".$parent_uri, LOGGER_DEBUG);
527
528         // Check if the contact id was blocked
529         if ($parent_contact > 0) {
530                 $r = q("SELECT `blocked`, `readonly`, `nick` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
531                         intval($uid), intval($parent_contact));
532
533                 // Should only happen if someone deleted the contact manually
534                 if(!count($r)) {
535                         logger("fbsync_createcomment: UID ".$uid." - Contact ".$parent_contact." doesn't seem to exist.", LOGGER_DEBUG);
536                         return;
537                 }
538
539                 // Is blocked? Then return
540                 if ($r[0]["readonly"] OR $r[0]["blocked"]) {
541                         logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
542                         return;
543                 }
544
545                 $parent_nick = $r[0]["nick"];
546                 logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' isn't blocked. ".print_r($r, true), LOGGER_DEBUG);
547         }
548
549         $postarray = array();
550         $postarray['gravity'] = 0;
551         $postarray['uid'] = $uid;
552         $postarray['wall'] = 0;
553
554         $postarray['verb'] = ACTIVITY_POST;
555         $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
556         $postarray['network'] =  dbesc(NETWORK_FACEBOOK);
557
558         $postarray['uri'] = "fb::".$comment->id;
559         $postarray['thr-parent'] = $parent_uri;
560         $postarray['parent-uri'] = $parent_uri;
561         //$postarray['plink'] = $comment->permalink;
562
563         $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
564
565         $contact_nick = $contacts[$comment->fromid]->name;
566
567         if ($contact_id == -1) {
568                 logger('fbsync_createcomment: Contact was blocked. Comment not imported '.print_r($comment, true), LOGGER_DEBUG);
569                 return;
570         }
571
572         // If no contact was found, take it from the thread owner
573         if ($contact_id <= 0) {
574                 $contact_id = $parent_contact;
575                 $contact_nick = $parent_nick;
576         }
577
578         // This case here should never happen
579         if ($contact_id <= 0) {
580                 $contact_id = $self[0]["id"];
581                 $contact_nick = $self[0]["nick"];
582         }
583
584         if ($comment->fromid != $self_id) {
585                 $postarray['contact-id'] = $contact_id;
586                 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
587                 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
588                 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
589         } else {
590                 $postarray['contact-id'] = $self[0]["id"];
591                 $postarray['owner-name'] = $self[0]["name"];
592                 $postarray['owner-link'] = $self[0]["url"];
593                 $postarray['owner-avatar'] = $self[0]["photo"];
594                 $contact_nick = $self[0]["nick"];
595         }
596
597         $postarray['author-name'] = $postarray['owner-name'];
598         $postarray['author-link'] = $postarray['owner-link'];
599         $postarray['author-avatar'] = $postarray['owner-avatar'];
600
601         $msgdata = fbsync_convertmsg($a, $comment->text);
602
603         $postarray["body"] = $msgdata["body"];
604         $postarray["tag"] = $msgdata["tags"];
605
606         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
607         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
608
609         $postarray['app'] = $applications[$comment->app_id]->display_name;
610
611         if ($postarray['app'] == "")
612                 $postarray['app'] = "Facebook";
613
614         if (trim($postarray["body"]) == "")
615                 return;
616
617         $item = item_store($postarray);
618         logger('fbsync_createcomment: UID '.$uid.' - CID '.$postarray['contact-id'].' - Nick '.$contact_nick.' posted comment '.$item, LOGGER_DEBUG);
619
620         if ($item == 0)
621                 return;
622
623         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
624                 dbesc($postarray['parent-uri']),
625                 intval($uid)
626         );
627
628         if(count($myconv)) {
629                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
630
631                 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
632                         intval($uid), dbesc("facebook::".$self_id));
633
634                 if (!count($own_contact))
635                         return;
636
637                 foreach($myconv as $conv) {
638
639                         // now if we find a match, it means we're in this conversation
640                         if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
641                                 continue;
642
643                         require_once('include/enotify.php');
644
645                         $conv_parent = $conv['parent'];
646
647                         $notifyarr = array(
648                                         'type'         => NOTIFY_COMMENT,
649                                         'notify_flags' => $user[0]['notify-flags'],
650                                         'language'     => $user[0]['language'],
651                                         'to_name'      => $user[0]['username'],
652                                         'to_email'     => $user[0]['email'],
653                                         'uid'          => $user[0]['uid'],
654                                         'item'         => $postarray,
655                                         'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
656                                         'source_name'  => $postarray['author-name'],
657                                         'source_link'  => $postarray['author-link'],
658                                         'source_photo' => $postarray['author-avatar'],
659                                         'verb'         => ACTIVITY_POST,
660                                         'otype'        => 'item',
661                                         'parent'       => $conv_parent,
662                         );
663
664                         notification($notifyarr);
665
666                         // only send one notification
667                         break;
668                 }
669         }
670 }
671
672 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
673
674         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
675                                 dbesc("fb::".$like->post_id),
676                                 intval($uid)
677                 );
678
679         if (count($r))
680                 $orig_post = $r[0];
681         else
682                 return;
683
684         // If we posted the like locally, it will be found with our url, not the FB url.
685
686         $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
687
688         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
689                 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
690                 dbesc($orig_post["uri"]),
691                 intval($uid),
692                 dbesc(ACTIVITY_LIKE),
693                 dbesc($contacts[$like->user_id]->url),
694                 dbesc($second_url)
695         );
696
697         if (count($r))
698                 return;
699
700         $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
701
702         if ($contact_id <= 0)
703                 $contact_id = $self[0]["id"];
704
705         $likedata = array();
706         $likedata['parent'] = $orig_post['id'];
707
708         $likedata['verb'] = ACTIVITY_LIKE;
709         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
710         $likedate['network'] =  dbesc(NETWORK_FACEBOOK);
711
712         $likedata['gravity'] = 3;
713         $likedata['uid'] = $uid;
714         $likedata['wall'] = 0;
715         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
716         $likedata['parent-uri'] = $orig_post["uri"];
717         $likedata['app'] = "Facebook";
718
719         if ($like->user_id != $self_id) {
720                 $likedata['contact-id'] = $contact_id;
721                 $likedata['author-name'] = $contacts[$like->user_id]->name;
722                 $likedata['author-link'] = $contacts[$like->user_id]->url;
723                 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
724         } else {
725                 $likedata['contact-id'] = $self[0]["id"];
726                 $likedata['author-name'] = $self[0]["name"];
727                 $likedata['author-link'] = $self[0]["url"];
728                 $likedata['author-avatar'] = $self[0]["photo"];
729         }
730
731         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
732
733         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
734         $post_type = t('status');
735
736         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
737         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
738
739         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
740
741         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
742                 '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . xmlify($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
743
744
745         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
746                                 dbesc($likedata['parent-uri']),
747                                 dbesc($likedata['author-link']),
748                                 dbesc(ACTIVITY_LIKE),
749                                 intval($uid)
750                 );
751
752         if (count($r))
753                 return;
754
755         $item = item_store($likedata);
756         logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
757 }
758
759 function fbsync_fetch_contact($uid, $contact, $create_user) {
760
761         if($contact->url == "")
762                 return(0);
763
764         // Check if the unique contact is existing
765         // To-Do: only update once a while
766         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
767                 dbesc(normalise_link($contact->url)));
768
769         if (count($r) == 0)
770                 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
771                         dbesc(normalise_link($contact->url)),
772                         dbesc($contact->name),
773                         dbesc($contact->username),
774                         dbesc($contact->pic_square));
775         else
776                 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
777                         dbesc($contact->name),
778                         dbesc($contact->username),
779                         dbesc($contact->pic_square),
780                         dbesc(normalise_link($contact->url)));
781
782         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
783                 intval($uid), dbesc("facebook::".$contact->id));
784
785         if(!count($r) AND !$create_user)
786                 return(0);
787
788         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
789                 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
790                 return(-1);
791         }
792
793         $avatarpicture = $contact->pic_square;
794
795         if(!count($r)) {
796                 // create contact record
797                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
798                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
799                                         `writable`, `blocked`, `readonly`, `pending`)
800                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
801                         intval($uid),
802                         dbesc(datetime_convert()),
803                         dbesc($contact->url),
804                         dbesc(normalise_link($contact->url)),
805                         dbesc($contact->username."@facebook.com"),
806                         dbesc("facebook::".$contact->id),
807                         dbesc($contact->id),
808                         dbesc("facebook::".$contact->id),
809                         dbesc($contact->name),
810                         dbesc($contact->username),
811                         dbesc($avatarpicture),
812                         dbesc(NETWORK_FACEBOOK),
813                         intval(CONTACT_IS_FRIEND),
814                         intval(1),
815                         intval(1)
816                 );
817
818                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
819                         dbesc("facebook::".$contact->id),
820                         intval($uid)
821                         );
822
823                 if(! count($r))
824                         return(false);
825
826                 $contact_id  = $r[0]['id'];
827
828                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
829                         intval($uid)
830                 );
831
832                 if($g && intval($g[0]['def_gid'])) {
833                         require_once('include/group.php');
834                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
835                 }
836
837                 require_once("Photo.php");
838
839                 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
840
841                 q("UPDATE `contact` SET `photo` = '%s',
842                                         `thumb` = '%s',
843                                         `micro` = '%s',
844                                         `name-date` = '%s',
845                                         `uri-date` = '%s',
846                                         `avatar-date` = '%s'
847                                 WHERE `id` = %d",
848                         dbesc($photos[0]),
849                         dbesc($photos[1]),
850                         dbesc($photos[2]),
851                         dbesc(datetime_convert()),
852                         dbesc(datetime_convert()),
853                         dbesc(datetime_convert()),
854                         intval($contact_id)
855                 );
856         } else {
857                 // update profile photos once every 12 hours as we have no notification of when they change.
858                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
859
860                 // check that we have all the photos, this has been known to fail on occasion
861                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
862
863                         logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
864
865                         require_once("Photo.php");
866
867                         $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
868
869                         q("UPDATE `contact` SET `photo` = '%s',
870                                                 `thumb` = '%s',
871                                                 `micro` = '%s',
872                                                 `name-date` = '%s',
873                                                 `uri-date` = '%s',
874                                                 `avatar-date` = '%s',
875                                                 `url` = '%s',
876                                                 `nurl` = '%s',
877                                                 `addr` = '%s',
878                                                 `name` = '%s',
879                                                 `nick` = '%s',
880                                                 `notify` = '%s'
881                                         WHERE `id` = %d",
882                                 dbesc($photos[0]),
883                                 dbesc($photos[1]),
884                                 dbesc($photos[2]),
885                                 dbesc(datetime_convert()),
886                                 dbesc(datetime_convert()),
887                                 dbesc(datetime_convert()),
888                                 dbesc($contact->url),
889                                 dbesc(normalise_link($contact->url)),
890                                 dbesc($contact->username."@facebook.com"),
891                                 dbesc($contact->name),
892                                 dbesc($contact->username),
893                                 dbesc($contact->id),
894                                 intval($r[0]['id'])
895                         );
896                 }
897         }
898         return($r[0]["id"]);
899 }
900
901 function fbsync_get_self($uid) {
902         $access_token = get_pconfig($uid,'facebook','access_token');
903         if(! $access_token)
904                 return;
905         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
906         if($s) {
907                 $j = json_decode($s);
908                 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
909         }
910 }
911
912 function fbsync_convertmsg($a, $body) {
913         $str_tags = '';
914
915         $tags = get_tags($body);
916
917         if(count($tags)) {
918                 foreach($tags as $tag) {
919                         if (strstr(trim($tag), " "))
920                                 continue;
921
922                         if(strpos($tag,'#') === 0) {
923                                 if(strpos($tag,'[url='))
924                                         continue;
925
926                                 // don't link tags that are already embedded in links
927
928                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
929                                         continue;
930                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
931                                         continue;
932
933                                 $basetag = str_replace('_',' ',substr($tag,1));
934                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
935                                 if(strlen($str_tags))
936                                         $str_tags .= ',';
937                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
938                                 continue;
939                         } elseif(strpos($tag,'@') === 0) {
940                                 $basetag = substr($tag,1);
941                                 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
942                         }
943
944                 }
945         }
946
947         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
948         if($cnt) {
949                 foreach($matches as $mtch) {
950                         if(strlen($str_tags))
951                                 $str_tags .= ',';
952                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
953                 }
954         }
955
956         return(array("body"=>$body, "tags"=>$str_tags));
957
958 }
959
960 function fbsync_fetchuser($a, $uid, $id) {
961         $access_token = get_pconfig($uid,'facebook','access_token');
962         $self_id = get_pconfig($uid,'fbsync','self_id');
963
964         $user = array();
965
966         $contact = q("SELECT `id`, `name`, `url`, `photo`  FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
967                 intval($uid), dbesc("facebook::".$id));
968
969         if (count($contact)) {
970                 if (($contact[0]["readonly"] OR $contact[0]["blocked"])) {
971                         logger("fbsync_fetchuser: Contact '".$contact[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
972                         $user["contact-id"] = -1;
973                 } else
974                         $user["contact-id"] = $contact[0]["id"];
975
976                 $user["name"] = $contact[0]["name"];
977                 $user["link"] = $contact[0]["url"];
978                 $user["avatar"] = $contact[0]["photo"];
979
980                 return($user);
981         }
982
983         $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
984                 intval($uid), dbesc("facebook::".$self_id));
985
986         if (!count($own_contact))
987                 return($user);
988
989         $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
990
991         $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
992
993         $feed = fetch_url($url);
994         $data = json_decode($feed);
995
996         if (is_array($data->data)) {
997                 $user["contact-id"] = $own_contact[0]["id"];
998                 $user["name"] = $data->data[0]->name;
999                 $user["link"] = $data->data[0]->url;
1000                 $user["avatar"] = $data->data[0]->pic_square;
1001         }
1002         return($user);
1003 }
1004
1005 function fbsync_fetchfeed($a, $uid) {
1006         $access_token = get_pconfig($uid,'facebook','access_token');
1007         $last_updated = get_pconfig($uid,'fbsync','last_updated');
1008         $self_id = get_pconfig($uid,'fbsync','self_id');
1009
1010         $create_user = get_pconfig($uid, 'fbsync', 'create_user');
1011         $do_likes = get_config('fbsync', 'do_likes');
1012
1013         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1014                 intval($uid)
1015         );
1016
1017         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1018                 intval($uid)
1019         );
1020         if(! count($user))
1021                 return;
1022
1023         require_once('include/items.php');
1024
1025         if ($last_updated == "")
1026                 $last_updated = 0;
1027
1028         logger("fbsync_fetchfeed: fetching content for user ".$self_id);
1029
1030         $fql = array(
1031                 "posts" => "SELECT action_links, actor_id, app_data, app_id, attachment, attribution, comment_info, created_time, filter_key, like_info, message, message_tags, parent_post_id, permalink, place, post_id, privacy, share_count, share_info, source_id, subscribed, tagged_ids, type, updated_time, with_tags FROM stream where filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed') AND updated_time > $last_updated ORDER BY updated_time DESC LIMIT 500",
1032                 "comments" => "SELECT app_id, attachment, post_id, id, likes, fromid, time, text, text_tags, user_likes, likes FROM comment WHERE post_id IN (SELECT post_id FROM #posts) ORDER BY time DESC LIMIT 500",
1033                 "profiles" => "SELECT id, name, username, url, pic_square FROM profile WHERE id IN (SELECT actor_id FROM #posts) OR id IN (SELECT fromid FROM #comments) OR id IN (SELECT source_id FROM #posts) LIMIT 500",
1034                 "applications" => "SELECT app_id, display_name FROM application WHERE app_id IN (SELECT app_id FROM #posts) OR app_id IN (SELECT app_id FROM #comments) LIMIT 500",
1035                 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
1036
1037         if ($do_likes) {
1038                 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
1039                 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
1040         }
1041
1042         $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
1043
1044         $feed = fetch_url($url);
1045         $data = json_decode($feed);
1046
1047         if (!is_array($data->data)) {
1048                 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
1049                 return;
1050         }
1051
1052         $posts = array();
1053         $comments = array();
1054         $likes = array();
1055         $profiles = array();
1056         $applications = array();
1057         $avatars = array();
1058
1059         foreach($data->data AS $query) {
1060                 switch ($query->name) {
1061                         case "posts":
1062                                 $posts = array_reverse($query->fql_result_set);
1063                                 break;
1064                         case "comments":
1065                                 $comments = $query->fql_result_set;
1066                                 break;
1067                         case "likes":
1068                                 $likes = $query->fql_result_set;
1069                                 break;
1070                         case "profiles":
1071                                 $profiles = $query->fql_result_set;
1072                                 break;
1073                         case "applications":
1074                                 $applications = $query->fql_result_set;
1075                                 break;
1076                         case "avatars":
1077                                 $avatars = $query->fql_result_set;
1078                                 break;
1079                 }
1080         }
1081
1082         $square_avatars = array();
1083         $contacts = array();
1084         $application_data = array();
1085         $post_data = array();
1086         $comment_data = array();
1087
1088         foreach ($avatars AS $avatar) {
1089                 $avatar->id = number_format($avatar->id, 0, '', '');
1090                 $square_avatars[$avatar->id] = $avatar;
1091         }
1092         unset($avatars);
1093
1094         foreach ($profiles AS $profile) {
1095                 $profile->id = number_format($profile->id, 0, '', '');
1096
1097                 if ($square_avatars[$profile->id]->url != "")
1098                         $profile->pic_square = $square_avatars[$profile->id]->url;
1099
1100                 $contacts[$profile->id] = $profile;
1101         }
1102         unset($profiles);
1103         unset($square_avatars);
1104
1105         foreach ($applications AS $application) {
1106                 $application->app_id = number_format($application->app_id, 0, '', '');
1107                 $application_data[$application->app_id] = $application;
1108         }
1109         unset($applications);
1110
1111         foreach ($posts AS $post) {
1112                 $post->actor_id = number_format($post->actor_id, 0, '', '');
1113                 $post->source_id = number_format($post->source_id, 0, '', '');
1114                 $post->app_id = number_format($post->app_id, 0, '', '');
1115                 $post_data[$post->post_id] = $post;
1116         }
1117         unset($posts);
1118
1119         foreach($comments AS $comment) {
1120                 $comment->fromid = number_format($comment->fromid, 0, '', '');
1121                 $comment_data[$comment->id] = $comment;
1122         }
1123         unset($comments);
1124
1125         foreach ($post_data AS $post) {
1126                 if ($post->updated_time > $last_updated)
1127                         $last_updated = $post->updated_time;
1128                 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
1129         }
1130
1131         foreach ($comment_data AS $comment) {
1132                 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
1133         }
1134
1135         foreach($likes AS $like) {
1136                 $like->user_id = number_format($like->user_id, 0, '', '');
1137
1138                 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
1139         }
1140
1141         set_pconfig($uid,'fbsync','last_updated', $last_updated);
1142 }
1143 ?>