]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch 'master' 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     /**
830      * @param $groups array of Group *objects*
831      * @param $recipients array of profile *ids*
832      */
833     function whoGets($groups=null, $recipients=null)
834     {
835         $c = self::memcache();
836
837         if (!empty($c)) {
838             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
839             if ($ni !== false) {
840                 return $ni;
841             }
842         }
843
844         if (is_null($groups)) {
845             $groups = $this->getGroups();
846         }
847
848         if (is_null($recipients)) {
849             $recipients = $this->getReplies();
850         }
851
852         $users = $this->getSubscribedUsers();
853
854         // FIXME: kind of ignoring 'transitional'...
855         // we'll probably stop supporting inboxless mode
856         // in 0.9.x
857
858         $ni = array();
859
860         foreach ($users as $id) {
861             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
862         }
863
864         $profile = $this->getProfile();
865
866         foreach ($groups as $group) {
867             $users = $group->getUserMembers();
868             foreach ($users as $id) {
869                 if (!array_key_exists($id, $ni)) {
870                     $user = User::staticGet('id', $id);
871                     if (!$user->hasBlocked($profile)) {
872                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
873                     }
874                 }
875             }
876         }
877
878         foreach ($recipients as $recipient) {
879
880             if (!array_key_exists($recipient, $ni)) {
881                 $recipientUser = User::staticGet('id', $recipient);
882                 if (!empty($recipientUser)) {
883                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
884                 }
885             }
886         }
887
888         if (!empty($c)) {
889             // XXX: pack this data better
890             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
891         }
892
893         return $ni;
894     }
895
896     function addToInboxes($groups, $recipients)
897     {
898         $ni = $this->whoGets($groups, $recipients);
899
900         Inbox::bulkInsert($this->id, array_keys($ni));
901
902         return;
903     }
904
905     function getSubscribedUsers()
906     {
907         $user = new User();
908
909         if(common_config('db','quote_identifiers'))
910           $user_table = '"user"';
911         else $user_table = 'user';
912
913         $qry =
914           'SELECT id ' .
915           'FROM '. $user_table .' JOIN subscription '.
916           'ON '. $user_table .'.id = subscription.subscriber ' .
917           'WHERE subscription.subscribed = %d ';
918
919         $user->query(sprintf($qry, $this->profile_id));
920
921         $ids = array();
922
923         while ($user->fetch()) {
924             $ids[] = $user->id;
925         }
926
927         $user->free();
928
929         return $ids;
930     }
931
932     /**
933      * @return array of Group objects
934      */
935     function saveGroups()
936     {
937         // Don't save groups for repeats
938
939         if (!empty($this->repeat_of)) {
940             return array();
941         }
942
943         $groups = array();
944
945         /* extract all !group */
946         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
947                                 strtolower($this->content),
948                                 $match);
949         if (!$count) {
950             return $groups;
951         }
952
953         $profile = $this->getProfile();
954
955         /* Add them to the database */
956
957         foreach (array_unique($match[1]) as $nickname) {
958             /* XXX: remote groups. */
959             $group = User_group::getForNickname($nickname);
960
961             if (empty($group)) {
962                 continue;
963             }
964
965             // we automatically add a tag for every group name, too
966
967             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
968                                              'notice_id' => $this->id));
969
970             if (is_null($tag)) {
971                 $this->saveTag($nickname);
972             }
973
974             if ($profile->isMember($group)) {
975
976                 $result = $this->addToGroupInbox($group);
977
978                 if (!$result) {
979                     common_log_db_error($gi, 'INSERT', __FILE__);
980                 }
981
982                 $groups[] = clone($group);
983             }
984         }
985
986         return $groups;
987     }
988
989     function addToGroupInbox($group)
990     {
991         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
992                                          'notice_id' => $this->id));
993
994         if (empty($gi)) {
995
996             $gi = new Group_inbox();
997
998             $gi->group_id  = $group->id;
999             $gi->notice_id = $this->id;
1000             $gi->created   = $this->created;
1001
1002             return $gi->insert();
1003         }
1004
1005         return true;
1006     }
1007
1008     /**
1009      * @return array of integer profile IDs
1010      */
1011     function saveReplies()
1012     {
1013         // Don't save reply data for repeats
1014
1015         if (!empty($this->repeat_of)) {
1016             return array();
1017         }
1018
1019         // Alternative reply format
1020         $tname = false;
1021         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1022             $tname = $match[1];
1023         }
1024         // extract all @messages
1025         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1026
1027         $names = array();
1028
1029         if ($cnt || $tname) {
1030             // XXX: is there another way to make an array copy?
1031             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1032         }
1033
1034         $sender = Profile::staticGet($this->profile_id);
1035
1036         $replied = array();
1037
1038         // store replied only for first @ (what user/notice what the reply directed,
1039         // we assume first @ is it)
1040
1041         for ($i=0; $i<count($names); $i++) {
1042             $nickname = $names[$i];
1043             $recipient = common_relative_profile($sender, $nickname, $this->created);
1044             if (empty($recipient)) {
1045                 continue;
1046             }
1047             // Don't save replies from blocked profile to local user
1048             $recipient_user = User::staticGet('id', $recipient->id);
1049             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1050                 continue;
1051             }
1052             $reply = new Reply();
1053             $reply->notice_id = $this->id;
1054             $reply->profile_id = $recipient->id;
1055             $id = $reply->insert();
1056             if (!$id) {
1057                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1058                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1059                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1060                 return array();
1061             } else {
1062                 $replied[$recipient->id] = 1;
1063             }
1064         }
1065
1066         // Hash format replies, too
1067         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1068         if ($cnt) {
1069             foreach ($match[1] as $tag) {
1070                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1071                 foreach ($tagged as $t) {
1072                     if (!$replied[$t->id]) {
1073                         // Don't save replies from blocked profile to local user
1074                         $t_user = User::staticGet('id', $t->id);
1075                         if ($t_user && $t_user->hasBlocked($sender)) {
1076                             continue;
1077                         }
1078                         $reply = new Reply();
1079                         $reply->notice_id = $this->id;
1080                         $reply->profile_id = $t->id;
1081                         $id = $reply->insert();
1082                         if (!$id) {
1083                             common_log_db_error($reply, 'INSERT', __FILE__);
1084                             return array();
1085                         } else {
1086                             $replied[$recipient->id] = 1;
1087                         }
1088                     }
1089                 }
1090             }
1091         }
1092
1093         $recipientIds = array_keys($replied);
1094
1095         foreach ($recipientIds as $recipientId) {
1096             $user = User::staticGet('id', $recipientId);
1097             if ($user) {
1098                 mail_notify_attn($user, $this);
1099             }
1100         }
1101
1102         return $recipientIds;
1103     }
1104
1105     function getReplies()
1106     {
1107         // XXX: cache me
1108
1109         $ids = array();
1110
1111         $reply = new Reply();
1112         $reply->selectAdd();
1113         $reply->selectAdd('profile_id');
1114         $reply->notice_id = $this->id;
1115
1116         if ($reply->find()) {
1117             while($reply->fetch()) {
1118                 $ids[] = $reply->profile_id;
1119             }
1120         }
1121
1122         $reply->free();
1123
1124         return $ids;
1125     }
1126
1127     /**
1128      * Same calculation as saveGroups but without the saving
1129      * @fixme merge the functions
1130      * @return array of Group objects
1131      */
1132     function getGroups()
1133     {
1134         // Don't save groups for repeats
1135
1136         if (!empty($this->repeat_of)) {
1137             return array();
1138         }
1139
1140         // XXX: cache me
1141
1142         $groups = array();
1143
1144         $gi = new Group_inbox();
1145
1146         $gi->selectAdd();
1147         $gi->selectAdd('group_id');
1148
1149         $gi->notice_id = $this->id;
1150
1151         if ($gi->find()) {
1152             while ($gi->fetch()) {
1153                 $groups[] = clone($gi);
1154             }
1155         }
1156
1157         $gi->free();
1158
1159         return $groups;
1160     }
1161
1162     function asAtomEntry($namespace=false, $source=false)
1163     {
1164         $profile = $this->getProfile();
1165
1166         $xs = new XMLStringer(true);
1167
1168         if ($namespace) {
1169             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1170                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1171         } else {
1172             $attrs = array();
1173         }
1174
1175         $xs->elementStart('entry', $attrs);
1176
1177         if ($source) {
1178             $xs->elementStart('source');
1179             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1180             $xs->element('link', array('href' => $profile->profileurl));
1181             $user = User::staticGet('id', $profile->id);
1182             if (!empty($user)) {
1183                 $atom_feed = common_local_url('ApiTimelineUser',
1184                                               array('format' => 'atom',
1185                                                     'id' => $profile->nickname));
1186                 $xs->element('link', array('rel' => 'self',
1187                                            'type' => 'application/atom+xml',
1188                                            'href' => $profile->profileurl));
1189                 $xs->element('link', array('rel' => 'license',
1190                                            'href' => common_config('license', 'url')));
1191             }
1192
1193             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1194         }
1195
1196         $xs->elementStart('author');
1197         $xs->element('name', null, $profile->nickname);
1198         $xs->element('uri', null, $profile->profileurl);
1199         $xs->elementEnd('author');
1200
1201         if ($source) {
1202             $xs->elementEnd('source');
1203         }
1204
1205         $xs->element('title', null, $this->content);
1206         $xs->element('summary', null, $this->content);
1207
1208         $xs->element('link', array('rel' => 'alternate',
1209                                    'href' => $this->bestUrl()));
1210
1211         $xs->element('id', null, $this->uri);
1212
1213         $xs->element('published', null, common_date_w3dtf($this->created));
1214         $xs->element('updated', null, common_date_w3dtf($this->created));
1215
1216         if ($this->reply_to) {
1217             $reply_notice = Notice::staticGet('id', $this->reply_to);
1218             if (!empty($reply_notice)) {
1219                 $xs->element('link', array('rel' => 'related',
1220                                            'href' => $reply_notice->bestUrl()));
1221                 $xs->element('thr:in-reply-to',
1222                              array('ref' => $reply_notice->uri,
1223                                    'href' => $reply_notice->bestUrl()));
1224             }
1225         }
1226
1227         $xs->element('content', array('type' => 'html'), $this->rendered);
1228
1229         $tag = new Notice_tag();
1230         $tag->notice_id = $this->id;
1231         if ($tag->find()) {
1232             while ($tag->fetch()) {
1233                 $xs->element('category', array('term' => $tag->tag));
1234             }
1235         }
1236         $tag->free();
1237
1238         # Enclosures
1239         $attachments = $this->attachments();
1240         if($attachments){
1241             foreach($attachments as $attachment){
1242                 $enclosure=$attachment->getEnclosure();
1243                 if ($enclosure) {
1244                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1245                     if($enclosure->title){
1246                         $attributes['title']=$enclosure->title;
1247                     }
1248                     $xs->element('link', $attributes, null);
1249                 }
1250             }
1251         }
1252
1253         if (!empty($this->lat) && !empty($this->lon)) {
1254             $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1255             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1256             $xs->elementEnd('geo');
1257         }
1258
1259         $xs->elementEnd('entry');
1260
1261         return $xs->getString();
1262     }
1263
1264     function bestUrl()
1265     {
1266         if (!empty($this->url)) {
1267             return $this->url;
1268         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1269             return $this->uri;
1270         } else {
1271             return common_local_url('shownotice',
1272                                     array('notice' => $this->id));
1273         }
1274     }
1275
1276     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1277     {
1278         $cache = common_memcache();
1279
1280         if (empty($cache) ||
1281             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1282             is_null($limit) ||
1283             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1284             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1285                                                                       $max_id, $since)));
1286         }
1287
1288         $idkey = common_cache_key($cachekey);
1289
1290         $idstr = $cache->get($idkey);
1291
1292         if ($idstr !== false) {
1293             // Cache hit! Woohoo!
1294             $window = explode(',', $idstr);
1295             $ids = array_slice($window, $offset, $limit);
1296             return $ids;
1297         }
1298
1299         $laststr = $cache->get($idkey.';last');
1300
1301         if ($laststr !== false) {
1302             $window = explode(',', $laststr);
1303             $last_id = $window[0];
1304             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1305                                                                           $last_id, 0, null)));
1306
1307             $new_window = array_merge($new_ids, $window);
1308
1309             $new_windowstr = implode(',', $new_window);
1310
1311             $result = $cache->set($idkey, $new_windowstr);
1312             $result = $cache->set($idkey . ';last', $new_windowstr);
1313
1314             $ids = array_slice($new_window, $offset, $limit);
1315
1316             return $ids;
1317         }
1318
1319         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1320                                                                      0, 0, null)));
1321
1322         $windowstr = implode(',', $window);
1323
1324         $result = $cache->set($idkey, $windowstr);
1325         $result = $cache->set($idkey . ';last', $windowstr);
1326
1327         $ids = array_slice($window, $offset, $limit);
1328
1329         return $ids;
1330     }
1331
1332     /**
1333      * Determine which notice, if any, a new notice is in reply to.
1334      *
1335      * For conversation tracking, we try to see where this notice fits
1336      * in the tree. Rough algorithm is:
1337      *
1338      * if (reply_to is set and valid) {
1339      *     return reply_to;
1340      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1341      *     return ID of last notice by initial @name in content;
1342      * }
1343      *
1344      * Note that all @nickname instances will still be used to save "reply" records,
1345      * so the notice shows up in the mentioned users' "replies" tab.
1346      *
1347      * @param integer $reply_to   ID passed in by Web or API
1348      * @param integer $profile_id ID of author
1349      * @param string  $source     Source tag, like 'web' or 'gwibber'
1350      * @param string  $content    Final notice content
1351      *
1352      * @return integer ID of replied-to notice, or null for not a reply.
1353      */
1354
1355     static function getReplyTo($reply_to, $profile_id, $source, $content)
1356     {
1357         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1358
1359         // If $reply_to is specified, we check that it exists, and then
1360         // return it if it does
1361
1362         if (!empty($reply_to)) {
1363             $reply_notice = Notice::staticGet('id', $reply_to);
1364             if (!empty($reply_notice)) {
1365                 return $reply_to;
1366             }
1367         }
1368
1369         // If it's not a "low bandwidth" source (one where you can't set
1370         // a reply_to argument), we return. This is mostly web and API
1371         // clients.
1372
1373         if (!in_array($source, $lb)) {
1374             return null;
1375         }
1376
1377         // Is there an initial @ or T?
1378
1379         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1380             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1381             $nickname = common_canonical_nickname($match[1]);
1382         } else {
1383             return null;
1384         }
1385
1386         // Figure out who that is.
1387
1388         $sender = Profile::staticGet('id', $profile_id);
1389         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1390
1391         if (empty($recipient)) {
1392             return null;
1393         }
1394
1395         // Get their last notice
1396
1397         $last = $recipient->getCurrentNotice();
1398
1399         if (!empty($last)) {
1400             return $last->id;
1401         }
1402     }
1403
1404     static function maxContent()
1405     {
1406         $contentlimit = common_config('notice', 'contentlimit');
1407         // null => use global limit (distinct from 0!)
1408         if (is_null($contentlimit)) {
1409             $contentlimit = common_config('site', 'textlimit');
1410         }
1411         return $contentlimit;
1412     }
1413
1414     static function contentTooLong($content)
1415     {
1416         $contentlimit = self::maxContent();
1417         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1418     }
1419
1420     function getLocation()
1421     {
1422         $location = null;
1423
1424         if (!empty($this->location_id) && !empty($this->location_ns)) {
1425             $location = Location::fromId($this->location_id, $this->location_ns);
1426         }
1427
1428         if (is_null($location)) { // no ID, or Location::fromId() failed
1429             if (!empty($this->lat) && !empty($this->lon)) {
1430                 $location = Location::fromLatLon($this->lat, $this->lon);
1431             }
1432         }
1433
1434         return $location;
1435     }
1436
1437     function repeat($repeater_id, $source)
1438     {
1439         $author = Profile::staticGet('id', $this->profile_id);
1440
1441         $content = sprintf(_('RT @%1$s %2$s'),
1442                            $author->nickname,
1443                            $this->content);
1444
1445         $maxlen = common_config('site', 'textlimit');
1446         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1447             // Web interface and current Twitter API clients will
1448             // pull the original notice's text, but some older
1449             // clients and RSS/Atom feeds will see this trimmed text.
1450             //
1451             // Unfortunately this is likely to lose tags or URLs
1452             // at the end of long notices.
1453             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1454         }
1455
1456         return self::saveNew($repeater_id, $content, $source,
1457                              array('repeat_of' => $this->id));
1458     }
1459
1460     // These are supposed to be in chron order!
1461
1462     function repeatStream($limit=100)
1463     {
1464         $cache = common_memcache();
1465
1466         if (empty($cache)) {
1467             $ids = $this->_repeatStreamDirect($limit);
1468         } else {
1469             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1470             if ($idstr !== false) {
1471                 $ids = explode(',', $idstr);
1472             } else {
1473                 $ids = $this->_repeatStreamDirect(100);
1474                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1475             }
1476             if ($limit < 100) {
1477                 // We do a max of 100, so slice down to limit
1478                 $ids = array_slice($ids, 0, $limit);
1479             }
1480         }
1481
1482         return Notice::getStreamByIds($ids);
1483     }
1484
1485     function _repeatStreamDirect($limit)
1486     {
1487         $notice = new Notice();
1488
1489         $notice->selectAdd(); // clears it
1490         $notice->selectAdd('id');
1491
1492         $notice->repeat_of = $this->id;
1493
1494         $notice->orderBy('created'); // NB: asc!
1495
1496         if (!is_null($offset)) {
1497             $notice->limit($offset, $limit);
1498         }
1499
1500         $ids = array();
1501
1502         if ($notice->find()) {
1503             while ($notice->fetch()) {
1504                 $ids[] = $notice->id;
1505             }
1506         }
1507
1508         $notice->free();
1509         $notice = NULL;
1510
1511         return $ids;
1512     }
1513
1514     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1515     {
1516         $options = array();
1517
1518         if (!empty($location_id) && !empty($location_ns)) {
1519
1520             $options['location_id'] = $location_id;
1521             $options['location_ns'] = $location_ns;
1522
1523             $location = Location::fromId($location_id, $location_ns);
1524
1525             if (!empty($location)) {
1526                 $options['lat'] = $location->lat;
1527                 $options['lon'] = $location->lon;
1528             }
1529
1530         } else if (!empty($lat) && !empty($lon)) {
1531
1532             $options['lat'] = $lat;
1533             $options['lon'] = $lon;
1534
1535             $location = Location::fromLatLon($lat, $lon);
1536
1537             if (!empty($location)) {
1538                 $options['location_id'] = $location->location_id;
1539                 $options['location_ns'] = $location->location_ns;
1540             }
1541         } else if (!empty($profile)) {
1542
1543             if (isset($profile->lat) && isset($profile->lon)) {
1544                 $options['lat'] = $profile->lat;
1545                 $options['lon'] = $profile->lon;
1546             }
1547
1548             if (isset($profile->location_id) && isset($profile->location_ns)) {
1549                 $options['location_id'] = $profile->location_id;
1550                 $options['location_ns'] = $profile->location_ns;
1551             }
1552         }
1553
1554         return $options;
1555     }
1556 }