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