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