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