]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch 'master' of gitorious.org:statusnet/mainline into testing
[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         // For auditing purposes, save a record that the notice
98         // was deleted.
99
100         // @fixme we have some cases where things get re-run and so the
101         // insert fails.
102         $deleted = Deleted_notice::staticGet('id', $this->id);
103         if (!$deleted) {
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             $deleted->insert();
113         }
114
115         // Clear related records
116
117         $this->clearReplies();
118         $this->clearRepeats();
119         $this->clearFaves();
120         $this->clearTags();
121         $this->clearGroupInboxes();
122
123         // NOTE: we don't clear inboxes
124         // NOTE: we don't clear queue items
125
126         $result = parent::delete();
127
128         $this->blowOnDelete();
129         return $result;
130     }
131
132     /**
133      * Extract #hashtags from this notice's content and save them to the database.
134      */
135     function saveTags()
136     {
137         /* extract all #hastags */
138         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
139         if (!$count) {
140             return true;
141         }
142
143         /* Add them to the database */
144         return $this->saveKnownTags($match[1]);
145     }
146
147     /**
148      * Record the given set of hash tags in the db for this notice.
149      * Given tag strings will be normalized and checked for dupes.
150      */
151     function saveKnownTags($hashtags)
152     {
153         //turn each into their canonical tag
154         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
155         for($i=0; $i<count($hashtags); $i++) {
156             /* elide characters we don't want in the tag */
157             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
158         }
159
160         foreach(array_unique($hashtags) as $hashtag) {
161             $this->saveTag($hashtag);
162             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
163         }
164         return true;
165     }
166
167     /**
168      * Record a single hash tag as associated with this notice.
169      * Tag format and uniqueness must be validated by caller.
170      */
171     function saveTag($hashtag)
172     {
173         $tag = new Notice_tag();
174         $tag->notice_id = $this->id;
175         $tag->tag = $hashtag;
176         $tag->created = $this->created;
177         $id = $tag->insert();
178
179         if (!$id) {
180             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
181                                               $last_error->message));
182             return;
183         }
184
185         // if it's saved, blow its cache
186         $tag->blowCache(false);
187     }
188
189     /**
190      * Save a new notice and push it out to subscribers' inboxes.
191      * Poster's permissions are checked before sending.
192      *
193      * @param int $profile_id Profile ID of the poster
194      * @param string $content source message text; links may be shortened
195      *                        per current user's preference
196      * @param string $source source key ('web', 'api', etc)
197      * @param array $options Associative array of optional properties:
198      *              string 'created' timestamp of notice; defaults to now
199      *              int 'is_local' source/gateway ID, one of:
200      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
201      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
202      *                                            hide from public timeline but show in
203      *                                            local "and friends" timelines
204      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
205      *                  Notice::GATEWAY         - From another non-OMB service;
206      *                                            will not appear in public views
207      *              float 'lat' decimal latitude for geolocation
208      *              float 'lon' decimal longitude for geolocation
209      *              int 'location_id' geoname identifier
210      *              int 'location_ns' geoname namespace to interpret location_id
211      *              int 'reply_to'; notice ID this is a reply to
212      *              int 'repeat_of'; notice ID this is a repeat of
213      *              string 'uri' unique ID for notice; defaults to local notice URL
214      *              string 'url' permalink to notice; defaults to local notice URL
215      *              string 'rendered' rendered HTML version of content
216      *              array 'replies' list of profile URIs for reply delivery in
217      *                              place of extracting @-replies from content.
218      *              array 'groups' list of group IDs to deliver to, in place of
219      *                              extracting ! tags from content
220      *              array 'tags' list of hashtag strings to save with the notice
221      *                           in place of extracting # tags from content
222      *              array 'urls' list of attached/referred URLs to save with the
223      *                           notice in place of extracting links from content
224      * @fixme tag override
225      *
226      * @return Notice
227      * @throws ClientException
228      */
229     static function saveNew($profile_id, $content, $source, $options=null) {
230         $defaults = array('uri' => null,
231                           'url' => null,
232                           'reply_to' => null,
233                           'repeat_of' => null);
234
235         if (!empty($options)) {
236             $options = $options + $defaults;
237             extract($options);
238         }
239
240         if (!isset($is_local)) {
241             $is_local = Notice::LOCAL_PUBLIC;
242         }
243
244         $profile = Profile::staticGet($profile_id);
245
246         $final = common_shorten_links($content);
247
248         if (Notice::contentTooLong($final)) {
249             throw new ClientException(_('Problem saving notice. Too long.'));
250         }
251
252         if (empty($profile)) {
253             throw new ClientException(_('Problem saving notice. Unknown user.'));
254         }
255
256         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
257             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
258             throw new ClientException(_('Too many notices too fast; take a breather '.
259                                         'and post again in a few minutes.'));
260         }
261
262         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
263             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
264             throw new ClientException(_('Too many duplicate messages too quickly;'.
265                                         ' take a breather and post again in a few minutes.'));
266         }
267
268         if (!$profile->hasRight(Right::NEWNOTICE)) {
269             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
270             throw new ClientException(_('You are banned from posting notices on this site.'));
271         }
272
273         $notice = new Notice();
274         $notice->profile_id = $profile_id;
275
276         $autosource = common_config('public', 'autosource');
277
278         # Sandboxed are non-false, but not 1, either
279
280         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
281             ($source && $autosource && in_array($source, $autosource))) {
282             $notice->is_local = Notice::LOCAL_NONPUBLIC;
283         } else {
284             $notice->is_local = $is_local;
285         }
286
287         if (!empty($created)) {
288             $notice->created = $created;
289         } else {
290             $notice->created = common_sql_now();
291         }
292
293         $notice->content = $final;
294
295         $notice->source = $source;
296         $notice->uri = $uri;
297         $notice->url = $url;
298
299         // Handle repeat case
300
301         if (isset($repeat_of)) {
302             $notice->repeat_of = $repeat_of;
303         } else {
304             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
305         }
306
307         if (!empty($notice->reply_to)) {
308             $reply = Notice::staticGet('id', $notice->reply_to);
309             $notice->conversation = $reply->conversation;
310         }
311
312         if (!empty($lat) && !empty($lon)) {
313             $notice->lat = $lat;
314             $notice->lon = $lon;
315         }
316
317         if (!empty($location_ns) && !empty($location_id)) {
318             $notice->location_id = $location_id;
319             $notice->location_ns = $location_ns;
320         }
321
322         if (!empty($rendered)) {
323             $notice->rendered = $rendered;
324         } else {
325             $notice->rendered = common_render_content($final, $notice);
326         }
327
328         if (Event::handle('StartNoticeSave', array(&$notice))) {
329
330             // XXX: some of these functions write to the DB
331
332             $id = $notice->insert();
333
334             if (!$id) {
335                 common_log_db_error($notice, 'INSERT', __FILE__);
336                 throw new ServerException(_('Problem saving notice.'));
337             }
338
339             // Update ID-dependent columns: URI, conversation
340
341             $orig = clone($notice);
342
343             $changed = false;
344
345             if (empty($uri)) {
346                 $notice->uri = common_notice_uri($notice);
347                 $changed = true;
348             }
349
350             // If it's not part of a conversation, it's
351             // the beginning of a new conversation.
352
353             if (empty($notice->conversation)) {
354                 $conv = Conversation::create();
355                 $notice->conversation = $conv->id;
356                 $changed = true;
357             }
358
359             if ($changed) {
360                 if (!$notice->update($orig)) {
361                     common_log_db_error($notice, 'UPDATE', __FILE__);
362                     throw new ServerException(_('Problem saving notice.'));
363                 }
364             }
365
366         }
367
368         # Clear the cache for subscribed users, so they'll update at next request
369         # XXX: someone clever could prepend instead of clearing the cache
370
371         $notice->blowOnInsert();
372
373         // Save per-notice metadata...
374
375         if (isset($replies)) {
376             $notice->saveKnownReplies($replies);
377         } else {
378             $notice->saveReplies();
379         }
380
381         if (isset($tags)) {
382             $notice->saveKnownTags($tags);
383         } else {
384             $notice->saveTags();
385         }
386
387         // Note: groups may save tags, so must be run after tags are saved
388         // to avoid errors on duplicates.
389         if (isset($groups)) {
390             $notice->saveKnownGroups($groups);
391         } else {
392             $notice->saveGroups();
393         }
394
395         if (isset($urls)) {
396             $notice->saveKnownUrls($urls);
397         } else {
398             $notice->saveUrls();
399         }
400
401         // Prepare inbox delivery, may be queued to background.
402         $notice->distribute();
403
404         return $notice;
405     }
406
407     function blowOnInsert($conversation = false)
408     {
409         self::blow('profile:notice_ids:%d', $this->profile_id);
410         self::blow('public');
411
412         // XXX: Before we were blowing the casche only if the notice id
413         // was not the root of the conversation.  What to do now?
414
415         self::blow('notice:conversation_ids:%d', $this->conversation);
416
417         if (!empty($this->repeat_of)) {
418             self::blow('notice:repeats:%d', $this->repeat_of);
419         }
420
421         $original = Notice::staticGet('id', $this->repeat_of);
422
423         if (!empty($original)) {
424             $originalUser = User::staticGet('id', $original->profile_id);
425             if (!empty($originalUser)) {
426                 self::blow('user:repeats_of_me:%d', $originalUser->id);
427             }
428         }
429
430         $profile = Profile::staticGet($this->profile_id);
431         if (!empty($profile)) {
432             $profile->blowNoticeCount();
433         }
434     }
435
436     /**
437      * Clear cache entries related to this notice at delete time.
438      * Necessary to avoid breaking paging on public, profile timelines.
439      */
440     function blowOnDelete()
441     {
442         $this->blowOnInsert();
443
444         self::blow('profile:notice_ids:%d;last', $this->profile_id);
445         self::blow('public;last');
446     }
447
448     /** save all urls in the notice to the db
449      *
450      * follow redirects and save all available file information
451      * (mimetype, date, size, oembed, etc.)
452      *
453      * @return void
454      */
455     function saveUrls() {
456         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
457     }
458
459     /**
460      * Save the given URLs as related links/attachments to the db
461      *
462      * follow redirects and save all available file information
463      * (mimetype, date, size, oembed, etc.)
464      *
465      * @return void
466      */
467     function saveKnownUrls($urls)
468     {
469         // @fixme validation?
470         foreach ($urls as $url) {
471             File::processNew($url, $this->id);
472         }
473     }
474
475     /**
476      * @private callback
477      */
478     function saveUrl($data) {
479         list($url, $notice_id) = $data;
480         File::processNew($url, $notice_id);
481     }
482
483     static function checkDupes($profile_id, $content) {
484         $profile = Profile::staticGet($profile_id);
485         if (empty($profile)) {
486             return false;
487         }
488         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
489         if (!empty($notice)) {
490             $last = 0;
491             while ($notice->fetch()) {
492                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
493                     return true;
494                 } else if ($notice->content == $content) {
495                     return false;
496                 }
497             }
498         }
499         # If we get here, oldest item in cache window is not
500         # old enough for dupe limit; do direct check against DB
501         $notice = new Notice();
502         $notice->profile_id = $profile_id;
503         $notice->content = $content;
504         if (common_config('db','type') == 'pgsql')
505           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
506         else
507           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
508
509         $cnt = $notice->count();
510         return ($cnt == 0);
511     }
512
513     static function checkEditThrottle($profile_id) {
514         $profile = Profile::staticGet($profile_id);
515         if (empty($profile)) {
516             return false;
517         }
518         # Get the Nth notice
519         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
520         if ($notice && $notice->fetch()) {
521             # If the Nth notice was posted less than timespan seconds ago
522             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
523                 # Then we throttle
524                 return false;
525             }
526         }
527         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
528         return true;
529     }
530
531     function getUploadedAttachment() {
532         $post = clone $this;
533         $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"';
534         $post->query($query);
535         $post->fetch();
536         if (empty($post->up) || empty($post->i)) {
537             $ret = false;
538         } else {
539             $ret = array($post->up, $post->i);
540         }
541         $post->free();
542         return $ret;
543     }
544
545     function hasAttachments() {
546         $post = clone $this;
547         $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);
548         $post->query($query);
549         $post->fetch();
550         $n_attachments = intval($post->n_attachments);
551         $post->free();
552         return $n_attachments;
553     }
554
555     function attachments() {
556         // XXX: cache this
557         $att = array();
558         $f2p = new File_to_post;
559         $f2p->post_id = $this->id;
560         if ($f2p->find()) {
561             while ($f2p->fetch()) {
562                 $f = File::staticGet($f2p->file_id);
563                 $att[] = clone($f);
564             }
565         }
566         return $att;
567     }
568
569     function getStreamByIds($ids)
570     {
571         $cache = common_memcache();
572
573         if (!empty($cache)) {
574             $notices = array();
575             foreach ($ids as $id) {
576                 $n = Notice::staticGet('id', $id);
577                 if (!empty($n)) {
578                     $notices[] = $n;
579                 }
580             }
581             return new ArrayWrapper($notices);
582         } else {
583             $notice = new Notice();
584             if (empty($ids)) {
585                 //if no IDs requested, just return the notice object
586                 return $notice;
587             }
588             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
589
590             $notice->find();
591
592             $temp = array();
593
594             while ($notice->fetch()) {
595                 $temp[$notice->id] = clone($notice);
596             }
597
598             $wrapped = array();
599
600             foreach ($ids as $id) {
601                 if (array_key_exists($id, $temp)) {
602                     $wrapped[] = $temp[$id];
603                 }
604             }
605
606             return new ArrayWrapper($wrapped);
607         }
608     }
609
610     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
611     {
612         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
613                               array(),
614                               'public',
615                               $offset, $limit, $since_id, $max_id);
616         return Notice::getStreamByIds($ids);
617     }
618
619     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
620     {
621         $notice = new Notice();
622
623         $notice->selectAdd(); // clears it
624         $notice->selectAdd('id');
625
626         $notice->orderBy('id DESC');
627
628         if (!is_null($offset)) {
629             $notice->limit($offset, $limit);
630         }
631
632         if (common_config('public', 'localonly')) {
633             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
634         } else {
635             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
636             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
637             $notice->whereAdd('is_local !='. Notice::GATEWAY);
638         }
639
640         if ($since_id != 0) {
641             $notice->whereAdd('id > ' . $since_id);
642         }
643
644         if ($max_id != 0) {
645             $notice->whereAdd('id <= ' . $max_id);
646         }
647
648         $ids = array();
649
650         if ($notice->find()) {
651             while ($notice->fetch()) {
652                 $ids[] = $notice->id;
653             }
654         }
655
656         $notice->free();
657         $notice = NULL;
658
659         return $ids;
660     }
661
662     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
663     {
664         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
665                               array($id),
666                               'notice:conversation_ids:'.$id,
667                               $offset, $limit, $since_id, $max_id);
668
669         return Notice::getStreamByIds($ids);
670     }
671
672     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
673     {
674         $notice = new Notice();
675
676         $notice->selectAdd(); // clears it
677         $notice->selectAdd('id');
678
679         $notice->conversation = $id;
680
681         $notice->orderBy('id DESC');
682
683         if (!is_null($offset)) {
684             $notice->limit($offset, $limit);
685         }
686
687         if ($since_id != 0) {
688             $notice->whereAdd('id > ' . $since_id);
689         }
690
691         if ($max_id != 0) {
692             $notice->whereAdd('id <= ' . $max_id);
693         }
694
695         $ids = array();
696
697         if ($notice->find()) {
698             while ($notice->fetch()) {
699                 $ids[] = $notice->id;
700             }
701         }
702
703         $notice->free();
704         $notice = NULL;
705
706         return $ids;
707     }
708
709     /**
710      * Is this notice part of an active conversation?
711      *
712      * @return boolean true if other messages exist in the same
713      *                 conversation, false if this is the only one
714      */
715     function hasConversation()
716     {
717         if (!empty($this->conversation)) {
718             $conversation = Notice::conversationStream(
719                 $this->conversation,
720                 1,
721                 1
722             );
723             if ($conversation->N > 0) {
724                 return true;
725             }
726         }
727         return false;
728     }
729
730     /**
731      * @param $groups array of Group *objects*
732      * @param $recipients array of profile *ids*
733      */
734     function whoGets($groups=null, $recipients=null)
735     {
736         $c = self::memcache();
737
738         if (!empty($c)) {
739             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
740             if ($ni !== false) {
741                 return $ni;
742             }
743         }
744
745         if (is_null($groups)) {
746             $groups = $this->getGroups();
747         }
748
749         if (is_null($recipients)) {
750             $recipients = $this->getReplies();
751         }
752
753         $users = $this->getSubscribedUsers();
754
755         // FIXME: kind of ignoring 'transitional'...
756         // we'll probably stop supporting inboxless mode
757         // in 0.9.x
758
759         $ni = array();
760
761         foreach ($users as $id) {
762             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
763         }
764
765         $profile = $this->getProfile();
766
767         foreach ($groups as $group) {
768             $users = $group->getUserMembers();
769             foreach ($users as $id) {
770                 if (!array_key_exists($id, $ni)) {
771                     $user = User::staticGet('id', $id);
772                     if (!$user->hasBlocked($profile)) {
773                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
774                     }
775                 }
776             }
777         }
778
779         foreach ($recipients as $recipient) {
780
781             if (!array_key_exists($recipient, $ni)) {
782                 $recipientUser = User::staticGet('id', $recipient);
783                 if (!empty($recipientUser)) {
784                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
785                 }
786             }
787         }
788
789         if (!empty($c)) {
790             // XXX: pack this data better
791             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
792         }
793
794         return $ni;
795     }
796
797     /**
798      * Adds this notice to the inboxes of each local user who should receive
799      * it, based on author subscriptions, group memberships, and @-replies.
800      *
801      * Warning: running a second time currently will make items appear
802      * multiple times in users' inboxes.
803      *
804      * @fixme make more robust against errors
805      * @fixme break up massive deliveries to smaller background tasks
806      *
807      * @param array $groups optional list of Group objects;
808      *              if left empty, will be loaded from group_inbox records
809      * @param array $recipient optional list of reply profile ids
810      *              if left empty, will be loaded from reply records
811      */
812     function addToInboxes($groups=null, $recipients=null)
813     {
814         $ni = $this->whoGets($groups, $recipients);
815
816         $ids = array_keys($ni);
817
818         // We remove the author (if they're a local user),
819         // since we'll have already done this in distribute()
820
821         $i = array_search($this->profile_id, $ids);
822
823         if ($i !== false) {
824             unset($ids[$i]);
825         }
826
827         // Bulk insert
828
829         Inbox::bulkInsert($this->id, $ids);
830
831         return;
832     }
833
834     function getSubscribedUsers()
835     {
836         $user = new User();
837
838         if(common_config('db','quote_identifiers'))
839           $user_table = '"user"';
840         else $user_table = 'user';
841
842         $qry =
843           'SELECT id ' .
844           'FROM '. $user_table .' JOIN subscription '.
845           'ON '. $user_table .'.id = subscription.subscriber ' .
846           'WHERE subscription.subscribed = %d ';
847
848         $user->query(sprintf($qry, $this->profile_id));
849
850         $ids = array();
851
852         while ($user->fetch()) {
853             $ids[] = $user->id;
854         }
855
856         $user->free();
857
858         return $ids;
859     }
860
861     /**
862      * Record this notice to the given group inboxes for delivery.
863      * Overrides the regular parsing of !group markup.
864      *
865      * @param string $group_ids
866      * @fixme might prefer URIs as identifiers, as for replies?
867      *        best with generalizations on user_group to support
868      *        remote groups better.
869      */
870     function saveKnownGroups($group_ids)
871     {
872         if (!is_array($group_ids)) {
873             throw new ServerException("Bad type provided to saveKnownGroups");
874         }
875
876         $groups = array();
877         foreach ($group_ids as $id) {
878             $group = User_group::staticGet('id', $id);
879             if ($group) {
880                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
881                 $result = $this->addToGroupInbox($group);
882                 if (!$result) {
883                     common_log_db_error($gi, 'INSERT', __FILE__);
884                 }
885
886                 // @fixme should we save the tags here or not?
887                 $groups[] = clone($group);
888             } else {
889                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
890             }
891         }
892
893         return $groups;
894     }
895
896     /**
897      * Parse !group delivery and record targets into group_inbox.
898      * @return array of Group objects
899      */
900     function saveGroups()
901     {
902         // Don't save groups for repeats
903
904         if (!empty($this->repeat_of)) {
905             return array();
906         }
907
908         $groups = array();
909
910         /* extract all !group */
911         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
912                                 strtolower($this->content),
913                                 $match);
914         if (!$count) {
915             return $groups;
916         }
917
918         $profile = $this->getProfile();
919
920         /* Add them to the database */
921
922         foreach (array_unique($match[1]) as $nickname) {
923             /* XXX: remote groups. */
924             $group = User_group::getForNickname($nickname, $profile);
925
926             if (empty($group)) {
927                 continue;
928             }
929
930             // we automatically add a tag for every group name, too
931
932             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
933                                              'notice_id' => $this->id));
934
935             if (is_null($tag)) {
936                 $this->saveTag($nickname);
937             }
938
939             if ($profile->isMember($group)) {
940
941                 $result = $this->addToGroupInbox($group);
942
943                 if (!$result) {
944                     common_log_db_error($gi, 'INSERT', __FILE__);
945                 }
946
947                 $groups[] = clone($group);
948             }
949         }
950
951         return $groups;
952     }
953
954     function addToGroupInbox($group)
955     {
956         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
957                                          'notice_id' => $this->id));
958
959         if (empty($gi)) {
960
961             $gi = new Group_inbox();
962
963             $gi->group_id  = $group->id;
964             $gi->notice_id = $this->id;
965             $gi->created   = $this->created;
966
967             $result = $gi->insert();
968
969             if (!$result) {
970                 common_log_db_error($gi, 'INSERT', __FILE__);
971                 throw new ServerException(_('Problem saving group inbox.'));
972             }
973
974             self::blow('user_group:notice_ids:%d', $gi->group_id);
975         }
976
977         return true;
978     }
979
980     /**
981      * Save reply records indicating that this notice needs to be
982      * delivered to the local users with the given URIs.
983      *
984      * Since this is expected to be used when saving foreign-sourced
985      * messages, we won't deliver to any remote targets as that's the
986      * source service's responsibility.
987      *
988      * Mail notifications etc will be handled later.
989      *
990      * @param array of unique identifier URIs for recipients
991      */
992     function saveKnownReplies($uris)
993     {
994         if (empty($uris)) {
995             return;
996         }
997         $sender = Profile::staticGet($this->profile_id);
998
999         foreach ($uris as $uri) {
1000
1001             $user = User::staticGet('uri', $uri);
1002
1003             if (!empty($user)) {
1004                 if ($user->hasBlocked($sender)) {
1005                     continue;
1006                 }
1007
1008                 $reply = new Reply();
1009
1010                 $reply->notice_id  = $this->id;
1011                 $reply->profile_id = $user->id;
1012
1013                 $id = $reply->insert();
1014             }
1015         }
1016
1017         return;
1018     }
1019
1020     /**
1021      * Pull @-replies from this message's content in StatusNet markup format
1022      * and save reply records indicating that this message needs to be
1023      * delivered to those users.
1024      *
1025      * Mail notifications to local profiles will be sent later.
1026      *
1027      * @return array of integer profile IDs
1028      */
1029
1030     function saveReplies()
1031     {
1032         // Don't save reply data for repeats
1033
1034         if (!empty($this->repeat_of)) {
1035             return array();
1036         }
1037
1038         $sender = Profile::staticGet($this->profile_id);
1039
1040         // @todo ideally this parser information would only
1041         // be calculated once.
1042
1043         $mentions = common_find_mentions($this->content, $this);
1044
1045         $replied = array();
1046
1047         // store replied only for first @ (what user/notice what the reply directed,
1048         // we assume first @ is it)
1049
1050         foreach ($mentions as $mention) {
1051
1052             foreach ($mention['mentioned'] as $mentioned) {
1053
1054                 // skip if they're already covered
1055
1056                 if (!empty($replied[$mentioned->id])) {
1057                     continue;
1058                 }
1059
1060                 // Don't save replies from blocked profile to local user
1061
1062                 $mentioned_user = User::staticGet('id', $mentioned->id);
1063                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1064                     continue;
1065                 }
1066
1067                 $reply = new Reply();
1068
1069                 $reply->notice_id  = $this->id;
1070                 $reply->profile_id = $mentioned->id;
1071
1072                 $id = $reply->insert();
1073
1074                 if (!$id) {
1075                     common_log_db_error($reply, 'INSERT', __FILE__);
1076                     throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
1077                 } else {
1078                     $replied[$mentioned->id] = 1;
1079                     self::blow('reply:stream:%d', $mentioned->id);
1080                 }
1081             }
1082         }
1083
1084         $recipientIds = array_keys($replied);
1085
1086         return $recipientIds;
1087     }
1088
1089     /**
1090      * Pull the complete list of @-reply targets for this notice.
1091      *
1092      * @return array of integer profile ids
1093      */
1094     function getReplies()
1095     {
1096         // XXX: cache me
1097
1098         $ids = array();
1099
1100         $reply = new Reply();
1101         $reply->selectAdd();
1102         $reply->selectAdd('profile_id');
1103         $reply->notice_id = $this->id;
1104
1105         if ($reply->find()) {
1106             while($reply->fetch()) {
1107                 $ids[] = $reply->profile_id;
1108             }
1109         }
1110
1111         $reply->free();
1112
1113         return $ids;
1114     }
1115
1116     /**
1117      * Send e-mail notifications to local @-reply targets.
1118      *
1119      * Replies must already have been saved; this is expected to be run
1120      * from the distrib queue handler.
1121      */
1122     function sendReplyNotifications()
1123     {
1124         // Don't send reply notifications for repeats
1125
1126         if (!empty($this->repeat_of)) {
1127             return array();
1128         }
1129
1130         $recipientIds = $this->getReplies();
1131
1132         foreach ($recipientIds as $recipientId) {
1133             $user = User::staticGet('id', $recipientId);
1134             if (!empty($user)) {
1135                 mail_notify_attn($user, $this);
1136             }
1137         }
1138     }
1139
1140     /**
1141      * Pull list of groups this notice needs to be delivered to,
1142      * as previously recorded by saveGroups() or saveKnownGroups().
1143      *
1144      * @return array of Group objects
1145      */
1146     function getGroups()
1147     {
1148         // Don't save groups for repeats
1149
1150         if (!empty($this->repeat_of)) {
1151             return array();
1152         }
1153
1154         // XXX: cache me
1155
1156         $groups = array();
1157
1158         $gi = new Group_inbox();
1159
1160         $gi->selectAdd();
1161         $gi->selectAdd('group_id');
1162
1163         $gi->notice_id = $this->id;
1164
1165         if ($gi->find()) {
1166             while ($gi->fetch()) {
1167                 $group = User_group::staticGet('id', $gi->group_id);
1168                 if ($group) {
1169                     $groups[] = $group;
1170                 }
1171             }
1172         }
1173
1174         $gi->free();
1175
1176         return $groups;
1177     }
1178
1179     function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1180     {
1181         $profile = $this->getProfile();
1182
1183         $xs = new XMLStringer(true);
1184
1185         if ($namespace) {
1186             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1187                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1188                            'xmlns:georss' => 'http://www.georss.org/georss',
1189                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1190                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
1191                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1192                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1193                            'xmlns:statusnet' => 'http://status.net/ont/');
1194         } else {
1195             $attrs = array();
1196         }
1197
1198         $xs->elementStart('entry', $attrs);
1199
1200         if ($source) {
1201             $xs->elementStart('source');
1202             $xs->element('id', null, $profile->profileurl);
1203             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1204             $xs->element('link', array('href' => $profile->profileurl));
1205             $user = User::staticGet('id', $profile->id);
1206             if (!empty($user)) {
1207                 $atom_feed = common_local_url('ApiTimelineUser',
1208                                               array('format' => 'atom',
1209                                                     'id' => $profile->nickname));
1210                 $xs->element('link', array('rel' => 'self',
1211                                            'type' => 'application/atom+xml',
1212                                            'href' => $profile->profileurl));
1213                 $xs->element('link', array('rel' => 'license',
1214                                            'href' => common_config('license', 'url')));
1215             }
1216
1217             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1218             $xs->element('updated', null, common_date_w3dtf($this->created));
1219         }
1220
1221         if ($source) {
1222             $xs->elementEnd('source');
1223         }
1224
1225         $xs->element('title', null, common_xml_safe_str($this->content));
1226
1227         if ($author) {
1228             $xs->raw($profile->asAtomAuthor());
1229             $xs->raw($profile->asActivityActor());
1230         }
1231
1232         $xs->element('link', array('rel' => 'alternate',
1233                                    'type' => 'text/html',
1234                                    'href' => $this->bestUrl()));
1235
1236         $xs->element('id', null, $this->uri);
1237
1238         $xs->element('published', null, common_date_w3dtf($this->created));
1239         $xs->element('updated', null, common_date_w3dtf($this->created));
1240
1241         $noticeInfoAttr = array(
1242             'local_id'   => $this->id,    // local notice ID (useful to clients for ordering)
1243             'source'     => $this->source, // the client name (source attribution)
1244         );
1245
1246         $ns = $this->getSource();
1247         if ($ns) {
1248             if (!empty($ns->url)) {
1249                 $noticeInfoAttr['source_link'] = $ns->url;
1250             }
1251         }
1252
1253         if (!empty($cur)) {
1254             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1255         }
1256
1257         if (!empty($this->repeat_of)) {
1258             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1259         }
1260
1261         $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1262
1263         if ($this->reply_to) {
1264             $reply_notice = Notice::staticGet('id', $this->reply_to);
1265             if (!empty($reply_notice)) {
1266                 $xs->element('link', array('rel' => 'related',
1267                                            'href' => $reply_notice->bestUrl()));
1268                 $xs->element('thr:in-reply-to',
1269                              array('ref' => $reply_notice->uri,
1270                                    'href' => $reply_notice->bestUrl()));
1271             }
1272         }
1273
1274         if (!empty($this->conversation)) {
1275
1276             $conv = Conversation::staticGet('id', $this->conversation);
1277
1278             if (!empty($conv)) {
1279                 $xs->element(
1280                     'link', array(
1281                         'rel' => 'ostatus:conversation',
1282                         'href' => $conv->uri
1283                     )
1284                 );
1285             }
1286         }
1287
1288         $reply_ids = $this->getReplies();
1289
1290         foreach ($reply_ids as $id) {
1291             $profile = Profile::staticGet('id', $id);
1292            if (!empty($profile)) {
1293                 $xs->element(
1294                     'link', array(
1295                         'rel' => 'ostatus:attention',
1296                         'href' => $profile->getUri()
1297                     )
1298                 );
1299             }
1300         }
1301
1302         $groups = $this->getGroups();
1303
1304         foreach ($groups as $group) {
1305             $xs->element(
1306                 'link', array(
1307                     'rel' => 'ostatus:attention',
1308                     'href' => $group->permalink()
1309                 )
1310             );
1311         }
1312
1313         if (!empty($this->repeat_of)) {
1314             $repeat = Notice::staticGet('id', $this->repeat_of);
1315             if (!empty($repeat)) {
1316                 $xs->element(
1317                     'ostatus:forward',
1318                      array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1319                 );
1320             }
1321         }
1322
1323         $xs->element(
1324             'content',
1325             array('type' => 'html'),
1326             common_xml_safe_str($this->rendered)
1327         );
1328
1329         $tag = new Notice_tag();
1330         $tag->notice_id = $this->id;
1331         if ($tag->find()) {
1332             while ($tag->fetch()) {
1333                 $xs->element('category', array('term' => $tag->tag));
1334             }
1335         }
1336         $tag->free();
1337
1338         # Enclosures
1339         $attachments = $this->attachments();
1340         if($attachments){
1341             foreach($attachments as $attachment){
1342                 $enclosure=$attachment->getEnclosure();
1343                 if ($enclosure) {
1344                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1345                     if($enclosure->title){
1346                         $attributes['title']=$enclosure->title;
1347                     }
1348                     $xs->element('link', $attributes, null);
1349                 }
1350             }
1351         }
1352
1353         if (!empty($this->lat) && !empty($this->lon)) {
1354             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1355         }
1356
1357         $xs->elementEnd('entry');
1358
1359         return $xs->getString();
1360     }
1361
1362     /**
1363      * Returns an XML string fragment with a reference to a notice as an
1364      * Activity Streams noun object with the given element type.
1365      *
1366      * Assumes that 'activity' namespace has been previously defined.
1367      *
1368      * @param string $element one of 'subject', 'object', 'target'
1369      * @return string
1370      */
1371     function asActivityNoun($element)
1372     {
1373         $noun = ActivityObject::fromNotice($this);
1374         return $noun->asString('activity:' . $element);
1375     }
1376
1377     function bestUrl()
1378     {
1379         if (!empty($this->url)) {
1380             return $this->url;
1381         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1382             return $this->uri;
1383         } else {
1384             return common_local_url('shownotice',
1385                                     array('notice' => $this->id));
1386         }
1387     }
1388
1389     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1390     {
1391         $cache = common_memcache();
1392
1393         if (empty($cache) ||
1394             $since_id != 0 || $max_id != 0 ||
1395             is_null($limit) ||
1396             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1397             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1398                                                                       $max_id)));
1399         }
1400
1401         $idkey = common_cache_key($cachekey);
1402
1403         $idstr = $cache->get($idkey);
1404
1405         if ($idstr !== false) {
1406             // Cache hit! Woohoo!
1407             $window = explode(',', $idstr);
1408             $ids = array_slice($window, $offset, $limit);
1409             return $ids;
1410         }
1411
1412         $laststr = $cache->get($idkey.';last');
1413
1414         if ($laststr !== false) {
1415             $window = explode(',', $laststr);
1416             $last_id = $window[0];
1417             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1418                                                                           $last_id, 0, null)));
1419
1420             $new_window = array_merge($new_ids, $window);
1421
1422             $new_windowstr = implode(',', $new_window);
1423
1424             $result = $cache->set($idkey, $new_windowstr);
1425             $result = $cache->set($idkey . ';last', $new_windowstr);
1426
1427             $ids = array_slice($new_window, $offset, $limit);
1428
1429             return $ids;
1430         }
1431
1432         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1433                                                                      0, 0, null)));
1434
1435         $windowstr = implode(',', $window);
1436
1437         $result = $cache->set($idkey, $windowstr);
1438         $result = $cache->set($idkey . ';last', $windowstr);
1439
1440         $ids = array_slice($window, $offset, $limit);
1441
1442         return $ids;
1443     }
1444
1445     /**
1446      * Determine which notice, if any, a new notice is in reply to.
1447      *
1448      * For conversation tracking, we try to see where this notice fits
1449      * in the tree. Rough algorithm is:
1450      *
1451      * if (reply_to is set and valid) {
1452      *     return reply_to;
1453      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1454      *     return ID of last notice by initial @name in content;
1455      * }
1456      *
1457      * Note that all @nickname instances will still be used to save "reply" records,
1458      * so the notice shows up in the mentioned users' "replies" tab.
1459      *
1460      * @param integer $reply_to   ID passed in by Web or API
1461      * @param integer $profile_id ID of author
1462      * @param string  $source     Source tag, like 'web' or 'gwibber'
1463      * @param string  $content    Final notice content
1464      *
1465      * @return integer ID of replied-to notice, or null for not a reply.
1466      */
1467
1468     static function getReplyTo($reply_to, $profile_id, $source, $content)
1469     {
1470         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1471
1472         // If $reply_to is specified, we check that it exists, and then
1473         // return it if it does
1474
1475         if (!empty($reply_to)) {
1476             $reply_notice = Notice::staticGet('id', $reply_to);
1477             if (!empty($reply_notice)) {
1478                 return $reply_to;
1479             }
1480         }
1481
1482         // If it's not a "low bandwidth" source (one where you can't set
1483         // a reply_to argument), we return. This is mostly web and API
1484         // clients.
1485
1486         if (!in_array($source, $lb)) {
1487             return null;
1488         }
1489
1490         // Is there an initial @ or T?
1491
1492         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1493             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1494             $nickname = common_canonical_nickname($match[1]);
1495         } else {
1496             return null;
1497         }
1498
1499         // Figure out who that is.
1500
1501         $sender = Profile::staticGet('id', $profile_id);
1502         if (empty($sender)) {
1503             return null;
1504         }
1505
1506         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1507
1508         if (empty($recipient)) {
1509             return null;
1510         }
1511
1512         // Get their last notice
1513
1514         $last = $recipient->getCurrentNotice();
1515
1516         if (!empty($last)) {
1517             return $last->id;
1518         }
1519     }
1520
1521     static function maxContent()
1522     {
1523         $contentlimit = common_config('notice', 'contentlimit');
1524         // null => use global limit (distinct from 0!)
1525         if (is_null($contentlimit)) {
1526             $contentlimit = common_config('site', 'textlimit');
1527         }
1528         return $contentlimit;
1529     }
1530
1531     static function contentTooLong($content)
1532     {
1533         $contentlimit = self::maxContent();
1534         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1535     }
1536
1537     function getLocation()
1538     {
1539         $location = null;
1540
1541         if (!empty($this->location_id) && !empty($this->location_ns)) {
1542             $location = Location::fromId($this->location_id, $this->location_ns);
1543         }
1544
1545         if (is_null($location)) { // no ID, or Location::fromId() failed
1546             if (!empty($this->lat) && !empty($this->lon)) {
1547                 $location = Location::fromLatLon($this->lat, $this->lon);
1548             }
1549         }
1550
1551         return $location;
1552     }
1553
1554     function repeat($repeater_id, $source)
1555     {
1556         $author = Profile::staticGet('id', $this->profile_id);
1557
1558         $content = sprintf(_('RT @%1$s %2$s'),
1559                            $author->nickname,
1560                            $this->content);
1561
1562         $maxlen = common_config('site', 'textlimit');
1563         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1564             // Web interface and current Twitter API clients will
1565             // pull the original notice's text, but some older
1566             // clients and RSS/Atom feeds will see this trimmed text.
1567             //
1568             // Unfortunately this is likely to lose tags or URLs
1569             // at the end of long notices.
1570             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1571         }
1572
1573         return self::saveNew($repeater_id, $content, $source,
1574                              array('repeat_of' => $this->id));
1575     }
1576
1577     // These are supposed to be in chron order!
1578
1579     function repeatStream($limit=100)
1580     {
1581         $cache = common_memcache();
1582
1583         if (empty($cache)) {
1584             $ids = $this->_repeatStreamDirect($limit);
1585         } else {
1586             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1587             if ($idstr !== false) {
1588                 $ids = explode(',', $idstr);
1589             } else {
1590                 $ids = $this->_repeatStreamDirect(100);
1591                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1592             }
1593             if ($limit < 100) {
1594                 // We do a max of 100, so slice down to limit
1595                 $ids = array_slice($ids, 0, $limit);
1596             }
1597         }
1598
1599         return Notice::getStreamByIds($ids);
1600     }
1601
1602     function _repeatStreamDirect($limit)
1603     {
1604         $notice = new Notice();
1605
1606         $notice->selectAdd(); // clears it
1607         $notice->selectAdd('id');
1608
1609         $notice->repeat_of = $this->id;
1610
1611         $notice->orderBy('created'); // NB: asc!
1612
1613         if (!is_null($offset)) {
1614             $notice->limit($offset, $limit);
1615         }
1616
1617         $ids = array();
1618
1619         if ($notice->find()) {
1620             while ($notice->fetch()) {
1621                 $ids[] = $notice->id;
1622             }
1623         }
1624
1625         $notice->free();
1626         $notice = NULL;
1627
1628         return $ids;
1629     }
1630
1631     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1632     {
1633         $options = array();
1634
1635         if (!empty($location_id) && !empty($location_ns)) {
1636
1637             $options['location_id'] = $location_id;
1638             $options['location_ns'] = $location_ns;
1639
1640             $location = Location::fromId($location_id, $location_ns);
1641
1642             if (!empty($location)) {
1643                 $options['lat'] = $location->lat;
1644                 $options['lon'] = $location->lon;
1645             }
1646
1647         } else if (!empty($lat) && !empty($lon)) {
1648
1649             $options['lat'] = $lat;
1650             $options['lon'] = $lon;
1651
1652             $location = Location::fromLatLon($lat, $lon);
1653
1654             if (!empty($location)) {
1655                 $options['location_id'] = $location->location_id;
1656                 $options['location_ns'] = $location->location_ns;
1657             }
1658         } else if (!empty($profile)) {
1659
1660             if (isset($profile->lat) && isset($profile->lon)) {
1661                 $options['lat'] = $profile->lat;
1662                 $options['lon'] = $profile->lon;
1663             }
1664
1665             if (isset($profile->location_id) && isset($profile->location_ns)) {
1666                 $options['location_id'] = $profile->location_id;
1667                 $options['location_ns'] = $profile->location_ns;
1668             }
1669         }
1670
1671         return $options;
1672     }
1673
1674     function clearReplies()
1675     {
1676         $replyNotice = new Notice();
1677         $replyNotice->reply_to = $this->id;
1678
1679         //Null any notices that are replies to this notice
1680
1681         if ($replyNotice->find()) {
1682             while ($replyNotice->fetch()) {
1683                 $orig = clone($replyNotice);
1684                 $replyNotice->reply_to = null;
1685                 $replyNotice->update($orig);
1686             }
1687         }
1688
1689         // Reply records
1690
1691         $reply = new Reply();
1692         $reply->notice_id = $this->id;
1693
1694         if ($reply->find()) {
1695             while($reply->fetch()) {
1696                 self::blow('reply:stream:%d', $reply->profile_id);
1697                 $reply->delete();
1698             }
1699         }
1700
1701         $reply->free();
1702     }
1703
1704     function clearRepeats()
1705     {
1706         $repeatNotice = new Notice();
1707         $repeatNotice->repeat_of = $this->id;
1708
1709         //Null any notices that are repeats of this notice
1710
1711         if ($repeatNotice->find()) {
1712             while ($repeatNotice->fetch()) {
1713                 $orig = clone($repeatNotice);
1714                 $repeatNotice->repeat_of = null;
1715                 $repeatNotice->update($orig);
1716             }
1717         }
1718     }
1719
1720     function clearFaves()
1721     {
1722         $fave = new Fave();
1723         $fave->notice_id = $this->id;
1724
1725         if ($fave->find()) {
1726             while ($fave->fetch()) {
1727                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1728                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1729                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1730                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1731                 $fave->delete();
1732             }
1733         }
1734
1735         $fave->free();
1736     }
1737
1738     function clearTags()
1739     {
1740         $tag = new Notice_tag();
1741         $tag->notice_id = $this->id;
1742
1743         if ($tag->find()) {
1744             while ($tag->fetch()) {
1745                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1746                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1747                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1748                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1749                 $tag->delete();
1750             }
1751         }
1752
1753         $tag->free();
1754     }
1755
1756     function clearGroupInboxes()
1757     {
1758         $gi = new Group_inbox();
1759
1760         $gi->notice_id = $this->id;
1761
1762         if ($gi->find()) {
1763             while ($gi->fetch()) {
1764                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1765                 $gi->delete();
1766             }
1767         }
1768
1769         $gi->free();
1770     }
1771
1772     function distribute()
1773     {
1774         // We always insert for the author so they don't
1775         // have to wait
1776
1777         $user = User::staticGet('id', $this->profile_id);
1778         if (!empty($user)) {
1779             Inbox::insertNotice($user->id, $this->id);
1780         }
1781
1782         if (common_config('queue', 'inboxes')) {
1783             // If there's a failure, we want to _force_
1784             // distribution at this point.
1785             try {
1786                 $qm = QueueManager::get();
1787                 $qm->enqueue($this, 'distrib');
1788             } catch (Exception $e) {
1789                 // If the exception isn't transient, this
1790                 // may throw more exceptions as DQH does
1791                 // its own enqueueing. So, we ignore them!
1792                 try {
1793                     $handler = new DistribQueueHandler();
1794                     $handler->handle($this);
1795                 } catch (Exception $e) {
1796                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1797                 }
1798                 // Re-throw so somebody smarter can handle it.
1799                 throw $e;
1800             }
1801         } else {
1802             $handler = new DistribQueueHandler();
1803             $handler->handle($this);
1804         }
1805     }
1806
1807     function insert()
1808     {
1809         $result = parent::insert();
1810
1811         if ($result) {
1812             // Profile::hasRepeated() abuses pkeyGet(), so we
1813             // have to clear manually
1814             if (!empty($this->repeat_of)) {
1815                 $c = self::memcache();
1816                 if (!empty($c)) {
1817                     $ck = self::multicacheKey('Notice',
1818                                               array('profile_id' => $this->profile_id,
1819                                                     'repeat_of' => $this->repeat_of));
1820                     $c->delete($ck);
1821                 }
1822             }
1823         }
1824
1825         return $result;
1826     }
1827
1828     /**
1829      * Get the source of the notice
1830      *
1831      * @return Notice_source $ns A notice source object. 'code' is the only attribute
1832      *                           guaranteed to be populated.
1833      */
1834     function getSource()
1835     {
1836         $ns = new Notice_source();
1837         if (!empty($this->source)) {
1838             switch ($this->source) {
1839             case 'web':
1840             case 'xmpp':
1841             case 'mail':
1842             case 'omb':
1843             case 'system':
1844             case 'api':
1845                 $ns->code = $this->source;
1846                 break;
1847             default:
1848                 $ns = Notice_source::staticGet($this->source);
1849                 if (!$ns) {
1850                     $ns = new Notice_source();
1851                     $ns->code = $this->source;
1852                     $app = Oauth_application::staticGet('name', $this->source);
1853                     if ($app) {
1854                         $ns->name = $app->name;
1855                         $ns->url  = $app->source_url;
1856                     }
1857                 }
1858                 break;
1859             }
1860         }
1861         return $ns;
1862     }
1863
1864 }