]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch '0.7.x' into 0.8.x
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, 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
20 if (!defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for notice
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28  * in the memcached cache. */
29
30 define('NOTICE_CACHE_WINDOW', 61);
31
32 class Notice extends Memcached_DataObject
33 {
34     ###START_AUTOCODE
35     /* the code below is auto generated do not remove the above tag */
36
37     public $__table = 'notice';                          // table name
38     public $id;                              // int(4)  primary_key not_null
39     public $profile_id;                      // int(4)   not_null
40     public $uri;                             // varchar(255)  unique_key
41     public $content;                         // varchar(140)
42     public $rendered;                        // text()
43     public $url;                             // varchar(255)
44     public $created;                         // datetime()   not_null
45     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
46     public $reply_to;                        // int(4)
47     public $is_local;                        // tinyint(1)
48     public $source;                          // varchar(32)
49     public $conversation;                    // int(4)
50
51     /* Static get */
52     function staticGet($k,$v=NULL) {
53         return Memcached_DataObject::staticGet('Notice',$k,$v);
54     }
55
56     /* the code above is auto generated do not remove the tag below */
57     ###END_AUTOCODE
58
59     function getProfile()
60     {
61         return Profile::staticGet('id', $this->profile_id);
62     }
63
64     function delete()
65     {
66         $this->blowCaches(true);
67         $this->blowFavesCache(true);
68         $this->blowSubsCache(true);
69
70         $this->query('BEGIN');
71         //Null any notices that are replies to this notice
72         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
73         $related = array('Reply',
74                          'Fave',
75                          'Notice_tag',
76                          'Group_inbox',
77                          'Queue_item');
78         if (common_config('inboxes', 'enabled')) {
79             $related[] = 'Notice_inbox';
80         }
81         foreach ($related as $cls) {
82             $inst = new $cls();
83             $inst->notice_id = $this->id;
84             $inst->delete();
85         }
86         $result = parent::delete();
87         $this->query('COMMIT');
88     }
89
90     function saveTags()
91     {
92         /* extract all #hastags */
93         $count = preg_match_all('/(?:^|\s)#([A-Za-z0-9_\-\.]{1,64})/', strtolower($this->content), $match);
94         if (!$count) {
95             return true;
96         }
97
98         /* Add them to the database */
99         foreach(array_unique($match[1]) as $hashtag) {
100             /* elide characters we don't want in the tag */
101             $this->saveTag($hashtag);
102         }
103         return true;
104     }
105
106     function saveTag($hashtag)
107     {
108         $hashtag = common_canonical_tag($hashtag);
109
110         $tag = new Notice_tag();
111         $tag->notice_id = $this->id;
112         $tag->tag = $hashtag;
113         $tag->created = $this->created;
114         $id = $tag->insert();
115
116         if (!$id) {
117             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
118                                               $last_error->message));
119             return;
120         }
121     }
122
123     static function saveNew($profile_id, $content, $source=null,
124                             $is_local=1, $reply_to=null, $uri=null, $created=null) {
125
126         $profile = Profile::staticGet($profile_id);
127
128         $final = common_shorten_links($content);
129
130         if (mb_strlen($final) > 140) {
131             common_log(LOG_INFO, 'Rejecting notice that is too long.');
132             return _('Problem saving notice. Too long.');
133         }
134
135         if (!$profile) {
136             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
137             return _('Problem saving notice. Unknown user.');
138         }
139
140         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
141             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
142             return _('Too many notices too fast; take a breather and post again in a few minutes.');
143         }
144
145         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
146             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
147                         return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
148         }
149
150                 $banned = common_config('profile', 'banned');
151
152         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
153             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
154             return _('You are banned from posting notices on this site.');
155         }
156
157         $notice = new Notice();
158         $notice->profile_id = $profile_id;
159
160         $blacklist = common_config('public', 'blacklist');
161         $autosource = common_config('public', 'autosource');
162
163         # Blacklisted are non-false, but not 1, either
164
165         if (($blacklist && in_array($profile_id, $blacklist)) ||
166             ($source && $autosource && in_array($source, $autosource))) {
167             $notice->is_local = -1;
168         } else {
169             $notice->is_local = $is_local;
170         }
171
172                 $notice->query('BEGIN');
173
174                 $notice->reply_to = $reply_to;
175         if (!empty($created)) {
176             $notice->created = $created;
177         } else {
178             $notice->created = common_sql_now();
179         }
180                 $notice->content = $final;
181                 $notice->rendered = common_render_content($final, $notice);
182                 $notice->source = $source;
183                 $notice->uri = $uri;
184
185         if (!empty($reply_to)) {
186             $reply_notice = Notice::staticGet('id', $reply_to);
187             if (!empty($reply_notice)) {
188                 $notice->reply_to = $reply_to;
189                 $notice->conversation = $reply_notice->conversation;
190             }
191         }
192
193         if (Event::handle('StartNoticeSave', array(&$notice))) {
194
195             $id = $notice->insert();
196
197             if (!$id) {
198                 common_log_db_error($notice, 'INSERT', __FILE__);
199                 return _('Problem saving notice.');
200             }
201
202             # Update the URI after the notice is in the database
203             if (!$uri) {
204                 $orig = clone($notice);
205                 $notice->uri = common_notice_uri($notice);
206
207                 if (!$notice->update($orig)) {
208                     common_log_db_error($notice, 'UPDATE', __FILE__);
209                     return _('Problem saving notice.');
210                 }
211             }
212
213             # XXX: do we need to change this for remote users?
214
215             $notice->saveReplies();
216             $notice->saveTags();
217
218             $notice->addToInboxes();
219             $notice->saveGroups();
220
221             $notice->query('COMMIT');
222
223             Event::handle('EndNoticeSave', array($notice));
224         }
225
226         # Clear the cache for subscribed users, so they'll update at next request
227         # XXX: someone clever could prepend instead of clearing the cache
228
229         $notice->blowCaches();
230
231         return $notice;
232     }
233
234     static function checkDupes($profile_id, $content) {
235         $profile = Profile::staticGet($profile_id);
236         if (!$profile) {
237             return false;
238         }
239         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
240         if ($notice) {
241             $last = 0;
242             while ($notice->fetch()) {
243                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
244                     return true;
245                 } else if ($notice->content == $content) {
246                     return false;
247                 }
248             }
249         }
250         # If we get here, oldest item in cache window is not
251         # old enough for dupe limit; do direct check against DB
252         $notice = new Notice();
253         $notice->profile_id = $profile_id;
254         $notice->content = $content;
255         if (common_config('db','type') == 'pgsql')
256             $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
257         else
258             $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
259
260         $cnt = $notice->count();
261         return ($cnt == 0);
262     }
263
264     static function checkEditThrottle($profile_id) {
265         $profile = Profile::staticGet($profile_id);
266         if (!$profile) {
267             return false;
268         }
269         # Get the Nth notice
270         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
271         if ($notice && $notice->fetch()) {
272             # If the Nth notice was posted less than timespan seconds ago
273             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
274                 # Then we throttle
275                 return false;
276             }
277         }
278         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
279         return true;
280     }
281
282     function getUploadedAttachment() {
283         $post = clone $this;
284         $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"';
285         $post->query($query);
286         $post->fetch();
287         if (empty($post->up) || empty($post->i)) {
288             $ret = false;
289         } else {
290             $ret = array($post->up, $post->i);
291         }
292         $post->free();
293         return $ret;
294     }
295
296     function hasAttachments() {
297         $post = clone $this;
298         $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);
299         $post->query($query);
300         $post->fetch();
301         $n_attachments = intval($post->n_attachments);
302         $post->free();
303         return $n_attachments;
304     }
305
306     function blowCaches($blowLast=false)
307     {
308         $this->blowSubsCache($blowLast);
309         $this->blowNoticeCache($blowLast);
310         $this->blowRepliesCache($blowLast);
311         $this->blowPublicCache($blowLast);
312         $this->blowTagCache($blowLast);
313         $this->blowGroupCache($blowLast);
314     }
315
316     function blowGroupCache($blowLast=false)
317     {
318         $cache = common_memcache();
319         if ($cache) {
320             $group_inbox = new Group_inbox();
321             $group_inbox->notice_id = $this->id;
322             if ($group_inbox->find()) {
323                 while ($group_inbox->fetch()) {
324                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
325                     if ($blowLast) {
326                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
327                     }
328                     $member = new Group_member();
329                     $member->group_id = $group_inbox->group_id;
330                     if ($member->find()) {
331                         while ($member->fetch()) {
332                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
333                             if ($blowLast) {
334                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
335                             }
336                         }
337                     }
338                 }
339             }
340             $group_inbox->free();
341             unset($group_inbox);
342         }
343     }
344
345     function blowTagCache($blowLast=false)
346     {
347         $cache = common_memcache();
348         if ($cache) {
349             $tag = new Notice_tag();
350             $tag->notice_id = $this->id;
351             if ($tag->find()) {
352                 while ($tag->fetch()) {
353                     $tag->blowCache($blowLast);
354                 }
355             }
356             $tag->free();
357             unset($tag);
358         }
359     }
360
361     function blowSubsCache($blowLast=false)
362     {
363         $cache = common_memcache();
364         if ($cache) {
365             $user = new User();
366
367             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
368             $user->query('SELECT id ' .
369
370                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
371                          'WHERE subscription.subscribed = ' . $this->profile_id);
372
373             while ($user->fetch()) {
374                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
375                 if ($blowLast) {
376                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
377                 }
378             }
379             $user->free();
380             unset($user);
381         }
382     }
383
384     function blowNoticeCache($blowLast=false)
385     {
386         if ($this->is_local) {
387             $cache = common_memcache();
388             if (!empty($cache)) {
389                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
390                 if ($blowLast) {
391                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
392                 }
393             }
394         }
395     }
396
397     function blowRepliesCache($blowLast=false)
398     {
399         $cache = common_memcache();
400         if ($cache) {
401             $reply = new Reply();
402             $reply->notice_id = $this->id;
403             if ($reply->find()) {
404                 while ($reply->fetch()) {
405                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
406                     if ($blowLast) {
407                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
408                     }
409                 }
410             }
411             $reply->free();
412             unset($reply);
413         }
414     }
415
416     function blowPublicCache($blowLast=false)
417     {
418         if ($this->is_local == 1) {
419             $cache = common_memcache();
420             if ($cache) {
421                 $cache->delete(common_cache_key('public'));
422                 if ($blowLast) {
423                     $cache->delete(common_cache_key('public').';last');
424                 }
425             }
426         }
427     }
428
429     function blowFavesCache($blowLast=false)
430     {
431         $cache = common_memcache();
432         if ($cache) {
433             $fave = new Fave();
434             $fave->notice_id = $this->id;
435             if ($fave->find()) {
436                 while ($fave->fetch()) {
437                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
438                     if ($blowLast) {
439                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
440                     }
441                 }
442             }
443             $fave->free();
444             unset($fave);
445         }
446     }
447
448     # XXX: too many args; we need to move to named params or even a separate
449     # class for notice streams
450
451     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
452
453         if (common_config('memcached', 'enabled')) {
454
455             # Skip the cache if this is a since, since_id or max_id qry
456             if ($since_id > 0 || $max_id > 0 || $since) {
457                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
458             } else {
459                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
460             }
461         }
462
463         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
464     }
465
466     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
467
468         $needAnd = false;
469         $needWhere = true;
470
471         if (preg_match('/\bWHERE\b/i', $qry)) {
472             $needWhere = false;
473             $needAnd = true;
474         }
475
476         if ($since_id > 0) {
477
478             if ($needWhere) {
479                 $qry .= ' WHERE ';
480                 $needWhere = false;
481             } else {
482                 $qry .= ' AND ';
483             }
484
485             $qry .= ' notice.id > ' . $since_id;
486         }
487
488         if ($max_id > 0) {
489
490             if ($needWhere) {
491                 $qry .= ' WHERE ';
492                 $needWhere = false;
493             } else {
494                 $qry .= ' AND ';
495             }
496
497             $qry .= ' notice.id <= ' . $max_id;
498         }
499
500         if ($since) {
501
502             if ($needWhere) {
503                 $qry .= ' WHERE ';
504                 $needWhere = false;
505             } else {
506                 $qry .= ' AND ';
507             }
508
509             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
510         }
511
512         # Allow ORDER override
513
514         if ($order) {
515             $qry .= $order;
516         } else {
517             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
518         }
519
520         if (common_config('db','type') == 'pgsql') {
521             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
522         } else {
523             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
524         }
525
526         $notice = new Notice();
527
528         $notice->query($qry);
529
530         return $notice;
531     }
532
533     # XXX: this is pretty long and should probably be broken up into
534     # some helper functions
535
536     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
537
538         # If outside our cache window, just go to the DB
539
540         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
541             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
542         }
543
544         # Get the cache; if we can't, just go to the DB
545
546         $cache = common_memcache();
547
548         if (!$cache) {
549             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
550         }
551
552         # Get the notices out of the cache
553
554         $notices = $cache->get(common_cache_key($cachekey));
555
556         # On a cache hit, return a DB-object-like wrapper
557
558         if ($notices !== false) {
559             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
560             return $wrapper;
561         }
562
563         # If the cache was invalidated because of new data being
564         # added, we can try and just get the new stuff. We keep an additional
565         # copy of the data at the key + ';last'
566
567         # No cache hit. Try to get the *last* cached version
568
569         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
570
571         if ($last_notices) {
572
573             # Reverse-chron order, so last ID is last.
574
575             $last_id = $last_notices[0]->id;
576
577             # XXX: this assumes monotonically increasing IDs; a fair
578             # bet with our DB.
579
580             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
581                                                   $last_id, null, $order, null);
582
583             if ($new_notice) {
584                 $new_notices = array();
585                 while ($new_notice->fetch()) {
586                     $new_notices[] = clone($new_notice);
587                 }
588                 $new_notice->free();
589                 $notices = array_slice(array_merge($new_notices, $last_notices),
590                                        0, NOTICE_CACHE_WINDOW);
591
592                 # Store the array in the cache for next time
593
594                 $result = $cache->set(common_cache_key($cachekey), $notices);
595                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
596
597                 # return a wrapper of the array for use now
598
599                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
600             }
601         }
602
603         # Otherwise, get the full cache window out of the DB
604
605         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
606
607         # If there are no hits, just return the value
608
609         if (!$notice) {
610             return $notice;
611         }
612
613         # Pack results into an array
614
615         $notices = array();
616
617         while ($notice->fetch()) {
618             $notices[] = clone($notice);
619         }
620
621         $notice->free();
622
623         # Store the array in the cache for next time
624
625         $result = $cache->set(common_cache_key($cachekey), $notices);
626         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
627
628         # return a wrapper of the array for use now
629
630         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
631
632         return $wrapper;
633     }
634
635     function getStreamByIds($ids)
636     {
637         $cache = common_memcache();
638
639         if (!empty($cache)) {
640             $notices = array();
641             foreach ($ids as $id) {
642                 $notices[] = Notice::staticGet('id', $id);
643             }
644             return new ArrayWrapper($notices);
645         } else {
646             $notice = new Notice();
647             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
648             $notice->orderBy('id DESC');
649
650             $notice->find();
651             return $notice;
652         }
653     }
654
655     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
656     {
657         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
658                               array(),
659                               'public',
660                               $offset, $limit, $since_id, $max_id, $since);
661
662         return Notice::getStreamByIds($ids);
663     }
664
665     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
666     {
667         $notice = new Notice();
668
669         $notice->selectAdd(); // clears it
670         $notice->selectAdd('id');
671
672         $notice->orderBy('id DESC');
673
674         if (!is_null($offset)) {
675             $notice->limit($offset, $limit);
676         }
677
678         if (common_config('public', 'localonly')) {
679             $notice->whereAdd('is_local = 1');
680         } else {
681             # -1 == blacklisted
682             $notice->whereAdd('is_local != -1');
683         }
684
685         if ($since_id != 0) {
686             $notice->whereAdd('id > ' . $since_id);
687         }
688
689         if ($max_id != 0) {
690             $notice->whereAdd('id <= ' . $max_id);
691         }
692
693         if (!is_null($since)) {
694             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
695         }
696
697         $ids = array();
698
699         if ($notice->find()) {
700             while ($notice->fetch()) {
701                 $ids[] = $notice->id;
702             }
703         }
704
705         $notice->free();
706         $notice = NULL;
707
708         return $ids;
709     }
710
711     function addToInboxes()
712     {
713         $enabled = common_config('inboxes', 'enabled');
714
715         if ($enabled === true || $enabled === 'transitional') {
716             $inbox = new Notice_inbox();
717             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
718             $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created) ' .
719               "SELECT $UT.id, " . $this->id . ", '" . $this->created . "' " .
720               "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
721               'WHERE subscription.subscribed = ' . $this->profile_id . ' ' .
722               'AND NOT EXISTS (SELECT user_id, notice_id ' .
723               'FROM notice_inbox ' .
724               "WHERE user_id = $UT.id " .
725               'AND notice_id = ' . $this->id . ' )';
726             if ($enabled === 'transitional') {
727                 $qry .= " AND $UT.inboxed = 1";
728             }
729             $inbox->query($qry);
730         }
731         return;
732     }
733
734     function saveGroups()
735     {
736         $enabled = common_config('inboxes', 'enabled');
737         if ($enabled !== true && $enabled !== 'transitional') {
738             return;
739         }
740
741         /* extract all !group */
742         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
743                                 strtolower($this->content),
744                                 $match);
745         if (!$count) {
746             return true;
747         }
748
749         $profile = $this->getProfile();
750
751         /* Add them to the database */
752
753         foreach (array_unique($match[1]) as $nickname) {
754             /* XXX: remote groups. */
755             $group = User_group::staticGet('nickname', $nickname);
756
757             if (!$group) {
758                 continue;
759             }
760
761             // we automatically add a tag for every group name, too
762
763             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
764                                            'notice_id' => $this->id));
765
766             if (is_null($tag)) {
767                 $this->saveTag($nickname);
768             }
769
770             if ($profile->isMember($group)) {
771
772                 $gi = new Group_inbox();
773
774                 $gi->group_id  = $group->id;
775                 $gi->notice_id = $this->id;
776                 $gi->created   = common_sql_now();
777
778                 $result = $gi->insert();
779
780                 if (!$result) {
781                     common_log_db_error($gi, 'INSERT', __FILE__);
782                 }
783
784                 // FIXME: do this in an offline daemon
785
786                 $this->addToGroupInboxes($group);
787             }
788         }
789     }
790
791     function addToGroupInboxes($group)
792     {
793         $inbox = new Notice_inbox();
794         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
795         $qry = 'INSERT INTO notice_inbox (user_id, notice_id, created, source) ' .
796           "SELECT $UT.id, " . $this->id . ", '" . $this->created . "', 2 " .
797           "FROM $UT JOIN group_member ON $UT.id = group_member.profile_id " .
798           'WHERE group_member.group_id = ' . $group->id . ' ' .
799           'AND NOT EXISTS (SELECT user_id, notice_id ' .
800           'FROM notice_inbox ' .
801           "WHERE user_id = $UT.id " .
802           'AND notice_id = ' . $this->id . ' )';
803         if ($enabled === 'transitional') {
804             $qry .= " AND $UT.inboxed = 1";
805         }
806         $result = $inbox->query($qry);
807     }
808
809     function saveReplies()
810     {
811         // Alternative reply format
812         $tname = false;
813         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
814             $tname = $match[1];
815         }
816         // extract all @messages
817         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
818
819         $names = array();
820
821         if ($cnt || $tname) {
822             // XXX: is there another way to make an array copy?
823             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
824         }
825
826         $sender = Profile::staticGet($this->profile_id);
827
828         $replied = array();
829
830         // store replied only for first @ (what user/notice what the reply directed,
831         // we assume first @ is it)
832
833         for ($i=0; $i<count($names); $i++) {
834             $nickname = $names[$i];
835             $recipient = common_relative_profile($sender, $nickname, $this->created);
836             if (!$recipient) {
837                 continue;
838             }
839             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
840                 $reply_for = $recipient;
841                 $recipient_notice = $reply_for->getCurrentNotice();
842                 if ($recipient_notice) {
843                     $orig = clone($this);
844                     $this->reply_to = $recipient_notice->id;
845                     $this->conversation = $recipient_notice->conversation;
846                     $this->update($orig);
847                 }
848             }
849             // Don't save replies from blocked profile to local user
850             $recipient_user = User::staticGet('id', $recipient->id);
851             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
852                 continue;
853             }
854             $reply = new Reply();
855             $reply->notice_id = $this->id;
856             $reply->profile_id = $recipient->id;
857             $id = $reply->insert();
858             if (!$id) {
859                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
860                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
861                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
862                 return;
863             } else {
864                 $replied[$recipient->id] = 1;
865             }
866         }
867
868         // Hash format replies, too
869         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
870         if ($cnt) {
871             foreach ($match[1] as $tag) {
872                 $tagged = Profile_tag::getTagged($sender->id, $tag);
873                 foreach ($tagged as $t) {
874                     if (!$replied[$t->id]) {
875                         // Don't save replies from blocked profile to local user
876                         $t_user = User::staticGet('id', $t->id);
877                         if ($t_user && $t_user->hasBlocked($sender)) {
878                             continue;
879                         }
880                         $reply = new Reply();
881                         $reply->notice_id = $this->id;
882                         $reply->profile_id = $t->id;
883                         $id = $reply->insert();
884                         if (!$id) {
885                             common_log_db_error($reply, 'INSERT', __FILE__);
886                             return;
887                         } else {
888                             $replied[$recipient->id] = 1;
889                         }
890                     }
891                 }
892             }
893         }
894
895         // If it's not a reply, make it the root of a new conversation
896
897         if (empty($this->conversation)) {
898             $orig = clone($this);
899             $this->conversation = $this->id;
900             $this->update($orig);
901         }
902
903         foreach (array_keys($replied) as $recipient) {
904             $user = User::staticGet('id', $recipient);
905             if ($user) {
906                 mail_notify_attn($user, $this);
907             }
908         }
909     }
910
911     function asAtomEntry($namespace=false, $source=false)
912     {
913         $profile = $this->getProfile();
914
915         $xs = new XMLStringer(true);
916
917         if ($namespace) {
918             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
919                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
920         } else {
921             $attrs = array();
922         }
923
924         $xs->elementStart('entry', $attrs);
925
926         if ($source) {
927             $xs->elementStart('source');
928             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
929             $xs->element('link', array('href' => $profile->profileurl));
930             $user = User::staticGet('id', $profile->id);
931             if (!empty($user)) {
932                 $atom_feed = common_local_url('api',
933                                               array('apiaction' => 'statuses',
934                                                     'method' => 'user_timeline',
935                                                     'argument' => $profile->nickname.'.atom'));
936                 $xs->element('link', array('rel' => 'self',
937                                            'type' => 'application/atom+xml',
938                                            'href' => $profile->profileurl));
939                 $xs->element('link', array('rel' => 'license',
940                                            'href' => common_config('license', 'url')));
941             }
942
943             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
944         }
945
946         $xs->elementStart('author');
947         $xs->element('name', null, $profile->nickname);
948         $xs->element('uri', null, $profile->profileurl);
949         $xs->elementEnd('author');
950
951         if ($source) {
952             $xs->elementEnd('source');
953         }
954
955         $xs->element('title', null, $this->content);
956         $xs->element('summary', null, $this->content);
957
958         $xs->element('link', array('rel' => 'alternate',
959                                    'href' => $this->bestUrl()));
960
961         $xs->element('id', null, $this->uri);
962
963         $xs->element('published', null, common_date_w3dtf($this->created));
964         $xs->element('updated', null, common_date_w3dtf($this->modified));
965
966         if ($this->reply_to) {
967             $reply_notice = Notice::staticGet('id', $this->reply_to);
968             if (!empty($reply_notice)) {
969                 $xs->element('link', array('rel' => 'related',
970                                            'href' => $reply_notice->bestUrl()));
971                 $xs->element('thr:in-reply-to',
972                              array('ref' => $reply_notice->uri,
973                                    'href' => $reply_notice->bestUrl()));
974             }
975         }
976
977         $xs->element('content', array('type' => 'html'), $this->rendered);
978
979         $tag = new Notice_tag();
980         $tag->notice_id = $this->id;
981         if ($tag->find()) {
982             while ($tag->fetch()) {
983                 $xs->element('category', array('term' => $tag->tag));
984             }
985         }
986         $tag->free();
987
988         $xs->elementEnd('entry');
989
990         return $xs->getString();
991     }
992
993     function bestUrl()
994     {
995         if (!empty($this->url)) {
996             return $this->url;
997         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
998             return $this->uri;
999         } else {
1000             return common_local_url('shownotice',
1001                                     array('notice' => $this->id));
1002         }
1003     }
1004
1005     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1006     {
1007         $cache = common_memcache();
1008
1009         if (empty($cache) ||
1010             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1011             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1012             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1013                                                                       $max_id, $since)));
1014         }
1015
1016         $idkey = common_cache_key($cachekey);
1017
1018         $idstr = $cache->get($idkey);
1019
1020         if (!empty($idstr)) {
1021             // Cache hit! Woohoo!
1022             $window = explode(',', $idstr);
1023             $ids = array_slice($window, $offset, $limit);
1024             return $ids;
1025         }
1026
1027         $laststr = $cache->get($idkey.';last');
1028
1029         if (!empty($laststr)) {
1030             $window = explode(',', $laststr);
1031             $last_id = $window[0];
1032             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1033                                                                           $last_id, 0, null, $tag)));
1034
1035             $new_window = array_merge($new_ids, $window);
1036
1037             $new_windowstr = implode(',', $new_window);
1038
1039             $result = $cache->set($idkey, $new_windowstr);
1040             $result = $cache->set($idkey . ';last', $new_windowstr);
1041
1042             $ids = array_slice($new_window, $offset, $limit);
1043
1044             return $ids;
1045         }
1046
1047         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1048                                                                      0, 0, null, $tag)));
1049
1050         $windowstr = implode(',', $window);
1051
1052         $result = $cache->set($idkey, $windowstr);
1053         $result = $cache->set($idkey . ';last', $windowstr);
1054
1055         $ids = array_slice($window, $offset, $limit);
1056
1057         return $ids;
1058     }
1059 }