]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch '0.9.x' of git@gitorious.org:statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  *
19  * @category Notices
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
36     exit(1);
37 }
38
39 /**
40  * Table Definition for notice
41  */
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
43
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45  * in the memcached cache. */
46
47 define('NOTICE_CACHE_WINDOW', 61);
48
49 define('MAX_BOXCARS', 128);
50
51 class Notice extends Memcached_DataObject
52 {
53     ###START_AUTOCODE
54     /* the code below is auto generated do not remove the above tag */
55
56     public $__table = 'notice';                          // table name
57     public $id;                              // int(4)  primary_key not_null
58     public $profile_id;                      // int(4)  multiple_key not_null
59     public $uri;                             // varchar(255)  unique_key
60     public $content;                         // text
61     public $rendered;                        // text
62     public $url;                             // varchar(255)
63     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
64     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // int(4)
67     public $source;                          // varchar(32)
68     public $conversation;                    // int(4)
69     public $lat;                             // decimal(10,7)
70     public $lon;                             // decimal(10,7)
71     public $location_id;                     // int(4)
72     public $location_ns;                     // int(4)
73     public $repeat_of;                       // int(4)
74
75     /* Static get */
76     function staticGet($k,$v=NULL)
77     {
78         return Memcached_DataObject::staticGet('Notice',$k,$v);
79     }
80
81     /* the code above is auto generated do not remove the tag below */
82     ###END_AUTOCODE
83
84     /* Notice types */
85     const LOCAL_PUBLIC    =  1;
86     const REMOTE_OMB      =  0;
87     const LOCAL_NONPUBLIC = -1;
88     const GATEWAY         = -2;
89
90     function getProfile()
91     {
92         return Profile::staticGet('id', $this->profile_id);
93     }
94
95     function delete()
96     {
97         $this->blowCaches(true);
98         $this->blowFavesCache(true);
99         $this->blowSubsCache(true);
100
101         // For auditing purposes, save a record that the notice
102         // was deleted.
103
104         $deleted = new Deleted_notice();
105
106         $deleted->id         = $this->id;
107         $deleted->profile_id = $this->profile_id;
108         $deleted->uri        = $this->uri;
109         $deleted->created    = $this->created;
110         $deleted->deleted    = common_sql_now();
111
112         $this->query('BEGIN');
113
114         $deleted->insert();
115
116         //Null any notices that are replies to this notice
117         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
118
119         //Null any notices that are repeats of this notice
120         //XXX: probably need to uncache these, too
121
122         $this->query(sprintf("UPDATE notice set repeat_of = null WHERE repeat_of = %d", $this->id));
123
124         $related = array('Reply',
125                          'Fave',
126                          'Notice_tag',
127                          'Group_inbox',
128                          'Queue_item');
129
130         foreach ($related as $cls) {
131             $inst = new $cls();
132             $inst->notice_id = $this->id;
133             $inst->delete();
134         }
135         $result = parent::delete();
136         $this->query('COMMIT');
137     }
138
139     function saveTags()
140     {
141         /* extract all #hastags */
142         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
143         if (!$count) {
144             return true;
145         }
146
147         //turn each into their canonical tag
148         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
149         $hashtags = array();
150         for($i=0; $i<count($match[1]); $i++) {
151             $hashtags[] = common_canonical_tag($match[1][$i]);
152         }
153
154         /* Add them to the database */
155         foreach(array_unique($hashtags) as $hashtag) {
156             /* elide characters we don't want in the tag */
157             $this->saveTag($hashtag);
158         }
159         return true;
160     }
161
162     function saveTag($hashtag)
163     {
164         $tag = new Notice_tag();
165         $tag->notice_id = $this->id;
166         $tag->tag = $hashtag;
167         $tag->created = $this->created;
168         $id = $tag->insert();
169
170         if (!$id) {
171             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
172                                               $last_error->message));
173             return;
174         }
175     }
176
177     /**
178      * Save a new notice and push it out to subscribers' inboxes.
179      * Poster's permissions are checked before sending.
180      *
181      * @param int $profile_id Profile ID of the poster
182      * @param string $content source message text; links may be shortened
183      *                        per current user's preference
184      * @param string $source source key ('web', 'api', etc)
185      * @param array $options Associative array of optional properties:
186      *              string 'created' timestamp of notice; defaults to now
187      *              int 'is_local' source/gateway ID, one of:
188      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
189      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
190      *                                            hide from public timeline but show in
191      *                                            local "and friends" timelines
192      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
193      *                  Notice::GATEWAY         - From another non-OMB service;
194      *                                            will not appear in public views
195      *              float 'lat' decimal latitude for geolocation
196      *              float 'lon' decimal longitude for geolocation
197      *              int 'location_id' geoname identifier
198      *              int 'location_ns' geoname namespace to interpret location_id
199      *              int 'reply_to'; notice ID this is a reply to
200      *              int 'repeat_of'; notice ID this is a repeat of
201      *              string 'uri' permalink to notice; defaults to local notice URL
202      *
203      * @return Notice
204      * @throws ClientException
205      */
206     static function saveNew($profile_id, $content, $source, $options=null) {
207         $defaults = array('uri' => null,
208                           'reply_to' => null,
209                           'repeat_of' => null);
210
211         if (!empty($options)) {
212             $options = $options + $defaults;
213             extract($options);
214         }
215
216         if (!isset($is_local)) {
217             $is_local = Notice::LOCAL_PUBLIC;
218         }
219
220         $profile = Profile::staticGet($profile_id);
221
222         $final = common_shorten_links($content);
223
224         if (Notice::contentTooLong($final)) {
225             throw new ClientException(_('Problem saving notice. Too long.'));
226         }
227
228         if (empty($profile)) {
229             throw new ClientException(_('Problem saving notice. Unknown user.'));
230         }
231
232         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
233             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
234             throw new ClientException(_('Too many notices too fast; take a breather '.
235                                         'and post again in a few minutes.'));
236         }
237
238         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
239             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
240             throw new ClientException(_('Too many duplicate messages too quickly;'.
241                                         ' take a breather and post again in a few minutes.'));
242         }
243
244         if (!$profile->hasRight(Right::NEWNOTICE)) {
245             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
246             throw new ClientException(_('You are banned from posting notices on this site.'));
247         }
248
249         $notice = new Notice();
250         $notice->profile_id = $profile_id;
251
252         $autosource = common_config('public', 'autosource');
253
254         # Sandboxed are non-false, but not 1, either
255
256         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
257             ($source && $autosource && in_array($source, $autosource))) {
258             $notice->is_local = Notice::LOCAL_NONPUBLIC;
259         } else {
260             $notice->is_local = $is_local;
261         }
262
263         if (!empty($created)) {
264             $notice->created = $created;
265         } else {
266             $notice->created = common_sql_now();
267         }
268
269         $notice->content = $final;
270         $notice->rendered = common_render_content($final, $notice);
271         $notice->source = $source;
272         $notice->uri = $uri;
273
274         // Handle repeat case
275
276         if (isset($repeat_of)) {
277             $notice->repeat_of = $repeat_of;
278         } else {
279             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
280         }
281
282         if (!empty($notice->reply_to)) {
283             $reply = Notice::staticGet('id', $notice->reply_to);
284             $notice->conversation = $reply->conversation;
285         }
286
287         if (!empty($lat) && !empty($lon)) {
288             $notice->lat = $lat;
289             $notice->lon = $lon;
290         }
291
292         if (!empty($location_ns) && !empty($location_id)) {
293             $notice->location_id = $location_id;
294             $notice->location_ns = $location_ns;
295         }
296
297         if (Event::handle('StartNoticeSave', array(&$notice))) {
298
299             // XXX: some of these functions write to the DB
300
301             $id = $notice->insert();
302
303             if (!$id) {
304                 common_log_db_error($notice, 'INSERT', __FILE__);
305                 throw new ServerException(_('Problem saving notice.'));
306             }
307
308             // Update ID-dependent columns: URI, conversation
309
310             $orig = clone($notice);
311
312             $changed = false;
313
314             if (empty($uri)) {
315                 $notice->uri = common_notice_uri($notice);
316                 $changed = true;
317             }
318
319             // If it's not part of a conversation, it's
320             // the beginning of a new conversation.
321
322             if (empty($notice->conversation)) {
323                 $notice->conversation = $notice->id;
324                 $changed = true;
325             }
326
327             if ($changed) {
328                 if (!$notice->update($orig)) {
329                     common_log_db_error($notice, 'UPDATE', __FILE__);
330                     throw new ServerException(_('Problem saving notice.'));
331                 }
332             }
333
334             // XXX: do we need to change this for remote users?
335
336             $notice->saveTags();
337
338             $groups = $notice->saveGroups();
339
340             $recipients = $notice->saveReplies();
341
342             $notice->addToInboxes($groups, $recipients);
343
344             $notice->saveUrls();
345
346             Event::handle('EndNoticeSave', array($notice));
347         }
348
349         # Clear the cache for subscribed users, so they'll update at next request
350         # XXX: someone clever could prepend instead of clearing the cache
351
352         $notice->blowCaches();
353
354         return $notice;
355     }
356
357     /** save all urls in the notice to the db
358      *
359      * follow redirects and save all available file information
360      * (mimetype, date, size, oembed, etc.)
361      *
362      * @return void
363      */
364     function saveUrls() {
365         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
366     }
367
368     function saveUrl($data) {
369         list($url, $notice_id) = $data;
370         File::processNew($url, $notice_id);
371     }
372
373     static function checkDupes($profile_id, $content) {
374         $profile = Profile::staticGet($profile_id);
375         if (empty($profile)) {
376             return false;
377         }
378         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
379         if (!empty($notice)) {
380             $last = 0;
381             while ($notice->fetch()) {
382                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
383                     return true;
384                 } else if ($notice->content == $content) {
385                     return false;
386                 }
387             }
388         }
389         # If we get here, oldest item in cache window is not
390         # old enough for dupe limit; do direct check against DB
391         $notice = new Notice();
392         $notice->profile_id = $profile_id;
393         $notice->content = $content;
394         if (common_config('db','type') == 'pgsql')
395           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
396         else
397           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
398
399         $cnt = $notice->count();
400         return ($cnt == 0);
401     }
402
403     static function checkEditThrottle($profile_id) {
404         $profile = Profile::staticGet($profile_id);
405         if (empty($profile)) {
406             return false;
407         }
408         # Get the Nth notice
409         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
410         if ($notice && $notice->fetch()) {
411             # If the Nth notice was posted less than timespan seconds ago
412             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
413                 # Then we throttle
414                 return false;
415             }
416         }
417         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
418         return true;
419     }
420
421     function getUploadedAttachment() {
422         $post = clone $this;
423         $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
424         $post->query($query);
425         $post->fetch();
426         if (empty($post->up) || empty($post->i)) {
427             $ret = false;
428         } else {
429             $ret = array($post->up, $post->i);
430         }
431         $post->free();
432         return $ret;
433     }
434
435     function hasAttachments() {
436         $post = clone $this;
437         $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
438         $post->query($query);
439         $post->fetch();
440         $n_attachments = intval($post->n_attachments);
441         $post->free();
442         return $n_attachments;
443     }
444
445     function attachments() {
446         // XXX: cache this
447         $att = array();
448         $f2p = new File_to_post;
449         $f2p->post_id = $this->id;
450         if ($f2p->find()) {
451             while ($f2p->fetch()) {
452                 $f = File::staticGet($f2p->file_id);
453                 $att[] = clone($f);
454             }
455         }
456         return $att;
457     }
458
459     function blowCaches($blowLast=false)
460     {
461         $this->blowSubsCache($blowLast);
462         $this->blowNoticeCache($blowLast);
463         $this->blowRepliesCache($blowLast);
464         $this->blowPublicCache($blowLast);
465         $this->blowTagCache($blowLast);
466         $this->blowGroupCache($blowLast);
467         $this->blowConversationCache($blowLast);
468         $this->blowRepeatCache();
469         $profile = Profile::staticGet($this->profile_id);
470         $profile->blowNoticeCount();
471     }
472
473     function blowRepeatCache()
474     {
475         if (!empty($this->repeat_of)) {
476             $cache = common_memcache();
477             if (!empty($cache)) {
478                 // XXX: only blow if <100 in cache
479                 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
480                 $result = $cache->delete($ck);
481
482                 $user = User::staticGet('id', $this->profile_id);
483
484                 if (!empty($user)) {
485                     $uk = common_cache_key('user:repeated_by_me:'.$user->id);
486                     $cache->delete($uk);
487                     $user->free();
488                     unset($user);
489                 }
490
491                 $original = Notice::staticGet('id', $this->repeat_of);
492
493                 if (!empty($original)) {
494                     $originalUser = User::staticGet('id', $original->profile_id);
495                     if (!empty($originalUser)) {
496                         $ouk = common_cache_key('user:repeats_of_me:'.$originalUser->id);
497                         $cache->delete($ouk);
498                         $originalUser->free();
499                         unset($originalUser);
500                     }
501                     $original->free();
502                     unset($original);
503                 }
504             }
505         }
506     }
507
508     function blowConversationCache($blowLast=false)
509     {
510         $cache = common_memcache();
511         if ($cache) {
512             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
513             $cache->delete($ck);
514             if ($blowLast) {
515                 $cache->delete($ck.';last');
516             }
517         }
518     }
519
520     function blowGroupCache($blowLast=false)
521     {
522         $cache = common_memcache();
523         if ($cache) {
524             $group_inbox = new Group_inbox();
525             $group_inbox->notice_id = $this->id;
526             if ($group_inbox->find()) {
527                 while ($group_inbox->fetch()) {
528                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
529                     if ($blowLast) {
530                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
531                     }
532                     $member = new Group_member();
533                     $member->group_id = $group_inbox->group_id;
534                     if ($member->find()) {
535                         while ($member->fetch()) {
536                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
537                             $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id));
538                             if (empty($this->repeat_of)) {
539                                 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id));
540                                 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id));
541                             }
542                             if ($blowLast) {
543                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
544                                 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id . ';last'));
545                                 if (empty($this->repeat_of)) {
546                                     $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id . ';last'));
547                                     $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id . ';last'));
548                                 }
549                             }
550                         }
551                     }
552                 }
553             }
554             $group_inbox->free();
555             unset($group_inbox);
556         }
557     }
558
559     function blowTagCache($blowLast=false)
560     {
561         $cache = common_memcache();
562         if ($cache) {
563             $tag = new Notice_tag();
564             $tag->notice_id = $this->id;
565             if ($tag->find()) {
566                 while ($tag->fetch()) {
567                     $tag->blowCache($blowLast);
568                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
569
570                     $cache->delete($ck);
571                     if ($blowLast) {
572                         $cache->delete($ck . ';last');
573                     }
574                 }
575             }
576             $tag->free();
577             unset($tag);
578         }
579     }
580
581     function blowSubsCache($blowLast=false)
582     {
583         $cache = common_memcache();
584         if ($cache) {
585             $user = new User();
586
587             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
588             $user->query('SELECT id ' .
589
590                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
591                          'WHERE subscription.subscribed = ' . $this->profile_id);
592
593             while ($user->fetch()) {
594                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
595                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
596                 if (empty($this->repeat_of)) {
597                     $cache->delete(common_cache_key('user:friends_timeline:'.$user->id));
598                     $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id));
599                 }
600                 if ($blowLast) {
601                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
602                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
603                     if (empty($this->repeat_of)) {
604                         $cache->delete(common_cache_key('user:friends_timeline:'.$user->id.';last'));
605                         $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id.';last'));
606                     }
607                 }
608             }
609             $user->free();
610             unset($user);
611         }
612     }
613
614     function blowNoticeCache($blowLast=false)
615     {
616         if ($this->is_local) {
617             $cache = common_memcache();
618             if (!empty($cache)) {
619                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
620                 if ($blowLast) {
621                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
622                 }
623             }
624         }
625     }
626
627     function blowRepliesCache($blowLast=false)
628     {
629         $cache = common_memcache();
630         if ($cache) {
631             $reply = new Reply();
632             $reply->notice_id = $this->id;
633             if ($reply->find()) {
634                 while ($reply->fetch()) {
635                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
636                     if ($blowLast) {
637                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
638                     }
639                 }
640             }
641             $reply->free();
642             unset($reply);
643         }
644     }
645
646     function blowPublicCache($blowLast=false)
647     {
648         if ($this->is_local == Notice::LOCAL_PUBLIC) {
649             $cache = common_memcache();
650             if ($cache) {
651                 $cache->delete(common_cache_key('public'));
652                 if ($blowLast) {
653                     $cache->delete(common_cache_key('public').';last');
654                 }
655             }
656         }
657     }
658
659     function blowFavesCache($blowLast=false)
660     {
661         $cache = common_memcache();
662         if ($cache) {
663             $fave = new Fave();
664             $fave->notice_id = $this->id;
665             if ($fave->find()) {
666                 while ($fave->fetch()) {
667                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
668                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
669                     if ($blowLast) {
670                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
671                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
672                     }
673                 }
674             }
675             $fave->free();
676             unset($fave);
677         }
678     }
679
680     function getStreamByIds($ids)
681     {
682         $cache = common_memcache();
683
684         if (!empty($cache)) {
685             $notices = array();
686             foreach ($ids as $id) {
687                 $n = Notice::staticGet('id', $id);
688                 if (!empty($n)) {
689                     $notices[] = $n;
690                 }
691             }
692             return new ArrayWrapper($notices);
693         } else {
694             $notice = new Notice();
695             if (empty($ids)) {
696                 //if no IDs requested, just return the notice object
697                 return $notice;
698             }
699             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
700
701             $notice->find();
702
703             $temp = array();
704
705             while ($notice->fetch()) {
706                 $temp[$notice->id] = clone($notice);
707             }
708
709             $wrapped = array();
710
711             foreach ($ids as $id) {
712                 if (array_key_exists($id, $temp)) {
713                     $wrapped[] = $temp[$id];
714                 }
715             }
716
717             return new ArrayWrapper($wrapped);
718         }
719     }
720
721     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
722     {
723         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
724                               array(),
725                               'public',
726                               $offset, $limit, $since_id, $max_id, $since);
727
728         return Notice::getStreamByIds($ids);
729     }
730
731     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
732     {
733         $notice = new Notice();
734
735         $notice->selectAdd(); // clears it
736         $notice->selectAdd('id');
737
738         $notice->orderBy('id DESC');
739
740         if (!is_null($offset)) {
741             $notice->limit($offset, $limit);
742         }
743
744         if (common_config('public', 'localonly')) {
745             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
746         } else {
747             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
748             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
749             $notice->whereAdd('is_local !='. Notice::GATEWAY);
750         }
751
752         if ($since_id != 0) {
753             $notice->whereAdd('id > ' . $since_id);
754         }
755
756         if ($max_id != 0) {
757             $notice->whereAdd('id <= ' . $max_id);
758         }
759
760         if (!is_null($since)) {
761             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
762         }
763
764         $ids = array();
765
766         if ($notice->find()) {
767             while ($notice->fetch()) {
768                 $ids[] = $notice->id;
769             }
770         }
771
772         $notice->free();
773         $notice = NULL;
774
775         return $ids;
776     }
777
778     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
779     {
780         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
781                               array($id),
782                               'notice:conversation_ids:'.$id,
783                               $offset, $limit, $since_id, $max_id, $since);
784
785         return Notice::getStreamByIds($ids);
786     }
787
788     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
789     {
790         $notice = new Notice();
791
792         $notice->selectAdd(); // clears it
793         $notice->selectAdd('id');
794
795         $notice->conversation = $id;
796
797         $notice->orderBy('id DESC');
798
799         if (!is_null($offset)) {
800             $notice->limit($offset, $limit);
801         }
802
803         if ($since_id != 0) {
804             $notice->whereAdd('id > ' . $since_id);
805         }
806
807         if ($max_id != 0) {
808             $notice->whereAdd('id <= ' . $max_id);
809         }
810
811         if (!is_null($since)) {
812             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
813         }
814
815         $ids = array();
816
817         if ($notice->find()) {
818             while ($notice->fetch()) {
819                 $ids[] = $notice->id;
820             }
821         }
822
823         $notice->free();
824         $notice = NULL;
825
826         return $ids;
827     }
828
829     function whoGets($groups=null, $recipients=null)
830     {
831         $c = self::memcache();
832
833         if (!empty($c)) {
834             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
835             if ($ni !== false) {
836                 return $ni;
837             }
838         }
839
840         if (is_null($groups)) {
841             $groups = $this->getGroups();
842         }
843
844         if (is_null($recipients)) {
845             $recipients = $this->getReplies();
846         }
847
848         $users = $this->getSubscribedUsers();
849
850         // FIXME: kind of ignoring 'transitional'...
851         // we'll probably stop supporting inboxless mode
852         // in 0.9.x
853
854         $ni = array();
855
856         foreach ($users as $id) {
857             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
858         }
859
860         $profile = $this->getProfile();
861
862         foreach ($groups as $group) {
863             $users = $group->getUserMembers();
864             foreach ($users as $id) {
865                 if (!array_key_exists($id, $ni)) {
866                     $user = User::staticGet('id', $id);
867                     if (!$user->hasBlocked($profile)) {
868                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
869                     }
870                 }
871             }
872         }
873
874         foreach ($recipients as $recipient) {
875
876             if (!array_key_exists($recipient, $ni)) {
877                 $recipientUser = User::staticGet('id', $recipient);
878                 if (!empty($recipientUser)) {
879                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
880                 }
881             }
882         }
883
884         if (!empty($c)) {
885             // XXX: pack this data better
886             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
887         }
888
889         return $ni;
890     }
891
892     function addToInboxes($groups, $recipients)
893     {
894         $ni = $this->whoGets($groups, $recipients);
895
896         Inbox::bulkInsert($this->id, array_keys($ni));
897
898         return;
899     }
900
901     function getSubscribedUsers()
902     {
903         $user = new User();
904
905         if(common_config('db','quote_identifiers'))
906           $user_table = '"user"';
907         else $user_table = 'user';
908
909         $qry =
910           'SELECT id ' .
911           'FROM '. $user_table .' JOIN subscription '.
912           'ON '. $user_table .'.id = subscription.subscriber ' .
913           'WHERE subscription.subscribed = %d ';
914
915         $user->query(sprintf($qry, $this->profile_id));
916
917         $ids = array();
918
919         while ($user->fetch()) {
920             $ids[] = $user->id;
921         }
922
923         $user->free();
924
925         return $ids;
926     }
927
928     function saveGroups()
929     {
930         // Don't save groups for repeats
931
932         if (!empty($this->repeat_of)) {
933             return array();
934         }
935
936         $groups = array();
937
938         /* extract all !group */
939         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
940                                 strtolower($this->content),
941                                 $match);
942         if (!$count) {
943             return $groups;
944         }
945
946         $profile = $this->getProfile();
947
948         /* Add them to the database */
949
950         foreach (array_unique($match[1]) as $nickname) {
951             /* XXX: remote groups. */
952             $group = User_group::getForNickname($nickname);
953
954             if (empty($group)) {
955                 continue;
956             }
957
958             // we automatically add a tag for every group name, too
959
960             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
961                                              'notice_id' => $this->id));
962
963             if (is_null($tag)) {
964                 $this->saveTag($nickname);
965             }
966
967             if ($profile->isMember($group)) {
968
969                 $result = $this->addToGroupInbox($group);
970
971                 if (!$result) {
972                     common_log_db_error($gi, 'INSERT', __FILE__);
973                 }
974
975                 $groups[] = clone($group);
976             }
977         }
978
979         return $groups;
980     }
981
982     function addToGroupInbox($group)
983     {
984         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
985                                          'notice_id' => $this->id));
986
987         if (empty($gi)) {
988
989             $gi = new Group_inbox();
990
991             $gi->group_id  = $group->id;
992             $gi->notice_id = $this->id;
993             $gi->created   = $this->created;
994
995             return $gi->insert();
996         }
997
998         return true;
999     }
1000
1001     /**
1002      * @return array of integer profile IDs
1003      */
1004     function saveReplies()
1005     {
1006         // Don't save reply data for repeats
1007
1008         if (!empty($this->repeat_of)) {
1009             return array();
1010         }
1011
1012         // Alternative reply format
1013         $tname = false;
1014         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1015             $tname = $match[1];
1016         }
1017         // extract all @messages
1018         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1019
1020         $names = array();
1021
1022         if ($cnt || $tname) {
1023             // XXX: is there another way to make an array copy?
1024             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1025         }
1026
1027         $sender = Profile::staticGet($this->profile_id);
1028
1029         $replied = array();
1030
1031         // store replied only for first @ (what user/notice what the reply directed,
1032         // we assume first @ is it)
1033
1034         for ($i=0; $i<count($names); $i++) {
1035             $nickname = $names[$i];
1036             $recipient = common_relative_profile($sender, $nickname, $this->created);
1037             if (empty($recipient)) {
1038                 continue;
1039             }
1040             // Don't save replies from blocked profile to local user
1041             $recipient_user = User::staticGet('id', $recipient->id);
1042             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1043                 continue;
1044             }
1045             $reply = new Reply();
1046             $reply->notice_id = $this->id;
1047             $reply->profile_id = $recipient->id;
1048             $id = $reply->insert();
1049             if (!$id) {
1050                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1051                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1052                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1053                 return array();
1054             } else {
1055                 $replied[$recipient->id] = 1;
1056             }
1057         }
1058
1059         // Hash format replies, too
1060         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1061         if ($cnt) {
1062             foreach ($match[1] as $tag) {
1063                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1064                 foreach ($tagged as $t) {
1065                     if (!$replied[$t->id]) {
1066                         // Don't save replies from blocked profile to local user
1067                         $t_user = User::staticGet('id', $t->id);
1068                         if ($t_user && $t_user->hasBlocked($sender)) {
1069                             continue;
1070                         }
1071                         $reply = new Reply();
1072                         $reply->notice_id = $this->id;
1073                         $reply->profile_id = $t->id;
1074                         $id = $reply->insert();
1075                         if (!$id) {
1076                             common_log_db_error($reply, 'INSERT', __FILE__);
1077                             return array();
1078                         } else {
1079                             $replied[$recipient->id] = 1;
1080                         }
1081                     }
1082                 }
1083             }
1084         }
1085
1086         $recipientIds = array_keys($replied);
1087
1088         foreach ($recipientIds as $recipientId) {
1089             $user = User::staticGet('id', $recipientId);
1090             if ($user) {
1091                 mail_notify_attn($user, $this);
1092             }
1093         }
1094
1095         return $recipientIds;
1096     }
1097
1098     function getReplies()
1099     {
1100         // XXX: cache me
1101
1102         $ids = array();
1103
1104         $reply = new Reply();
1105         $reply->selectAdd();
1106         $reply->selectAdd('profile_id');
1107         $reply->notice_id = $this->id;
1108
1109         if ($reply->find()) {
1110             while($reply->fetch()) {
1111                 $ids[] = $reply->profile_id;
1112             }
1113         }
1114
1115         $reply->free();
1116
1117         return $ids;
1118     }
1119
1120     function getGroups()
1121     {
1122         // XXX: cache me
1123
1124         $ids = array();
1125
1126         $gi = new Group_inbox();
1127
1128         $gi->selectAdd();
1129         $gi->selectAdd('group_id');
1130
1131         $gi->notice_id = $this->id;
1132
1133         if ($gi->find()) {
1134             while ($gi->fetch()) {
1135                 $ids[] = $gi->group_id;
1136             }
1137         }
1138
1139         $gi->free();
1140
1141         return $ids;
1142     }
1143
1144     function asAtomEntry($namespace=false, $source=false)
1145     {
1146         $profile = $this->getProfile();
1147
1148         $xs = new XMLStringer(true);
1149
1150         if ($namespace) {
1151             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1152                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1153         } else {
1154             $attrs = array();
1155         }
1156
1157         $xs->elementStart('entry', $attrs);
1158
1159         if ($source) {
1160             $xs->elementStart('source');
1161             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1162             $xs->element('link', array('href' => $profile->profileurl));
1163             $user = User::staticGet('id', $profile->id);
1164             if (!empty($user)) {
1165                 $atom_feed = common_local_url('ApiTimelineUser',
1166                                               array('format' => 'atom',
1167                                                     'id' => $profile->nickname));
1168                 $xs->element('link', array('rel' => 'self',
1169                                            'type' => 'application/atom+xml',
1170                                            'href' => $profile->profileurl));
1171                 $xs->element('link', array('rel' => 'license',
1172                                            'href' => common_config('license', 'url')));
1173             }
1174
1175             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1176         }
1177
1178         $xs->elementStart('author');
1179         $xs->element('name', null, $profile->nickname);
1180         $xs->element('uri', null, $profile->profileurl);
1181         $xs->elementEnd('author');
1182
1183         if ($source) {
1184             $xs->elementEnd('source');
1185         }
1186
1187         $xs->element('title', null, $this->content);
1188         $xs->element('summary', null, $this->content);
1189
1190         $xs->element('link', array('rel' => 'alternate',
1191                                    'href' => $this->bestUrl()));
1192
1193         $xs->element('id', null, $this->uri);
1194
1195         $xs->element('published', null, common_date_w3dtf($this->created));
1196         $xs->element('updated', null, common_date_w3dtf($this->created));
1197
1198         if ($this->reply_to) {
1199             $reply_notice = Notice::staticGet('id', $this->reply_to);
1200             if (!empty($reply_notice)) {
1201                 $xs->element('link', array('rel' => 'related',
1202                                            'href' => $reply_notice->bestUrl()));
1203                 $xs->element('thr:in-reply-to',
1204                              array('ref' => $reply_notice->uri,
1205                                    'href' => $reply_notice->bestUrl()));
1206             }
1207         }
1208
1209         $xs->element('content', array('type' => 'html'), $this->rendered);
1210
1211         $tag = new Notice_tag();
1212         $tag->notice_id = $this->id;
1213         if ($tag->find()) {
1214             while ($tag->fetch()) {
1215                 $xs->element('category', array('term' => $tag->tag));
1216             }
1217         }
1218         $tag->free();
1219
1220         # Enclosures
1221         $attachments = $this->attachments();
1222         if($attachments){
1223             foreach($attachments as $attachment){
1224                 $enclosure=$attachment->getEnclosure();
1225                 if ($enclosure) {
1226                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1227                     if($enclosure->title){
1228                         $attributes['title']=$enclosure->title;
1229                     }
1230                     $xs->element('link', $attributes, null);
1231                 }
1232             }
1233         }
1234
1235         if (!empty($this->lat) && !empty($this->lon)) {
1236             $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1237             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1238             $xs->elementEnd('geo');
1239         }
1240
1241         $xs->elementEnd('entry');
1242
1243         return $xs->getString();
1244     }
1245
1246     function bestUrl()
1247     {
1248         if (!empty($this->url)) {
1249             return $this->url;
1250         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1251             return $this->uri;
1252         } else {
1253             return common_local_url('shownotice',
1254                                     array('notice' => $this->id));
1255         }
1256     }
1257
1258     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1259     {
1260         $cache = common_memcache();
1261
1262         if (empty($cache) ||
1263             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1264             is_null($limit) ||
1265             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1266             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1267                                                                       $max_id, $since)));
1268         }
1269
1270         $idkey = common_cache_key($cachekey);
1271
1272         $idstr = $cache->get($idkey);
1273
1274         if ($idstr !== false) {
1275             // Cache hit! Woohoo!
1276             $window = explode(',', $idstr);
1277             $ids = array_slice($window, $offset, $limit);
1278             return $ids;
1279         }
1280
1281         $laststr = $cache->get($idkey.';last');
1282
1283         if ($laststr !== false) {
1284             $window = explode(',', $laststr);
1285             $last_id = $window[0];
1286             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1287                                                                           $last_id, 0, null)));
1288
1289             $new_window = array_merge($new_ids, $window);
1290
1291             $new_windowstr = implode(',', $new_window);
1292
1293             $result = $cache->set($idkey, $new_windowstr);
1294             $result = $cache->set($idkey . ';last', $new_windowstr);
1295
1296             $ids = array_slice($new_window, $offset, $limit);
1297
1298             return $ids;
1299         }
1300
1301         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1302                                                                      0, 0, null)));
1303
1304         $windowstr = implode(',', $window);
1305
1306         $result = $cache->set($idkey, $windowstr);
1307         $result = $cache->set($idkey . ';last', $windowstr);
1308
1309         $ids = array_slice($window, $offset, $limit);
1310
1311         return $ids;
1312     }
1313
1314     /**
1315      * Determine which notice, if any, a new notice is in reply to.
1316      *
1317      * For conversation tracking, we try to see where this notice fits
1318      * in the tree. Rough algorithm is:
1319      *
1320      * if (reply_to is set and valid) {
1321      *     return reply_to;
1322      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1323      *     return ID of last notice by initial @name in content;
1324      * }
1325      *
1326      * Note that all @nickname instances will still be used to save "reply" records,
1327      * so the notice shows up in the mentioned users' "replies" tab.
1328      *
1329      * @param integer $reply_to   ID passed in by Web or API
1330      * @param integer $profile_id ID of author
1331      * @param string  $source     Source tag, like 'web' or 'gwibber'
1332      * @param string  $content    Final notice content
1333      *
1334      * @return integer ID of replied-to notice, or null for not a reply.
1335      */
1336
1337     static function getReplyTo($reply_to, $profile_id, $source, $content)
1338     {
1339         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1340
1341         // If $reply_to is specified, we check that it exists, and then
1342         // return it if it does
1343
1344         if (!empty($reply_to)) {
1345             $reply_notice = Notice::staticGet('id', $reply_to);
1346             if (!empty($reply_notice)) {
1347                 return $reply_to;
1348             }
1349         }
1350
1351         // If it's not a "low bandwidth" source (one where you can't set
1352         // a reply_to argument), we return. This is mostly web and API
1353         // clients.
1354
1355         if (!in_array($source, $lb)) {
1356             return null;
1357         }
1358
1359         // Is there an initial @ or T?
1360
1361         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1362             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1363             $nickname = common_canonical_nickname($match[1]);
1364         } else {
1365             return null;
1366         }
1367
1368         // Figure out who that is.
1369
1370         $sender = Profile::staticGet('id', $profile_id);
1371         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1372
1373         if (empty($recipient)) {
1374             return null;
1375         }
1376
1377         // Get their last notice
1378
1379         $last = $recipient->getCurrentNotice();
1380
1381         if (!empty($last)) {
1382             return $last->id;
1383         }
1384     }
1385
1386     static function maxContent()
1387     {
1388         $contentlimit = common_config('notice', 'contentlimit');
1389         // null => use global limit (distinct from 0!)
1390         if (is_null($contentlimit)) {
1391             $contentlimit = common_config('site', 'textlimit');
1392         }
1393         return $contentlimit;
1394     }
1395
1396     static function contentTooLong($content)
1397     {
1398         $contentlimit = self::maxContent();
1399         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1400     }
1401
1402     function getLocation()
1403     {
1404         $location = null;
1405
1406         if (!empty($this->location_id) && !empty($this->location_ns)) {
1407             $location = Location::fromId($this->location_id, $this->location_ns);
1408         }
1409
1410         if (is_null($location)) { // no ID, or Location::fromId() failed
1411             if (!empty($this->lat) && !empty($this->lon)) {
1412                 $location = Location::fromLatLon($this->lat, $this->lon);
1413             }
1414         }
1415
1416         return $location;
1417     }
1418
1419     function repeat($repeater_id, $source)
1420     {
1421         $author = Profile::staticGet('id', $this->profile_id);
1422
1423         $content = sprintf(_('RT @%1$s %2$s'),
1424                            $author->nickname,
1425                            $this->content);
1426
1427         $maxlen = common_config('site', 'textlimit');
1428         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1429             // Web interface and current Twitter API clients will
1430             // pull the original notice's text, but some older
1431             // clients and RSS/Atom feeds will see this trimmed text.
1432             //
1433             // Unfortunately this is likely to lose tags or URLs
1434             // at the end of long notices.
1435             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1436         }
1437
1438         return self::saveNew($repeater_id, $content, $source,
1439                              array('repeat_of' => $this->id));
1440     }
1441
1442     // These are supposed to be in chron order!
1443
1444     function repeatStream($limit=100)
1445     {
1446         $cache = common_memcache();
1447
1448         if (empty($cache)) {
1449             $ids = $this->_repeatStreamDirect($limit);
1450         } else {
1451             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1452             if ($idstr !== false) {
1453                 $ids = explode(',', $idstr);
1454             } else {
1455                 $ids = $this->_repeatStreamDirect(100);
1456                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1457             }
1458             if ($limit < 100) {
1459                 // We do a max of 100, so slice down to limit
1460                 $ids = array_slice($ids, 0, $limit);
1461             }
1462         }
1463
1464         return Notice::getStreamByIds($ids);
1465     }
1466
1467     function _repeatStreamDirect($limit)
1468     {
1469         $notice = new Notice();
1470
1471         $notice->selectAdd(); // clears it
1472         $notice->selectAdd('id');
1473
1474         $notice->repeat_of = $this->id;
1475
1476         $notice->orderBy('created'); // NB: asc!
1477
1478         if (!is_null($offset)) {
1479             $notice->limit($offset, $limit);
1480         }
1481
1482         $ids = array();
1483
1484         if ($notice->find()) {
1485             while ($notice->fetch()) {
1486                 $ids[] = $notice->id;
1487             }
1488         }
1489
1490         $notice->free();
1491         $notice = NULL;
1492
1493         return $ids;
1494     }
1495
1496     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1497     {
1498         $options = array();
1499
1500         if (!empty($location_id) && !empty($location_ns)) {
1501
1502             $options['location_id'] = $location_id;
1503             $options['location_ns'] = $location_ns;
1504
1505             $location = Location::fromId($location_id, $location_ns);
1506
1507             if (!empty($location)) {
1508                 $options['lat'] = $location->lat;
1509                 $options['lon'] = $location->lon;
1510             }
1511
1512         } else if (!empty($lat) && !empty($lon)) {
1513
1514             $options['lat'] = $lat;
1515             $options['lon'] = $lon;
1516
1517             $location = Location::fromLatLon($lat, $lon);
1518
1519             if (!empty($location)) {
1520                 $options['location_id'] = $location->location_id;
1521                 $options['location_ns'] = $location->location_ns;
1522             }
1523         } else if (!empty($profile)) {
1524
1525             if (isset($profile->lat) && isset($profile->lon)) {
1526                 $options['lat'] = $profile->lat;
1527                 $options['lon'] = $profile->lon;
1528             }
1529
1530             if (isset($profile->location_id) && isset($profile->location_ns)) {
1531                 $options['location_id'] = $profile->location_id;
1532                 $options['location_ns'] = $profile->location_ns;
1533             }
1534         }
1535
1536         return $options;
1537     }
1538 }