]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch '0.9.x' of gitorious.org:statusnet/mainline into 0.9.x
[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)   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()   not_null
64     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // tinyint(1)
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
74     /* Static get */
75     function staticGet($k,$v=NULL) {
76         return Memcached_DataObject::staticGet('Notice',$k,$v);
77     }
78
79     /* the code above is auto generated do not remove the tag below */
80     ###END_AUTOCODE
81
82     /* Notice types */
83     const LOCAL_PUBLIC    =  1;
84     const REMOTE_OMB      =  0;
85     const LOCAL_NONPUBLIC = -1;
86     const GATEWAY         = -2;
87
88     function getProfile()
89     {
90         return Profile::staticGet('id', $this->profile_id);
91     }
92
93     function delete()
94     {
95         $this->blowCaches(true);
96         $this->blowFavesCache(true);
97         $this->blowSubsCache(true);
98
99         // For auditing purposes, save a record that the notice
100         // was deleted.
101
102         $deleted = new Deleted_notice();
103
104         $deleted->id         = $this->id;
105         $deleted->profile_id = $this->profile_id;
106         $deleted->uri        = $this->uri;
107         $deleted->created    = $this->created;
108         $deleted->deleted    = common_sql_now();
109
110         $this->query('BEGIN');
111
112         $deleted->insert();
113
114         //Null any notices that are replies to this notice
115         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
116         $related = array('Reply',
117                          'Fave',
118                          'Notice_tag',
119                          'Group_inbox',
120                          'Queue_item',
121                          'Notice_inbox');
122
123         foreach ($related as $cls) {
124             $inst = new $cls();
125             $inst->notice_id = $this->id;
126             $inst->delete();
127         }
128         $result = parent::delete();
129         $this->query('COMMIT');
130     }
131
132     function saveTags()
133     {
134         /* extract all #hastags */
135         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
136         if (!$count) {
137             return true;
138         }
139
140         //turn each into their canonical tag
141         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
142         $hashtags = array();
143         for($i=0; $i<count($match[1]); $i++) {
144             $hashtags[] = common_canonical_tag($match[1][$i]);
145         }
146
147         /* Add them to the database */
148         foreach(array_unique($hashtags) as $hashtag) {
149             /* elide characters we don't want in the tag */
150             $this->saveTag($hashtag);
151         }
152         return true;
153     }
154
155     function saveTag($hashtag)
156     {
157         $tag = new Notice_tag();
158         $tag->notice_id = $this->id;
159         $tag->tag = $hashtag;
160         $tag->created = $this->created;
161         $id = $tag->insert();
162
163         if (!$id) {
164             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
165                                               $last_error->message));
166             return;
167         }
168     }
169
170     static function saveNew($profile_id, $content, $source=null,
171                             $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null,
172                             $lat=null, $lon=null, $location_id=null, $location_ns=null) {
173
174         $profile = Profile::staticGet($profile_id);
175
176         $final = common_shorten_links($content);
177
178         if (Notice::contentTooLong($final)) {
179             throw new ClientException(_('Problem saving notice. Too long.'));
180         }
181
182         if (empty($profile)) {
183             throw new ClientException(_('Problem saving notice. Unknown user.'));
184         }
185
186         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
187             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
188             throw new ClientException(_('Too many notices too fast; take a breather '.
189                                         'and post again in a few minutes.'));
190         }
191
192         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
193             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
194             throw new ClientException(_('Too many duplicate messages too quickly;'.
195                                         ' take a breather and post again in a few minutes.'));
196         }
197
198         if (!$profile->hasRight(Right::NEWNOTICE)) {
199             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
200             throw new ClientException(_('You are banned from posting notices on this site.'));
201         }
202
203         $notice = new Notice();
204         $notice->profile_id = $profile_id;
205
206         $autosource = common_config('public', 'autosource');
207
208         # Sandboxed are non-false, but not 1, either
209
210         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
211             ($source && $autosource && in_array($source, $autosource))) {
212             $notice->is_local = Notice::LOCAL_NONPUBLIC;
213         } else {
214             $notice->is_local = $is_local;
215         }
216
217         if (!empty($created)) {
218             $notice->created = $created;
219         } else {
220             $notice->created = common_sql_now();
221         }
222
223         $notice->content = $final;
224         $notice->rendered = common_render_content($final, $notice);
225         $notice->source = $source;
226         $notice->uri = $uri;
227
228         $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
229
230         if (!empty($notice->reply_to)) {
231             $reply = Notice::staticGet('id', $notice->reply_to);
232             $notice->conversation = $reply->conversation;
233         }
234
235         if (!empty($lat) && !empty($lon)) {
236             $notice->lat = $lat;
237             $notice->lon = $lon;
238             $notice->location_id = $location_id;
239             $notice->location_ns = $location_ns;
240         } else if (!empty($location_ns) && !empty($location_id)) {
241             $location = Location::fromId($location_id, $location_ns);
242             if (!empty($location)) {
243                 $notice->lat = $location->lat;
244                 $notice->lon = $location->lon;
245                 $notice->location_id = $location_id;
246                 $notice->location_ns = $location_ns;
247             }
248         } else {
249             $notice->lat         = $profile->lat;
250             $notice->lon         = $profile->lon;
251             $notice->location_id = $profile->location_id;
252             $notice->location_ns = $profile->location_ns;
253         }
254
255         if (Event::handle('StartNoticeSave', array(&$notice))) {
256
257             // XXX: some of these functions write to the DB
258
259             $notice->query('BEGIN');
260
261             $id = $notice->insert();
262
263             if (!$id) {
264                 common_log_db_error($notice, 'INSERT', __FILE__);
265                 throw new ServerException(_('Problem saving notice.'));
266             }
267
268             // Update ID-dependent columns: URI, conversation
269
270             $orig = clone($notice);
271
272             $changed = false;
273
274             if (empty($uri)) {
275                 $notice->uri = common_notice_uri($notice);
276                 $changed = true;
277             }
278
279             // If it's not part of a conversation, it's
280             // the beginning of a new conversation.
281
282             if (empty($notice->conversation)) {
283                 $notice->conversation = $notice->id;
284                 $changed = true;
285             }
286
287             if ($changed) {
288                 if (!$notice->update($orig)) {
289                     common_log_db_error($notice, 'UPDATE', __FILE__);
290                     throw new ServerException(_('Problem saving notice.'));
291                 }
292             }
293
294             // XXX: do we need to change this for remote users?
295
296             $notice->saveTags();
297
298             $notice->addToInboxes();
299
300             $notice->saveUrls();
301
302             $notice->query('COMMIT');
303
304             Event::handle('EndNoticeSave', array($notice));
305         }
306
307         # Clear the cache for subscribed users, so they'll update at next request
308         # XXX: someone clever could prepend instead of clearing the cache
309
310         $notice->blowCaches();
311
312         return $notice;
313     }
314
315     /** save all urls in the notice to the db
316      *
317      * follow redirects and save all available file information
318      * (mimetype, date, size, oembed, etc.)
319      *
320      * @return void
321      */
322     function saveUrls() {
323         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
324     }
325
326     function saveUrl($data) {
327         list($url, $notice_id) = $data;
328         File::processNew($url, $notice_id);
329     }
330
331     static function checkDupes($profile_id, $content) {
332         $profile = Profile::staticGet($profile_id);
333         if (empty($profile)) {
334             return false;
335         }
336         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
337         if (!empty($notice)) {
338             $last = 0;
339             while ($notice->fetch()) {
340                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
341                     return true;
342                 } else if ($notice->content == $content) {
343                     return false;
344                 }
345             }
346         }
347         # If we get here, oldest item in cache window is not
348         # old enough for dupe limit; do direct check against DB
349         $notice = new Notice();
350         $notice->profile_id = $profile_id;
351         $notice->content = $content;
352         if (common_config('db','type') == 'pgsql')
353           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
354         else
355           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
356
357         $cnt = $notice->count();
358         return ($cnt == 0);
359     }
360
361     static function checkEditThrottle($profile_id) {
362         $profile = Profile::staticGet($profile_id);
363         if (empty($profile)) {
364             return false;
365         }
366         # Get the Nth notice
367         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
368         if ($notice && $notice->fetch()) {
369             # If the Nth notice was posted less than timespan seconds ago
370             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
371                 # Then we throttle
372                 return false;
373             }
374         }
375         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
376         return true;
377     }
378
379     function getUploadedAttachment() {
380         $post = clone $this;
381         $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"';
382         $post->query($query);
383         $post->fetch();
384         if (empty($post->up) || empty($post->i)) {
385             $ret = false;
386         } else {
387             $ret = array($post->up, $post->i);
388         }
389         $post->free();
390         return $ret;
391     }
392
393     function hasAttachments() {
394         $post = clone $this;
395         $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);
396         $post->query($query);
397         $post->fetch();
398         $n_attachments = intval($post->n_attachments);
399         $post->free();
400         return $n_attachments;
401     }
402
403     function attachments() {
404         // XXX: cache this
405         $att = array();
406         $f2p = new File_to_post;
407         $f2p->post_id = $this->id;
408         if ($f2p->find()) {
409             while ($f2p->fetch()) {
410                 $f = File::staticGet($f2p->file_id);
411                 $att[] = clone($f);
412             }
413         }
414         return $att;
415     }
416
417     function blowCaches($blowLast=false)
418     {
419         $this->blowSubsCache($blowLast);
420         $this->blowNoticeCache($blowLast);
421         $this->blowRepliesCache($blowLast);
422         $this->blowPublicCache($blowLast);
423         $this->blowTagCache($blowLast);
424         $this->blowGroupCache($blowLast);
425         $this->blowConversationCache($blowLast);
426         $profile = Profile::staticGet($this->profile_id);
427         $profile->blowNoticeCount();
428     }
429
430     function blowConversationCache($blowLast=false)
431     {
432         $cache = common_memcache();
433         if ($cache) {
434             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
435             $cache->delete($ck);
436             if ($blowLast) {
437                 $cache->delete($ck.';last');
438             }
439         }
440     }
441
442     function blowGroupCache($blowLast=false)
443     {
444         $cache = common_memcache();
445         if ($cache) {
446             $group_inbox = new Group_inbox();
447             $group_inbox->notice_id = $this->id;
448             if ($group_inbox->find()) {
449                 while ($group_inbox->fetch()) {
450                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
451                     if ($blowLast) {
452                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
453                     }
454                     $member = new Group_member();
455                     $member->group_id = $group_inbox->group_id;
456                     if ($member->find()) {
457                         while ($member->fetch()) {
458                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
459                             if ($blowLast) {
460                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
461                             }
462                         }
463                     }
464                 }
465             }
466             $group_inbox->free();
467             unset($group_inbox);
468         }
469     }
470
471     function blowTagCache($blowLast=false)
472     {
473         $cache = common_memcache();
474         if ($cache) {
475             $tag = new Notice_tag();
476             $tag->notice_id = $this->id;
477             if ($tag->find()) {
478                 while ($tag->fetch()) {
479                     $tag->blowCache($blowLast);
480                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
481
482                     $cache->delete($ck);
483                     if ($blowLast) {
484                         $cache->delete($ck . ';last');
485                     }
486                 }
487             }
488             $tag->free();
489             unset($tag);
490         }
491     }
492
493     function blowSubsCache($blowLast=false)
494     {
495         $cache = common_memcache();
496         if ($cache) {
497             $user = new User();
498
499             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
500             $user->query('SELECT id ' .
501
502                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
503                          'WHERE subscription.subscribed = ' . $this->profile_id);
504
505             while ($user->fetch()) {
506                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
507                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
508                 if ($blowLast) {
509                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
510                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
511                 }
512             }
513             $user->free();
514             unset($user);
515         }
516     }
517
518     function blowNoticeCache($blowLast=false)
519     {
520         if ($this->is_local) {
521             $cache = common_memcache();
522             if (!empty($cache)) {
523                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
524                 if ($blowLast) {
525                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
526                 }
527             }
528         }
529     }
530
531     function blowRepliesCache($blowLast=false)
532     {
533         $cache = common_memcache();
534         if ($cache) {
535             $reply = new Reply();
536             $reply->notice_id = $this->id;
537             if ($reply->find()) {
538                 while ($reply->fetch()) {
539                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
540                     if ($blowLast) {
541                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
542                     }
543                 }
544             }
545             $reply->free();
546             unset($reply);
547         }
548     }
549
550     function blowPublicCache($blowLast=false)
551     {
552         if ($this->is_local == Notice::LOCAL_PUBLIC) {
553             $cache = common_memcache();
554             if ($cache) {
555                 $cache->delete(common_cache_key('public'));
556                 if ($blowLast) {
557                     $cache->delete(common_cache_key('public').';last');
558                 }
559             }
560         }
561     }
562
563     function blowFavesCache($blowLast=false)
564     {
565         $cache = common_memcache();
566         if ($cache) {
567             $fave = new Fave();
568             $fave->notice_id = $this->id;
569             if ($fave->find()) {
570                 while ($fave->fetch()) {
571                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
572                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
573                     if ($blowLast) {
574                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
575                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
576                     }
577                 }
578             }
579             $fave->free();
580             unset($fave);
581         }
582     }
583
584     # XXX: too many args; we need to move to named params or even a separate
585     # class for notice streams
586
587     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
588
589         if (common_config('memcached', 'enabled')) {
590
591             # Skip the cache if this is a since, since_id or max_id qry
592             if ($since_id > 0 || $max_id > 0 || $since) {
593                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
594             } else {
595                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
596             }
597         }
598
599         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
600     }
601
602     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
603
604         $needAnd = false;
605         $needWhere = true;
606
607         if (preg_match('/\bWHERE\b/i', $qry)) {
608             $needWhere = false;
609             $needAnd = true;
610         }
611
612         if ($since_id > 0) {
613
614             if ($needWhere) {
615                 $qry .= ' WHERE ';
616                 $needWhere = false;
617             } else {
618                 $qry .= ' AND ';
619             }
620
621             $qry .= ' notice.id > ' . $since_id;
622         }
623
624         if ($max_id > 0) {
625
626             if ($needWhere) {
627                 $qry .= ' WHERE ';
628                 $needWhere = false;
629             } else {
630                 $qry .= ' AND ';
631             }
632
633             $qry .= ' notice.id <= ' . $max_id;
634         }
635
636         if ($since) {
637
638             if ($needWhere) {
639                 $qry .= ' WHERE ';
640                 $needWhere = false;
641             } else {
642                 $qry .= ' AND ';
643             }
644
645             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
646         }
647
648         # Allow ORDER override
649
650         if ($order) {
651             $qry .= $order;
652         } else {
653             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
654         }
655
656         if (common_config('db','type') == 'pgsql') {
657             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
658         } else {
659             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
660         }
661
662         $notice = new Notice();
663
664         $notice->query($qry);
665
666         return $notice;
667     }
668
669     # XXX: this is pretty long and should probably be broken up into
670     # some helper functions
671
672     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
673
674         # If outside our cache window, just go to the DB
675
676         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
677             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
678         }
679
680         # Get the cache; if we can't, just go to the DB
681
682         $cache = common_memcache();
683
684         if (empty($cache)) {
685             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
686         }
687
688         # Get the notices out of the cache
689
690         $notices = $cache->get(common_cache_key($cachekey));
691
692         # On a cache hit, return a DB-object-like wrapper
693
694         if ($notices !== false) {
695             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
696             return $wrapper;
697         }
698
699         # If the cache was invalidated because of new data being
700         # added, we can try and just get the new stuff. We keep an additional
701         # copy of the data at the key + ';last'
702
703         # No cache hit. Try to get the *last* cached version
704
705         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
706
707         if ($last_notices) {
708
709             # Reverse-chron order, so last ID is last.
710
711             $last_id = $last_notices[0]->id;
712
713             # XXX: this assumes monotonically increasing IDs; a fair
714             # bet with our DB.
715
716             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
717                                                   $last_id, null, $order, null);
718
719             if ($new_notice) {
720                 $new_notices = array();
721                 while ($new_notice->fetch()) {
722                     $new_notices[] = clone($new_notice);
723                 }
724                 $new_notice->free();
725                 $notices = array_slice(array_merge($new_notices, $last_notices),
726                                        0, NOTICE_CACHE_WINDOW);
727
728                 # Store the array in the cache for next time
729
730                 $result = $cache->set(common_cache_key($cachekey), $notices);
731                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
732
733                 # return a wrapper of the array for use now
734
735                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
736             }
737         }
738
739         # Otherwise, get the full cache window out of the DB
740
741         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
742
743         # If there are no hits, just return the value
744
745         if (empty($notice)) {
746             return $notice;
747         }
748
749         # Pack results into an array
750
751         $notices = array();
752
753         while ($notice->fetch()) {
754             $notices[] = clone($notice);
755         }
756
757         $notice->free();
758
759         # Store the array in the cache for next time
760
761         $result = $cache->set(common_cache_key($cachekey), $notices);
762         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
763
764         # return a wrapper of the array for use now
765
766         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
767
768         return $wrapper;
769     }
770
771     function getStreamByIds($ids)
772     {
773         $cache = common_memcache();
774
775         if (!empty($cache)) {
776             $notices = array();
777             foreach ($ids as $id) {
778                 $n = Notice::staticGet('id', $id);
779                 if (!empty($n)) {
780                     $notices[] = $n;
781                 }
782             }
783             return new ArrayWrapper($notices);
784         } else {
785             $notice = new Notice();
786             if (empty($ids)) {
787                 //if no IDs requested, just return the notice object
788                 return $notice;
789             }
790             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
791             $notice->orderBy('id DESC');
792
793             $notice->find();
794             return $notice;
795         }
796     }
797
798     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
799     {
800         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
801                               array(),
802                               'public',
803                               $offset, $limit, $since_id, $max_id, $since);
804
805         return Notice::getStreamByIds($ids);
806     }
807
808     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
809     {
810         $notice = new Notice();
811
812         $notice->selectAdd(); // clears it
813         $notice->selectAdd('id');
814
815         $notice->orderBy('id DESC');
816
817         if (!is_null($offset)) {
818             $notice->limit($offset, $limit);
819         }
820
821         if (common_config('public', 'localonly')) {
822             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
823         } else {
824             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
825             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
826             $notice->whereAdd('is_local !='. Notice::GATEWAY);
827         }
828
829         if ($since_id != 0) {
830             $notice->whereAdd('id > ' . $since_id);
831         }
832
833         if ($max_id != 0) {
834             $notice->whereAdd('id <= ' . $max_id);
835         }
836
837         if (!is_null($since)) {
838             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
839         }
840
841         $ids = array();
842
843         if ($notice->find()) {
844             while ($notice->fetch()) {
845                 $ids[] = $notice->id;
846             }
847         }
848
849         $notice->free();
850         $notice = NULL;
851
852         return $ids;
853     }
854
855     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
856     {
857         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
858                               array($id),
859                               'notice:conversation_ids:'.$id,
860                               $offset, $limit, $since_id, $max_id, $since);
861
862         return Notice::getStreamByIds($ids);
863     }
864
865     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
866     {
867         $notice = new Notice();
868
869         $notice->selectAdd(); // clears it
870         $notice->selectAdd('id');
871
872         $notice->conversation = $id;
873
874         $notice->orderBy('id DESC');
875
876         if (!is_null($offset)) {
877             $notice->limit($offset, $limit);
878         }
879
880         if ($since_id != 0) {
881             $notice->whereAdd('id > ' . $since_id);
882         }
883
884         if ($max_id != 0) {
885             $notice->whereAdd('id <= ' . $max_id);
886         }
887
888         if (!is_null($since)) {
889             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
890         }
891
892         $ids = array();
893
894         if ($notice->find()) {
895             while ($notice->fetch()) {
896                 $ids[] = $notice->id;
897             }
898         }
899
900         $notice->free();
901         $notice = NULL;
902
903         return $ids;
904     }
905
906     function addToInboxes()
907     {
908         // XXX: loads constants
909
910         $inbox = new Notice_inbox();
911
912         $users = $this->getSubscribedUsers();
913
914         // FIXME: kind of ignoring 'transitional'...
915         // we'll probably stop supporting inboxless mode
916         // in 0.9.x
917
918         $ni = array();
919
920         foreach ($users as $id) {
921             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
922         }
923
924         $groups = $this->saveGroups();
925         $profile = $this->getProfile();
926
927         foreach ($groups as $group) {
928             $users = $group->getUserMembers();
929             foreach ($users as $id) {
930                 if (!array_key_exists($id, $ni)) {
931                     $user = User::staticGet('id', $id);
932                     if (!$user->hasBlocked($profile)) {
933                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
934                     }
935                 }
936             }
937         }
938
939         $recipients = $this->saveReplies();
940
941         foreach ($recipients as $recipient) {
942
943             if (!array_key_exists($recipient, $ni)) {
944                 $recipientUser = User::staticGet('id', $recipient);
945                 if (!empty($recipientUser)) {
946                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
947                 }
948             }
949         }
950
951         $cnt = 0;
952
953         $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
954         $qry = $qryhdr;
955
956         foreach ($ni as $id => $source) {
957             if ($cnt > 0) {
958                 $qry .= ', ';
959             }
960             $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
961             $cnt++;
962             if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
963                 // FIXME: Causes lag in replicated servers
964                 // Notice_inbox::gc($id);
965             }
966             if ($cnt >= MAX_BOXCARS) {
967                 $inbox = new Notice_inbox();
968                 $result = $inbox->query($qry);
969                 if (PEAR::isError($result)) {
970                     common_log_db_error($inbox, $qry);
971                 }
972                 $qry = $qryhdr;
973                 $cnt = 0;
974             }
975         }
976
977         if ($cnt > 0) {
978             $inbox = new Notice_inbox();
979             $result = $inbox->query($qry);
980             if (PEAR::isError($result)) {
981                 common_log_db_error($inbox, $qry);
982             }
983         }
984
985         return;
986     }
987
988     function getSubscribedUsers()
989     {
990         $user = new User();
991
992         if(common_config('db','quote_identifiers'))
993           $user_table = '"user"';
994         else $user_table = 'user';
995
996         $qry =
997           'SELECT id ' .
998           'FROM '. $user_table .' JOIN subscription '.
999           'ON '. $user_table .'.id = subscription.subscriber ' .
1000           'WHERE subscription.subscribed = %d ';
1001
1002         $user->query(sprintf($qry, $this->profile_id));
1003
1004         $ids = array();
1005
1006         while ($user->fetch()) {
1007             $ids[] = $user->id;
1008         }
1009
1010         $user->free();
1011
1012         return $ids;
1013     }
1014
1015     function saveGroups()
1016     {
1017         $groups = array();
1018
1019         /* extract all !group */
1020         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
1021                                 strtolower($this->content),
1022                                 $match);
1023         if (!$count) {
1024             return $groups;
1025         }
1026
1027         $profile = $this->getProfile();
1028
1029         /* Add them to the database */
1030
1031         foreach (array_unique($match[1]) as $nickname) {
1032             /* XXX: remote groups. */
1033             $group = User_group::getForNickname($nickname);
1034
1035             if (empty($group)) {
1036                 continue;
1037             }
1038
1039             // we automatically add a tag for every group name, too
1040
1041             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1042                                              'notice_id' => $this->id));
1043
1044             if (is_null($tag)) {
1045                 $this->saveTag($nickname);
1046             }
1047
1048             if ($profile->isMember($group)) {
1049
1050                 $result = $this->addToGroupInbox($group);
1051
1052                 if (!$result) {
1053                     common_log_db_error($gi, 'INSERT', __FILE__);
1054                 }
1055
1056                 $groups[] = clone($group);
1057             }
1058         }
1059
1060         return $groups;
1061     }
1062
1063     function addToGroupInbox($group)
1064     {
1065         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1066                                          'notice_id' => $this->id));
1067
1068         if (empty($gi)) {
1069
1070             $gi = new Group_inbox();
1071
1072             $gi->group_id  = $group->id;
1073             $gi->notice_id = $this->id;
1074             $gi->created   = $this->created;
1075
1076             return $gi->insert();
1077         }
1078
1079         return true;
1080     }
1081
1082     function saveReplies()
1083     {
1084         // Alternative reply format
1085         $tname = false;
1086         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1087             $tname = $match[1];
1088         }
1089         // extract all @messages
1090         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1091
1092         $names = array();
1093
1094         if ($cnt || $tname) {
1095             // XXX: is there another way to make an array copy?
1096             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1097         }
1098
1099         $sender = Profile::staticGet($this->profile_id);
1100
1101         $replied = array();
1102
1103         // store replied only for first @ (what user/notice what the reply directed,
1104         // we assume first @ is it)
1105
1106         for ($i=0; $i<count($names); $i++) {
1107             $nickname = $names[$i];
1108             $recipient = common_relative_profile($sender, $nickname, $this->created);
1109             if (empty($recipient)) {
1110                 continue;
1111             }
1112             // Don't save replies from blocked profile to local user
1113             $recipient_user = User::staticGet('id', $recipient->id);
1114             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1115                 continue;
1116             }
1117             $reply = new Reply();
1118             $reply->notice_id = $this->id;
1119             $reply->profile_id = $recipient->id;
1120             $id = $reply->insert();
1121             if (!$id) {
1122                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1123                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1124                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1125                 return array();
1126             } else {
1127                 $replied[$recipient->id] = 1;
1128             }
1129         }
1130
1131         // Hash format replies, too
1132         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1133         if ($cnt) {
1134             foreach ($match[1] as $tag) {
1135                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1136                 foreach ($tagged as $t) {
1137                     if (!$replied[$t->id]) {
1138                         // Don't save replies from blocked profile to local user
1139                         $t_user = User::staticGet('id', $t->id);
1140                         if ($t_user && $t_user->hasBlocked($sender)) {
1141                             continue;
1142                         }
1143                         $reply = new Reply();
1144                         $reply->notice_id = $this->id;
1145                         $reply->profile_id = $t->id;
1146                         $id = $reply->insert();
1147                         if (!$id) {
1148                             common_log_db_error($reply, 'INSERT', __FILE__);
1149                             return array();
1150                         } else {
1151                             $replied[$recipient->id] = 1;
1152                         }
1153                     }
1154                 }
1155             }
1156         }
1157
1158         $recipientIds = array_keys($replied);
1159
1160         foreach ($recipientIds as $recipient) {
1161             $user = User::staticGet('id', $recipient);
1162             if ($user) {
1163                 mail_notify_attn($user, $this);
1164             }
1165         }
1166
1167         return $recipientIds;
1168     }
1169
1170     function asAtomEntry($namespace=false, $source=false)
1171     {
1172         $profile = $this->getProfile();
1173
1174         $xs = new XMLStringer(true);
1175
1176         if ($namespace) {
1177             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1178                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1179         } else {
1180             $attrs = array();
1181         }
1182
1183         $xs->elementStart('entry', $attrs);
1184
1185         if ($source) {
1186             $xs->elementStart('source');
1187             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1188             $xs->element('link', array('href' => $profile->profileurl));
1189             $user = User::staticGet('id', $profile->id);
1190             if (!empty($user)) {
1191                 $atom_feed = common_local_url('ApiTimelineUser',
1192                                               array('format' => 'atom',
1193                                                     'id' => $profile->nickname));
1194                 $xs->element('link', array('rel' => 'self',
1195                                            'type' => 'application/atom+xml',
1196                                            'href' => $profile->profileurl));
1197                 $xs->element('link', array('rel' => 'license',
1198                                            'href' => common_config('license', 'url')));
1199             }
1200
1201             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1202         }
1203
1204         $xs->elementStart('author');
1205         $xs->element('name', null, $profile->nickname);
1206         $xs->element('uri', null, $profile->profileurl);
1207         $xs->elementEnd('author');
1208
1209         if ($source) {
1210             $xs->elementEnd('source');
1211         }
1212
1213         $xs->element('title', null, $this->content);
1214         $xs->element('summary', null, $this->content);
1215
1216         $xs->element('link', array('rel' => 'alternate',
1217                                    'href' => $this->bestUrl()));
1218
1219         $xs->element('id', null, $this->uri);
1220
1221         $xs->element('published', null, common_date_w3dtf($this->created));
1222         $xs->element('updated', null, common_date_w3dtf($this->modified));
1223
1224         if ($this->reply_to) {
1225             $reply_notice = Notice::staticGet('id', $this->reply_to);
1226             if (!empty($reply_notice)) {
1227                 $xs->element('link', array('rel' => 'related',
1228                                            'href' => $reply_notice->bestUrl()));
1229                 $xs->element('thr:in-reply-to',
1230                              array('ref' => $reply_notice->uri,
1231                                    'href' => $reply_notice->bestUrl()));
1232             }
1233         }
1234
1235         $xs->element('content', array('type' => 'html'), $this->rendered);
1236
1237         $tag = new Notice_tag();
1238         $tag->notice_id = $this->id;
1239         if ($tag->find()) {
1240             while ($tag->fetch()) {
1241                 $xs->element('category', array('term' => $tag->tag));
1242             }
1243         }
1244         $tag->free();
1245
1246         # Enclosures
1247         $attachments = $this->attachments();
1248         if($attachments){
1249             foreach($attachments as $attachment){
1250                 $enclosure=$attachment->getEnclosure();
1251                 if ($enclosure) {
1252                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1253                     if($enclosure->title){
1254                         $attributes['title']=$enclosure->title;
1255                     }
1256                     $xs->element('link', $attributes, null);
1257                 }
1258             }
1259         }
1260
1261         if (!empty($this->lat) && !empty($this->lon)) {
1262             $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1263             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1264             $xs->elementEnd('geo');
1265         }
1266
1267         $xs->elementEnd('entry');
1268
1269         return $xs->getString();
1270     }
1271
1272     function bestUrl()
1273     {
1274         if (!empty($this->url)) {
1275             return $this->url;
1276         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1277             return $this->uri;
1278         } else {
1279             return common_local_url('shownotice',
1280                                     array('notice' => $this->id));
1281         }
1282     }
1283
1284     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1285     {
1286         $cache = common_memcache();
1287
1288         if (empty($cache) ||
1289             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1290             is_null($limit) ||
1291             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1292             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1293                                                                       $max_id, $since)));
1294         }
1295
1296         $idkey = common_cache_key($cachekey);
1297
1298         $idstr = $cache->get($idkey);
1299
1300         if (!empty($idstr)) {
1301             // Cache hit! Woohoo!
1302             $window = explode(',', $idstr);
1303             $ids = array_slice($window, $offset, $limit);
1304             return $ids;
1305         }
1306
1307         $laststr = $cache->get($idkey.';last');
1308
1309         if (!empty($laststr)) {
1310             $window = explode(',', $laststr);
1311             $last_id = $window[0];
1312             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1313                                                                           $last_id, 0, null)));
1314
1315             $new_window = array_merge($new_ids, $window);
1316
1317             $new_windowstr = implode(',', $new_window);
1318
1319             $result = $cache->set($idkey, $new_windowstr);
1320             $result = $cache->set($idkey . ';last', $new_windowstr);
1321
1322             $ids = array_slice($new_window, $offset, $limit);
1323
1324             return $ids;
1325         }
1326
1327         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1328                                                                      0, 0, null)));
1329
1330         $windowstr = implode(',', $window);
1331
1332         $result = $cache->set($idkey, $windowstr);
1333         $result = $cache->set($idkey . ';last', $windowstr);
1334
1335         $ids = array_slice($window, $offset, $limit);
1336
1337         return $ids;
1338     }
1339
1340     /**
1341      * Determine which notice, if any, a new notice is in reply to.
1342      *
1343      * For conversation tracking, we try to see where this notice fits
1344      * in the tree. Rough algorithm is:
1345      *
1346      * if (reply_to is set and valid) {
1347      *     return reply_to;
1348      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1349      *     return ID of last notice by initial @name in content;
1350      * }
1351      *
1352      * Note that all @nickname instances will still be used to save "reply" records,
1353      * so the notice shows up in the mentioned users' "replies" tab.
1354      *
1355      * @param integer $reply_to   ID passed in by Web or API
1356      * @param integer $profile_id ID of author
1357      * @param string  $source     Source tag, like 'web' or 'gwibber'
1358      * @param string  $content    Final notice content
1359      *
1360      * @return integer ID of replied-to notice, or null for not a reply.
1361      */
1362
1363     static function getReplyTo($reply_to, $profile_id, $source, $content)
1364     {
1365         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1366
1367         // If $reply_to is specified, we check that it exists, and then
1368         // return it if it does
1369
1370         if (!empty($reply_to)) {
1371             $reply_notice = Notice::staticGet('id', $reply_to);
1372             if (!empty($reply_notice)) {
1373                 return $reply_to;
1374             }
1375         }
1376
1377         // If it's not a "low bandwidth" source (one where you can't set
1378         // a reply_to argument), we return. This is mostly web and API
1379         // clients.
1380
1381         if (!in_array($source, $lb)) {
1382             return null;
1383         }
1384
1385         // Is there an initial @ or T?
1386
1387         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1388             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1389             $nickname = common_canonical_nickname($match[1]);
1390         } else {
1391             return null;
1392         }
1393
1394         // Figure out who that is.
1395
1396         $sender = Profile::staticGet('id', $profile_id);
1397         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1398
1399         if (empty($recipient)) {
1400             return null;
1401         }
1402
1403         // Get their last notice
1404
1405         $last = $recipient->getCurrentNotice();
1406
1407         if (!empty($last)) {
1408             return $last->id;
1409         }
1410     }
1411
1412     static function maxContent()
1413     {
1414         $contentlimit = common_config('notice', 'contentlimit');
1415         // null => use global limit (distinct from 0!)
1416         if (is_null($contentlimit)) {
1417             $contentlimit = common_config('site', 'textlimit');
1418         }
1419         return $contentlimit;
1420     }
1421
1422     static function contentTooLong($content)
1423     {
1424         $contentlimit = self::maxContent();
1425         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1426     }
1427
1428     function getLocation()
1429     {
1430         $location = null;
1431
1432         if (!empty($this->location_id) && !empty($this->location_ns)) {
1433             $location = Location::fromId($this->location_id, $this->location_ns);
1434         }
1435
1436         if (is_null($location)) { // no ID, or Location::fromId() failed
1437             if (!empty($this->lat) && !empty($this->lon)) {
1438                 $location = Location::fromLatLon($this->lat, $this->lon);
1439             }
1440         }
1441
1442         return $location;
1443     }
1444 }