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