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