PageRenderTime 59ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/Notice.php

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