Notice.php 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008-2011 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. * @author Mikael Nordfeldth <mmn@hethane.se>
  33. * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
  34. * @license GNU Affero General Public License http://www.gnu.org/licenses/
  35. */
  36. if (!defined('GNUSOCIAL')) { exit(1); }
  37. /**
  38. * Table Definition for notice
  39. */
  40. /* We keep 200 notices, the max number of notices available per API request,
  41. * in the memcached cache. */
  42. define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
  43. define('MAX_BOXCARS', 128);
  44. class Notice extends Managed_DataObject
  45. {
  46. ###START_AUTOCODE
  47. /* the code below is auto generated do not remove the above tag */
  48. public $__table = 'notice'; // table name
  49. public $id; // int(4) primary_key not_null
  50. public $profile_id; // int(4) multiple_key not_null
  51. public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  52. public $content; // text
  53. public $rendered; // text
  54. public $url; // varchar(191) not 255 because utf8mb4 takes more space
  55. public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
  56. public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
  57. public $reply_to; // int(4)
  58. public $is_local; // int(4)
  59. public $source; // varchar(32)
  60. public $conversation; // int(4)
  61. public $repeat_of; // int(4)
  62. public $verb; // varchar(191) not 255 because utf8mb4 takes more space
  63. public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
  64. public $scope; // int(4)
  65. /* the code above is auto generated do not remove the tag below */
  66. ###END_AUTOCODE
  67. public static function schemaDef()
  68. {
  69. $def = array(
  70. 'fields' => array(
  71. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
  72. 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
  73. 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
  74. 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
  75. 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
  76. 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
  77. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  78. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  79. 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
  80. 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
  81. 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
  82. 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
  83. 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
  84. 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => null),
  85. 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
  86. 'scope' => array('type' => 'int',
  87. 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
  88. ),
  89. 'primary key' => array('id'),
  90. 'unique keys' => array(
  91. 'notice_uri_key' => array('uri'),
  92. ),
  93. 'foreign keys' => array(
  94. 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
  95. 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
  96. 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
  97. 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
  98. ),
  99. 'indexes' => array(
  100. 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
  101. 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
  102. 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
  103. 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
  104. 'notice_verb_idx' => array('verb'),
  105. 'notice_replyto_idx' => array('reply_to')
  106. )
  107. );
  108. if (common_config('search', 'type') == 'fulltext') {
  109. $def['fulltext indexes'] = array('content' => array('content'));
  110. }
  111. return $def;
  112. }
  113. /* Notice types */
  114. const LOCAL_PUBLIC = 1;
  115. const REMOTE = 0;
  116. const LOCAL_NONPUBLIC = -1;
  117. const GATEWAY = -2;
  118. const PUBLIC_SCOPE = 0; // Useful fake constant
  119. const SITE_SCOPE = 1;
  120. const ADDRESSEE_SCOPE = 2;
  121. const GROUP_SCOPE = 4;
  122. const FOLLOWER_SCOPE = 8;
  123. protected $_profile = array();
  124. /**
  125. * Will always return a profile, if anything fails it will
  126. * (through _setProfile) throw a NoProfileException.
  127. */
  128. public function getProfile()
  129. {
  130. if (!isset($this->_profile[$this->profile_id])) {
  131. // We could've sent getKV directly to _setProfile, but occasionally we get
  132. // a "false" (instead of null), likely because it indicates a cache miss.
  133. $profile = Profile::getKV('id', $this->profile_id);
  134. $this->_setProfile($profile instanceof Profile ? $profile : null);
  135. }
  136. return $this->_profile[$this->profile_id];
  137. }
  138. public function _setProfile(Profile $profile=null)
  139. {
  140. if (!$profile instanceof Profile) {
  141. throw new NoProfileException($this->profile_id);
  142. }
  143. $this->_profile[$this->profile_id] = $profile;
  144. }
  145. public function deleteAs(Profile $actor, $delete_event=true)
  146. {
  147. if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
  148. throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
  149. }
  150. if (Event::handle('NoticeDeleteRelated', array($this))) {
  151. // Clear related records
  152. $this->clearReplies();
  153. $this->clearLocation();
  154. $this->clearRepeats();
  155. $this->clearTags();
  156. $this->clearGroupInboxes();
  157. $this->clearFiles();
  158. $this->clearAttentions();
  159. // NOTE: we don't clear queue items
  160. }
  161. $result = null;
  162. if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
  163. // If $delete_event is true, we run the event. If the Event then
  164. // returns false it is assumed everything was handled properly
  165. // and the notice was deleted.
  166. $result = $this->delete();
  167. }
  168. return $result;
  169. }
  170. public function delete($useWhere=false)
  171. {
  172. $result = parent::delete($useWhere);
  173. $this->blowOnDelete();
  174. return $result;
  175. }
  176. public function getUri()
  177. {
  178. return $this->uri;
  179. }
  180. /*
  181. * Get a Notice object by URI. Will call external plugins for help
  182. * using the event StartGetNoticeFromURI.
  183. *
  184. * @param string $uri A unique identifier for a resource (notice in this case)
  185. */
  186. static function fromUri($uri)
  187. {
  188. $notice = null;
  189. if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
  190. $notice = Notice::getKV('uri', $uri);
  191. Event::handle('EndGetNoticeFromUri', array($uri, $notice));
  192. }
  193. if (!$notice instanceof Notice) {
  194. throw new UnknownUriException($uri);
  195. }
  196. return $notice;
  197. }
  198. /*
  199. * @param $root boolean If true, link to just the conversation root.
  200. *
  201. * @return URL to conversation
  202. */
  203. public function getConversationUrl($anchor=true)
  204. {
  205. return Conversation::getUrlFromNotice($this, $anchor);
  206. }
  207. /*
  208. * Get the local representation URL of this notice.
  209. */
  210. public function getLocalUrl()
  211. {
  212. return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
  213. }
  214. public function getTitle()
  215. {
  216. $title = null;
  217. if (Event::handle('GetNoticeTitle', array($this, &$title))) {
  218. // TRANS: Title of a notice posted without a title value.
  219. // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
  220. $title = sprintf(_('%1$s\'s status on %2$s'),
  221. $this->getProfile()->getFancyName(),
  222. common_exact_date($this->created));
  223. }
  224. return $title;
  225. }
  226. public function getContent()
  227. {
  228. return $this->content;
  229. }
  230. public function getRendered()
  231. {
  232. // we test $this->id because if it's not inserted yet, we can't update the field
  233. if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
  234. // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
  235. common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
  236. $orig = clone($this);
  237. $this->rendered = common_render_content($this->getContent(),
  238. $this->getProfile(),
  239. $this->hasParent() ? $this->getParent() : null);
  240. $this->update($orig);
  241. }
  242. return $this->rendered;
  243. }
  244. public function getCreated()
  245. {
  246. return $this->created;
  247. }
  248. public function getVerb($make_relative=false)
  249. {
  250. return ActivityUtils::resolveUri($this->verb, $make_relative);
  251. }
  252. public function isVerb(array $verbs)
  253. {
  254. return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
  255. }
  256. /*
  257. * Get the original representation URL of this notice.
  258. *
  259. * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
  260. */
  261. public function getUrl($fallback=false)
  262. {
  263. // The risk is we start having empty urls and non-http uris...
  264. // and we can't really handle any other protocol right now.
  265. switch (true) {
  266. case $this->isLocal():
  267. return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
  268. case common_valid_http_url($this->url): // should we allow non-http/https URLs?
  269. return $this->url;
  270. case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
  271. return $this->uri;
  272. case $fallback:
  273. // let's generate a valid link to our locally available notice on demand
  274. return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
  275. default:
  276. common_debug('No URL available for notice: id='.$this->getID());
  277. throw new InvalidUrlException($this->url);
  278. }
  279. }
  280. public function getObjectType($canonical=false) {
  281. if (is_null($this->object_type) || $this->object_type==='') {
  282. throw new NoObjectTypeException($this);
  283. }
  284. return ActivityUtils::resolveUri($this->object_type, $canonical);
  285. }
  286. public function isObjectType(array $types)
  287. {
  288. try {
  289. return ActivityUtils::compareTypes($this->getObjectType(), $types);
  290. } catch (NoObjectTypeException $e) {
  291. return false;
  292. }
  293. }
  294. public static function getByUri($uri)
  295. {
  296. $notice = new Notice();
  297. $notice->uri = $uri;
  298. if (!$notice->find(true)) {
  299. throw new NoResultException($notice);
  300. }
  301. return $notice;
  302. }
  303. /**
  304. * Extract #hashtags from this notice's content and save them to the database.
  305. */
  306. function saveTags()
  307. {
  308. /* extract all #hastags */
  309. $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
  310. if (!$count) {
  311. return true;
  312. }
  313. /* Add them to the database */
  314. return $this->saveKnownTags($match[1]);
  315. }
  316. /**
  317. * Record the given set of hash tags in the db for this notice.
  318. * Given tag strings will be normalized and checked for dupes.
  319. */
  320. function saveKnownTags($hashtags)
  321. {
  322. //turn each into their canonical tag
  323. //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
  324. for($i=0; $i<count($hashtags); $i++) {
  325. /* elide characters we don't want in the tag */
  326. $hashtags[$i] = common_canonical_tag($hashtags[$i]);
  327. }
  328. foreach(array_unique($hashtags) as $hashtag) {
  329. $this->saveTag($hashtag);
  330. self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
  331. }
  332. return true;
  333. }
  334. /**
  335. * Record a single hash tag as associated with this notice.
  336. * Tag format and uniqueness must be validated by caller.
  337. */
  338. function saveTag($hashtag)
  339. {
  340. $tag = new Notice_tag();
  341. $tag->notice_id = $this->id;
  342. $tag->tag = $hashtag;
  343. $tag->created = $this->created;
  344. $id = $tag->insert();
  345. if (!$id) {
  346. // TRANS: Server exception. %s are the error details.
  347. throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
  348. $last_error->message));
  349. return;
  350. }
  351. // if it's saved, blow its cache
  352. $tag->blowCache(false);
  353. }
  354. /**
  355. * Save a new notice and push it out to subscribers' inboxes.
  356. * Poster's permissions are checked before sending.
  357. *
  358. * @param int $profile_id Profile ID of the poster
  359. * @param string $content source message text; links may be shortened
  360. * per current user's preference
  361. * @param string $source source key ('web', 'api', etc)
  362. * @param array $options Associative array of optional properties:
  363. * string 'created' timestamp of notice; defaults to now
  364. * int 'is_local' source/gateway ID, one of:
  365. * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
  366. * Notice::REMOTE - Sent from a remote service;
  367. * hide from public timeline but show in
  368. * local "and friends" timelines
  369. * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
  370. * Notice::GATEWAY - From another non-OStatus service;
  371. * will not appear in public views
  372. * float 'lat' decimal latitude for geolocation
  373. * float 'lon' decimal longitude for geolocation
  374. * int 'location_id' geoname identifier
  375. * int 'location_ns' geoname namespace to interpret location_id
  376. * int 'reply_to'; notice ID this is a reply to
  377. * int 'repeat_of'; notice ID this is a repeat of
  378. * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
  379. * string 'url' permalink to notice; defaults to local notice URL
  380. * string 'rendered' rendered HTML version of content
  381. * array 'replies' list of profile URIs for reply delivery in
  382. * place of extracting @-replies from content.
  383. * array 'groups' list of group IDs to deliver to, in place of
  384. * extracting ! tags from content
  385. * array 'tags' list of hashtag strings to save with the notice
  386. * in place of extracting # tags from content
  387. * array 'urls' list of attached/referred URLs to save with the
  388. * notice in place of extracting links from content
  389. * boolean 'distribute' whether to distribute the notice, default true
  390. * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
  391. * string 'verb' URL of the associated verb (default ActivityVerb::POST)
  392. * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
  393. *
  394. * @fixme tag override
  395. *
  396. * @return Notice
  397. * @throws ClientException
  398. */
  399. static function saveNew($profile_id, $content, $source, array $options=null) {
  400. $defaults = array('uri' => null,
  401. 'url' => null,
  402. 'conversation' => null, // URI of conversation
  403. 'reply_to' => null, // This will override convo URI if the parent is known
  404. 'repeat_of' => null, // This will override convo URI if the repeated notice is known
  405. 'scope' => null,
  406. 'distribute' => true,
  407. 'object_type' => null,
  408. 'verb' => null);
  409. if (!empty($options) && is_array($options)) {
  410. $options = array_merge($defaults, $options);
  411. extract($options);
  412. } else {
  413. extract($defaults);
  414. }
  415. if (!isset($is_local)) {
  416. $is_local = Notice::LOCAL_PUBLIC;
  417. }
  418. $profile = Profile::getKV('id', $profile_id);
  419. if (!$profile instanceof Profile) {
  420. // TRANS: Client exception thrown when trying to save a notice for an unknown user.
  421. throw new ClientException(_('Problem saving notice. Unknown user.'));
  422. }
  423. $user = User::getKV('id', $profile_id);
  424. if ($user instanceof User) {
  425. // Use the local user's shortening preferences, if applicable.
  426. $final = $user->shortenLinks($content);
  427. } else {
  428. $final = common_shorten_links($content);
  429. }
  430. if (Notice::contentTooLong($final)) {
  431. // TRANS: Client exception thrown if a notice contains too many characters.
  432. throw new ClientException(_('Problem saving notice. Too long.'));
  433. }
  434. if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
  435. common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
  436. // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
  437. throw new ClientException(_('Too many notices too fast; take a breather '.
  438. 'and post again in a few minutes.'));
  439. }
  440. if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
  441. common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
  442. // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
  443. throw new ClientException(_('Too many duplicate messages too quickly;'.
  444. ' take a breather and post again in a few minutes.'));
  445. }
  446. if (!$profile->hasRight(Right::NEWNOTICE)) {
  447. common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
  448. // TRANS: Client exception thrown when a user tries to post while being banned.
  449. throw new ClientException(_('You are banned from posting notices on this site.'), 403);
  450. }
  451. $notice = new Notice();
  452. $notice->profile_id = $profile_id;
  453. $autosource = common_config('public', 'autosource');
  454. // Sandboxed are non-false, but not 1, either
  455. if (!$profile->hasRight(Right::PUBLICNOTICE) ||
  456. ($source && $autosource && in_array($source, $autosource))) {
  457. $notice->is_local = Notice::LOCAL_NONPUBLIC;
  458. } else {
  459. $notice->is_local = $is_local;
  460. }
  461. if (!empty($created)) {
  462. $notice->created = $created;
  463. } else {
  464. $notice->created = common_sql_now();
  465. }
  466. if (!$notice->isLocal()) {
  467. // Only do these checks for non-local notices. Local notices will generate these values later.
  468. if (!common_valid_http_url($url)) {
  469. common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
  470. }
  471. if (empty($uri)) {
  472. throw new ServerException('No URI for remote notice. Cannot accept that.');
  473. }
  474. }
  475. $notice->content = $final;
  476. $notice->source = $source;
  477. $notice->uri = $uri;
  478. $notice->url = $url;
  479. // Get the groups here so we can figure out replies and such
  480. if (!isset($groups)) {
  481. $groups = User_group::idsFromText($notice->content, $profile);
  482. }
  483. $reply = null;
  484. // Handle repeat case
  485. if (!empty($options['repeat_of'])) {
  486. // Check for a private one
  487. $repeat = Notice::getByID($options['repeat_of']);
  488. if ($profile->sameAs($repeat->getProfile())) {
  489. // TRANS: Client error displayed when trying to repeat an own notice.
  490. throw new ClientException(_('You cannot repeat your own notice.'));
  491. }
  492. if ($repeat->scope != Notice::SITE_SCOPE &&
  493. $repeat->scope != Notice::PUBLIC_SCOPE) {
  494. // TRANS: Client error displayed when trying to repeat a non-public notice.
  495. throw new ClientException(_('Cannot repeat a private notice.'), 403);
  496. }
  497. if (!$repeat->inScope($profile)) {
  498. // The generic checks above should cover this, but let's be sure!
  499. // TRANS: Client error displayed when trying to repeat a notice you cannot access.
  500. throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
  501. }
  502. if ($profile->hasRepeated($repeat)) {
  503. // TRANS: Client error displayed when trying to repeat an already repeated notice.
  504. throw new ClientException(_('You already repeated that notice.'));
  505. }
  506. $notice->repeat_of = $repeat->id;
  507. $notice->conversation = $repeat->conversation;
  508. } else {
  509. $reply = null;
  510. // If $reply_to is specified, we check that it exists, and then
  511. // return it if it does
  512. if (!empty($reply_to)) {
  513. $reply = Notice::getKV('id', $reply_to);
  514. } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
  515. // If the source lacks capability of sending the "reply_to"
  516. // metadata, let's try to find an inline replyto-reference.
  517. $reply = self::getInlineReplyTo($profile, $final);
  518. }
  519. if ($reply instanceof Notice) {
  520. if (!$reply->inScope($profile)) {
  521. // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
  522. // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
  523. throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
  524. $profile->nickname, $reply->id), 403);
  525. }
  526. // If it's a repeat, the reply_to should be to the original
  527. if ($reply->isRepeat()) {
  528. $notice->reply_to = $reply->repeat_of;
  529. } else {
  530. $notice->reply_to = $reply->id;
  531. }
  532. // But the conversation ought to be the same :)
  533. $notice->conversation = $reply->conversation;
  534. // If the original is private to a group, and notice has
  535. // no group specified, make it to the same group(s)
  536. if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
  537. $groups = array();
  538. $replyGroups = $reply->getGroups();
  539. foreach ($replyGroups as $group) {
  540. if ($profile->isMember($group)) {
  541. $groups[] = $group->id;
  542. }
  543. }
  544. }
  545. // Scope set below
  546. }
  547. // If we don't know the reply, we might know the conversation!
  548. // This will happen if a known remote user replies to an
  549. // unknown remote user - within a known conversation.
  550. if (empty($notice->conversation) and !empty($options['conversation'])) {
  551. $conv = Conversation::getKV('uri', $options['conversation']);
  552. if ($conv instanceof Conversation) {
  553. common_debug('Conversation stitched together from (probably) a reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
  554. } else {
  555. // Conversation entry with specified URI was not found, so we must create it.
  556. common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
  557. // The insert in Conversation::create throws exception on failure
  558. $conv = Conversation::create($options['conversation'], $notice->created);
  559. }
  560. $notice->conversation = $conv->getID();
  561. unset($conv);
  562. }
  563. }
  564. // If it's not part of a conversation, it's the beginning of a new conversation.
  565. if (empty($notice->conversation)) {
  566. $conv = Conversation::create();
  567. $notice->conversation = $conv->getID();
  568. unset($conv);
  569. }
  570. $notloc = new Notice_location();
  571. if (!empty($lat) && !empty($lon)) {
  572. $notloc->lat = $lat;
  573. $notloc->lon = $lon;
  574. }
  575. if (!empty($location_ns) && !empty($location_id)) {
  576. $notloc->location_id = $location_id;
  577. $notloc->location_ns = $location_ns;
  578. }
  579. if (!empty($rendered)) {
  580. $notice->rendered = $rendered;
  581. } else {
  582. $notice->rendered = common_render_content($final,
  583. $notice->getProfile(),
  584. $notice->hasParent() ? $notice->getParent() : null);
  585. }
  586. if (empty($verb)) {
  587. if ($notice->isRepeat()) {
  588. $notice->verb = ActivityVerb::SHARE;
  589. $notice->object_type = ActivityObject::ACTIVITY;
  590. } else {
  591. $notice->verb = ActivityVerb::POST;
  592. }
  593. } else {
  594. $notice->verb = $verb;
  595. }
  596. if (empty($object_type)) {
  597. $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
  598. } else {
  599. $notice->object_type = $object_type;
  600. }
  601. if (is_null($scope) && $reply instanceof Notice) {
  602. $notice->scope = $reply->scope;
  603. } else {
  604. $notice->scope = $scope;
  605. }
  606. $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
  607. if (Event::handle('StartNoticeSave', array(&$notice))) {
  608. // XXX: some of these functions write to the DB
  609. try {
  610. $notice->insert(); // throws exception on failure, if successful we have an ->id
  611. if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
  612. $notloc->notice_id = $notice->getID();
  613. $notloc->insert(); // store the notice location if it had any information
  614. }
  615. } catch (Exception $e) {
  616. // Let's test if we managed initial insert, which would imply
  617. // failing on some update-part (check 'insert()'). Delete if
  618. // something had been stored to the database.
  619. if (!empty($notice->id)) {
  620. $notice->delete();
  621. }
  622. throw $e;
  623. }
  624. }
  625. // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
  626. // the activityverb is a POST (since stuff like repeat, favorite etc.
  627. // reasonably handle notifications themselves.
  628. if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
  629. if (isset($replies)) {
  630. $notice->saveKnownReplies($replies);
  631. } else {
  632. $notice->saveReplies();
  633. }
  634. if (isset($tags)) {
  635. $notice->saveKnownTags($tags);
  636. } else {
  637. $notice->saveTags();
  638. }
  639. // Note: groups may save tags, so must be run after tags are saved
  640. // to avoid errors on duplicates.
  641. // Note: groups should always be set.
  642. $notice->saveKnownGroups($groups);
  643. if (isset($urls)) {
  644. $notice->saveKnownUrls($urls);
  645. } else {
  646. $notice->saveUrls();
  647. }
  648. }
  649. if ($distribute) {
  650. // Prepare inbox delivery, may be queued to background.
  651. $notice->distribute();
  652. }
  653. return $notice;
  654. }
  655. static function saveActivity(Activity $act, Profile $actor, array $options=array())
  656. {
  657. // First check if we're going to let this Activity through from the specific actor
  658. if (!$actor->hasRight(Right::NEWNOTICE)) {
  659. common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
  660. // TRANS: Client exception thrown when a user tries to post while being banned.
  661. throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
  662. }
  663. if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
  664. common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
  665. // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
  666. throw new ClientException(_m('Too many notices too fast; take a breather '.
  667. 'and post again in a few minutes.'));
  668. }
  669. // Get ActivityObject properties
  670. $actobj = null;
  671. if (!empty($act->id)) {
  672. // implied object
  673. $options['uri'] = $act->id;
  674. $options['url'] = $act->link;
  675. } else {
  676. $actobj = count($act->objects)===1 ? $act->objects[0] : null;
  677. if (!is_null($actobj) && !empty($actobj->id)) {
  678. $options['uri'] = $actobj->id;
  679. if ($actobj->link) {
  680. $options['url'] = $actobj->link;
  681. } elseif (preg_match('!^https?://!', $actobj->id)) {
  682. $options['url'] = $actobj->id;
  683. }
  684. }
  685. }
  686. $defaults = array(
  687. 'groups' => array(),
  688. 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
  689. 'mentions' => array(),
  690. 'reply_to' => null,
  691. 'repeat_of' => null,
  692. 'scope' => null,
  693. 'source' => 'unknown',
  694. 'tags' => array(),
  695. 'uri' => null,
  696. 'url' => null,
  697. 'urls' => array(),
  698. 'distribute' => true);
  699. // options will have default values when nothing has been supplied
  700. $options = array_merge($defaults, $options);
  701. foreach (array_keys($defaults) as $key) {
  702. // Only convert the keynames we specify ourselves from 'defaults' array into variables
  703. $$key = $options[$key];
  704. }
  705. extract($options, EXTR_SKIP);
  706. // dupe check
  707. $stored = new Notice();
  708. if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
  709. $stored->uri = $uri;
  710. if ($stored->find()) {
  711. common_debug('cannot create duplicate Notice URI: '.$stored->uri);
  712. // I _assume_ saving a Notice with a colliding URI means we're really trying to
  713. // save the same notice again...
  714. throw new AlreadyFulfilledException('Notice URI already exists');
  715. }
  716. }
  717. $autosource = common_config('public', 'autosource');
  718. // Sandboxed are non-false, but not 1, either
  719. if (!$actor->hasRight(Right::PUBLICNOTICE) ||
  720. ($source && $autosource && in_array($source, $autosource))) {
  721. // FIXME: ...what about remote nonpublic? Hmmm. That is, if we sandbox remote profiles...
  722. $stored->is_local = Notice::LOCAL_NONPUBLIC;
  723. } else {
  724. $stored->is_local = intval($is_local);
  725. }
  726. if (!$stored->isLocal()) {
  727. // Only do these checks for non-local notices. Local notices will generate these values later.
  728. if (!common_valid_http_url($url)) {
  729. common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
  730. }
  731. if (empty($uri)) {
  732. throw new ServerException('No URI for remote notice. Cannot accept that.');
  733. }
  734. }
  735. $stored->profile_id = $actor->id;
  736. $stored->source = $source;
  737. $stored->uri = $uri;
  738. $stored->url = $url;
  739. $stored->verb = $act->verb;
  740. $content = $act->content ?: $act->summary;
  741. if (is_null($content) && !is_null($actobj)) {
  742. $content = $actobj->content ?: $actobj->summary;
  743. }
  744. // Strip out any bad HTML
  745. $stored->rendered = common_purify($content);
  746. $stored->content = common_strip_html($stored->getRendered(), true, true);
  747. if (trim($stored->content) === '') {
  748. // TRANS: Error message when the plain text content of a notice has zero length.
  749. throw new ClientException(_('Empty notice content, will not save this.'));
  750. }
  751. // Maybe a missing act-time should be fatal if the actor is not local?
  752. if (!empty($act->time)) {
  753. $stored->created = common_sql_date($act->time);
  754. } else {
  755. $stored->created = common_sql_now();
  756. }
  757. $reply = null;
  758. if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
  759. $reply = self::getKV('uri', $act->context->replyToID);
  760. }
  761. if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
  762. $reply = self::getKV('uri', $act->target->id);
  763. }
  764. if ($reply instanceof Notice) {
  765. if (!$reply->inScope($actor)) {
  766. // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
  767. // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
  768. throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
  769. }
  770. $stored->reply_to = $reply->id;
  771. $stored->conversation = $reply->conversation;
  772. // If the original is private to a group, and notice has no group specified,
  773. // make it to the same group(s)
  774. if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
  775. $replyGroups = $reply->getGroups();
  776. foreach ($replyGroups as $group) {
  777. if ($actor->isMember($group)) {
  778. $groups[] = $group->id;
  779. }
  780. }
  781. }
  782. if (is_null($scope)) {
  783. $scope = $reply->scope;
  784. }
  785. } else {
  786. // If we don't know the reply, we might know the conversation!
  787. // This will happen if a known remote user replies to an
  788. // unknown remote user - within a known conversation.
  789. if (empty($stored->conversation) and !empty($act->context->conversation)) {
  790. $conv = Conversation::getKV('uri', $act->context->conversation);
  791. if ($conv instanceof Conversation) {
  792. common_debug('Conversation stitched together from (probably) a reply activity to unknown remote user. Activity creation time ('.$stored->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
  793. } else {
  794. // Conversation entry with specified URI was not found, so we must create it.
  795. common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
  796. // The insert in Conversation::create throws exception on failure
  797. $conv = Conversation::create($act->context->conversation, $stored->created);
  798. }
  799. $stored->conversation = $conv->getID();
  800. unset($conv);
  801. }
  802. }
  803. // If it's not part of a conversation, it's the beginning of a new conversation.
  804. if (empty($stored->conversation)) {
  805. $conv = Conversation::create();
  806. $stored->conversation = $conv->getID();
  807. unset($conv);
  808. }
  809. $notloc = null;
  810. if ($act->context instanceof ActivityContext) {
  811. if ($act->context->location instanceof Location) {
  812. $notloc = Notice_location::fromLocation($act->context->location);
  813. }
  814. } else {
  815. $act->context = new ActivityContext();
  816. }
  817. $stored->scope = self::figureOutScope($actor, $groups, $scope);
  818. foreach ($act->categories as $cat) {
  819. if ($cat->term) {
  820. $term = common_canonical_tag($cat->term);
  821. if (!empty($term)) {
  822. $tags[] = $term;
  823. }
  824. }
  825. }
  826. foreach ($act->enclosures as $href) {
  827. // @todo FIXME: Save these locally or....?
  828. $urls[] = $href;
  829. }
  830. if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
  831. if (empty($act->objects[0]->type)) {
  832. // Default type for the post verb is 'note', but we know it's
  833. // a 'comment' if it is in reply to something.
  834. $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
  835. } else {
  836. //TODO: Is it safe to always return a relative URI? The
  837. // JSON version of ActivityStreams always use it, so we
  838. // should definitely be able to handle it...
  839. $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
  840. }
  841. }
  842. if (Event::handle('StartNoticeSave', array(&$stored))) {
  843. // XXX: some of these functions write to the DB
  844. try {
  845. $result = $stored->insert(); // throws exception on error
  846. if ($notloc instanceof Notice_location) {
  847. $notloc->notice_id = $stored->getID();
  848. $notloc->insert();
  849. }
  850. $orig = clone($stored); // for updating later in this try clause
  851. $object = null;
  852. Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
  853. if (empty($object)) {
  854. throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
  855. }
  856. // If something changed in the Notice during StoreActivityObject
  857. $stored->update($orig);
  858. } catch (Exception $e) {
  859. if (empty($stored->id)) {
  860. common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
  861. } else {
  862. common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
  863. $stored->delete();
  864. }
  865. throw $e;
  866. }
  867. }
  868. if (!$stored instanceof Notice) {
  869. throw new ServerException('StartNoticeSave did not give back a Notice');
  870. }
  871. // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
  872. // the activityverb is a POST (since stuff like repeat, favorite etc.
  873. // reasonably handle notifications themselves.
  874. if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
  875. if (!empty($tags)) {
  876. $stored->saveKnownTags($tags);
  877. } else {
  878. $stored->saveTags();
  879. }
  880. // Note: groups may save tags, so must be run after tags are saved
  881. // to avoid errors on duplicates.
  882. $stored->saveAttentions($act->context->attention);
  883. if (!empty($urls)) {
  884. $stored->saveKnownUrls($urls);
  885. } else {
  886. $stored->saveUrls();
  887. }
  888. }
  889. if ($distribute) {
  890. // Prepare inbox delivery, may be queued to background.
  891. $stored->distribute();
  892. }
  893. return $stored;
  894. }
  895. static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
  896. $scope = is_null($scope) ? self::defaultScope() : intval($scope);
  897. // For private streams
  898. try {
  899. $user = $actor->getUser();
  900. // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
  901. if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
  902. $scope |= Notice::FOLLOWER_SCOPE;
  903. }
  904. } catch (NoSuchUserException $e) {
  905. // TODO: Not a local user, so we don't know about scope preferences... yet!
  906. }
  907. // Force the scope for private groups
  908. foreach ($groups as $group_id) {
  909. try {
  910. $group = User_group::getByID($group_id);
  911. if ($group->force_scope) {
  912. $scope |= Notice::GROUP_SCOPE;
  913. break;
  914. }
  915. } catch (Exception $e) {
  916. common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
  917. }
  918. }
  919. return $scope;
  920. }
  921. function blowOnInsert($conversation = false)
  922. {
  923. $this->blowStream('profile:notice_ids:%d', $this->profile_id);
  924. if ($this->isPublic()) {
  925. $this->blowStream('public');
  926. $this->blowStream('networkpublic');
  927. }
  928. if ($this->conversation) {
  929. self::blow('notice:list-ids:conversation:%s', $this->conversation);
  930. self::blow('conversation:notice_count:%d', $this->conversation);
  931. }
  932. if ($this->isRepeat()) {
  933. // XXX: we should probably only use one of these
  934. $this->blowStream('notice:repeats:%d', $this->repeat_of);
  935. self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
  936. }
  937. $original = Notice::getKV('id', $this->repeat_of);
  938. if ($original instanceof Notice) {
  939. $originalUser = User::getKV('id', $original->profile_id);
  940. if ($originalUser instanceof User) {
  941. $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
  942. }
  943. }
  944. $profile = Profile::getKV($this->profile_id);
  945. if ($profile instanceof Profile) {
  946. $profile->blowNoticeCount();
  947. }
  948. $ptags = $this->getProfileTags();
  949. foreach ($ptags as $ptag) {
  950. $ptag->blowNoticeStreamCache();
  951. }
  952. }
  953. /**
  954. * Clear cache entries related to this notice at delete time.
  955. * Necessary to avoid breaking paging on public, profile timelines.
  956. */
  957. function blowOnDelete()
  958. {
  959. $this->blowOnInsert();
  960. self::blow('profile:notice_ids:%d;last', $this->profile_id);
  961. if ($this->isPublic()) {
  962. self::blow('public;last');
  963. self::blow('networkpublic;last');
  964. }
  965. self::blow('fave:by_notice', $this->id);
  966. if ($this->conversation) {
  967. // In case we're the first, will need to calc a new root.
  968. self::blow('notice:conversation_root:%d', $this->conversation);
  969. }
  970. $ptags = $this->getProfileTags();
  971. foreach ($ptags as $ptag) {
  972. $ptag->blowNoticeStreamCache(true);
  973. }
  974. }
  975. function blowStream()
  976. {
  977. $c = self::memcache();
  978. if (empty($c)) {
  979. return false;
  980. }
  981. $args = func_get_args();
  982. $format = array_shift($args);
  983. $keyPart = vsprintf($format, $args);
  984. $cacheKey = Cache::key($keyPart);
  985. $c->delete($cacheKey);
  986. // delete the "last" stream, too, if this notice is
  987. // older than the top of that stream
  988. $lastKey = $cacheKey.';last';
  989. $lastStr = $c->get($lastKey);
  990. if ($lastStr !== false) {
  991. $window = explode(',', $lastStr);
  992. $lastID = $window[0];
  993. $lastNotice = Notice::getKV('id', $lastID);
  994. if (!$lastNotice instanceof Notice // just weird
  995. || strtotime($lastNotice->created) >= strtotime($this->created)) {
  996. $c->delete($lastKey);
  997. }
  998. }
  999. }
  1000. /** save all urls in the notice to the db
  1001. *
  1002. * follow redirects and save all available file information
  1003. * (mimetype, date, size, oembed, etc.)
  1004. *
  1005. * @return void
  1006. */
  1007. function saveUrls() {
  1008. if (common_config('attachments', 'process_links')) {
  1009. common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
  1010. }
  1011. }
  1012. /**
  1013. * Save the given URLs as related links/attachments to the db
  1014. *
  1015. * follow redirects and save all available file information
  1016. * (mimetype, date, size, oembed, etc.)
  1017. *
  1018. * @return void
  1019. */
  1020. function saveKnownUrls($urls)
  1021. {
  1022. if (common_config('attachments', 'process_links')) {
  1023. // @fixme validation?
  1024. foreach (array_unique($urls) as $url) {
  1025. $this->saveUrl($url, $this);
  1026. }
  1027. }
  1028. }
  1029. /**
  1030. * @private callback
  1031. */
  1032. function saveUrl($url, Notice $notice) {
  1033. try {
  1034. File::processNew($url, $notice);
  1035. } catch (ServerException $e) {
  1036. // Could not save URL. Log it?
  1037. }
  1038. }
  1039. static function checkDupes($profile_id, $content) {
  1040. $profile = Profile::getKV($profile_id);
  1041. if (!$profile instanceof Profile) {
  1042. return false;
  1043. }
  1044. $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
  1045. if (!empty($notice)) {
  1046. $last = 0;
  1047. while ($notice->fetch()) {
  1048. if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
  1049. return true;
  1050. } else if ($notice->content == $content) {
  1051. return false;
  1052. }
  1053. }
  1054. }
  1055. // If we get here, oldest item in cache window is not
  1056. // old enough for dupe limit; do direct check against DB
  1057. $notice = new Notice();
  1058. $notice->profile_id = $profile_id;
  1059. $notice->content = $content;
  1060. $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
  1061. $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
  1062. $cnt = $notice->count();
  1063. return ($cnt == 0);
  1064. }
  1065. static function checkEditThrottle($profile_id) {
  1066. $profile = Profile::getKV($profile_id);
  1067. if (!$profile instanceof Profile) {
  1068. return false;
  1069. }
  1070. // Get the Nth notice
  1071. $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
  1072. if ($notice && $notice->fetch()) {
  1073. // If the Nth notice was posted less than timespan seconds ago
  1074. if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
  1075. // Then we throttle
  1076. return false;
  1077. }
  1078. }
  1079. // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
  1080. return true;
  1081. }
  1082. protected $_attachments = array();
  1083. function attachments() {
  1084. if (isset($this->_attachments[$this->id])) {
  1085. return $this->_attachments[$this->id];
  1086. }
  1087. $f2ps = File_to_post::listGet('post_id', array($this->id));
  1088. $ids = array();
  1089. foreach ($f2ps[$this->id] as $f2p) {
  1090. $ids[] = $f2p->file_id;
  1091. }
  1092. $files = File::multiGet('id', $ids);
  1093. $this->_attachments[$this->id] = $files->fetchAll();
  1094. return $this->_attachments[$this->id];
  1095. }
  1096. function _setAttachments($attachments)
  1097. {
  1098. $this->_attachments[$this->id] = $attachments;
  1099. }
  1100. static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
  1101. {
  1102. $stream = new PublicNoticeStream();
  1103. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  1104. }
  1105. static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
  1106. {
  1107. $stream = new ConversationNoticeStream($id);
  1108. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  1109. }
  1110. /**
  1111. * Is this notice part of an active conversation?
  1112. *
  1113. * @return boolean true if other messages exist in the same
  1114. * conversation, false if this is the only one
  1115. */
  1116. function hasConversation()
  1117. {
  1118. if (empty($this->conversation)) {
  1119. // this notice is not part of a conversation apparently
  1120. // FIXME: all notices should have a conversation value, right?
  1121. return false;
  1122. }
  1123. $stream = new ConversationNoticeStream($this->conversation);
  1124. $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
  1125. // if our "offset 1, limit 1" query got a result, return true else false
  1126. return $notice->N > 0;
  1127. }
  1128. /**
  1129. * Grab the earliest notice from this conversation.
  1130. *
  1131. * @return Notice or null
  1132. */
  1133. function conversationRoot($profile=-1)
  1134. {
  1135. // XXX: can this happen?
  1136. if (empty($this->conversation)) {
  1137. return null;
  1138. }
  1139. // Get the current profile if not specified
  1140. if (is_int($profile) && $profile == -1) {
  1141. $profile = Profile::current();
  1142. }
  1143. // If this notice is out of scope, no root for you!
  1144. if (!$this->inScope($profile)) {
  1145. return null;
  1146. }
  1147. // If this isn't a reply to anything, then it's its own
  1148. // root if it's the earliest notice in the conversation:
  1149. if (empty($this->reply_to)) {
  1150. $root = new Notice;
  1151. $root->conversation = $this->conversation;
  1152. $root->orderBy('notice.created ASC');
  1153. $root->find(true); // true means "fetch first result"
  1154. $root->free();
  1155. return $root;
  1156. }
  1157. if (is_null($profile)) {
  1158. $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
  1159. } else {
  1160. $keypart = sprintf('notice:conversation_root:%d:%d',
  1161. $this->id,
  1162. $profile->id);
  1163. }
  1164. $root = self::cacheGet($keypart);
  1165. if ($root !== false && $root->inScope($profile)) {
  1166. return $root;
  1167. }
  1168. $last = $this;
  1169. while (true) {
  1170. try {
  1171. $parent = $last->getParent();
  1172. if ($parent->inScope($profile)) {
  1173. $last = $parent;
  1174. continue;
  1175. }
  1176. } catch (NoParentNoticeException $e) {
  1177. // Latest notice has no parent
  1178. } catch (NoResultException $e) {
  1179. // Notice was not found, so we can't go further up in the tree.
  1180. // FIXME: Maybe we should do this in a more stable way where deleted
  1181. // notices won't break conversation chains?
  1182. }
  1183. // No parent, or parent out of scope
  1184. $root = $last;
  1185. break;
  1186. }
  1187. self::cacheSet($keypart, $root);
  1188. return $root;
  1189. }
  1190. /**
  1191. * Pull up a full list of local recipients who will be getting
  1192. * this notice in their inbox. Results will be cached, so don't
  1193. * change the input data wily-nilly!
  1194. *
  1195. * @param array $groups optional list of Group objects;
  1196. * if left empty, will be loaded from group_inbox records
  1197. * @param array $recipient optional list of reply profile ids
  1198. * if left empty, will be loaded from reply records
  1199. * @return array associating recipient user IDs with an inbox source constant
  1200. */
  1201. function whoGets(array $groups=null, array $recipients=null)
  1202. {
  1203. $c = self::memcache();
  1204. if (!empty($c)) {
  1205. $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
  1206. if ($ni !== false) {
  1207. return $ni;
  1208. }
  1209. }
  1210. if (is_null($recipients)) {
  1211. $recipients = $this->getReplies();
  1212. }
  1213. $ni = array();
  1214. // Give plugins a chance to add folks in at start...
  1215. if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
  1216. $users = $this->getSubscribedUsers();
  1217. foreach ($users as $id) {
  1218. $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
  1219. }
  1220. if (is_null($groups)) {
  1221. $groups = $this->getGroups();
  1222. }
  1223. foreach ($groups as $group) {
  1224. $users = $group->getUserMembers();
  1225. foreach ($users as $id) {
  1226. if (!array_key_exists($id, $ni)) {
  1227. $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
  1228. }
  1229. }
  1230. }
  1231. $ptAtts = $this->getAttentionsFromProfileTags();
  1232. foreach ($ptAtts as $key=>$val) {
  1233. if (!array_key_exists($key, $ni)) {
  1234. $ni[$key] = $val;
  1235. }
  1236. }
  1237. foreach ($recipients as $recipient) {
  1238. if (!array_key_exists($recipient, $ni)) {
  1239. $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
  1240. }
  1241. }
  1242. // Exclude any deleted, non-local, or blocking recipients.
  1243. $profile = $this->getProfile();
  1244. $originalProfile = null;
  1245. if ($this->isRepeat()) {
  1246. // Check blocks against the original notice's poster as well.
  1247. $original = Notice::getKV('id', $this->repeat_of);
  1248. if ($original instanceof Notice) {
  1249. $originalProfile = $original->getProfile();
  1250. }
  1251. }
  1252. foreach ($ni as $id => $source) {
  1253. try {
  1254. $user = User::getKV('id', $id);
  1255. if (!$user instanceof User ||
  1256. $user->hasBlocked($profile) ||
  1257. ($originalProfile && $user->hasBlocked($originalProfile))) {
  1258. unset($ni[$id]);
  1259. }
  1260. } catch (UserNoProfileException $e) {
  1261. // User doesn't have a profile; invalid; skip them.
  1262. unset($ni[$id]);
  1263. }
  1264. }
  1265. // Give plugins a chance to filter out...
  1266. Event::handle('EndNoticeWhoGets', array($this, &$ni));
  1267. }
  1268. if (!empty($c)) {
  1269. // XXX: pack this data better
  1270. $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
  1271. }
  1272. return $ni;
  1273. }
  1274. function getSubscribedUsers()
  1275. {
  1276. $user = new User();
  1277. if(common_config('db','quote_identifiers'))
  1278. $user_table = '"user"';
  1279. else $user_table = 'user';
  1280. $qry =
  1281. 'SELECT id ' .
  1282. 'FROM '. $user_table .' JOIN subscription '.
  1283. 'ON '. $user_table .'.id = subscription.subscriber ' .
  1284. 'WHERE subscription.subscribed = %d ';
  1285. $user->query(sprintf($qry, $this->profile_id));
  1286. $ids = array();
  1287. while ($user->fetch()) {
  1288. $ids[] = $user->id;
  1289. }
  1290. $user->free();
  1291. return $ids;
  1292. }
  1293. function getProfileTags()
  1294. {
  1295. $profile = $this->getProfile();
  1296. $list = $profile->getOtherTags($profile);
  1297. $ptags = array();
  1298. while($list->fetch()) {
  1299. $ptags[] = clone($list);
  1300. }
  1301. return $ptags;
  1302. }
  1303. public function getAttentionsFromProfileTags()
  1304. {
  1305. $ni = array();
  1306. $ptags = $this->getProfileTags();
  1307. foreach ($ptags as $ptag) {
  1308. $users = $ptag->getUserSubscribers();
  1309. foreach ($users as $id) {
  1310. $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
  1311. }
  1312. }
  1313. return $ni;
  1314. }
  1315. /**
  1316. * Record this notice to the given group inboxes for delivery.
  1317. * Overrides the regular parsing of !group markup.
  1318. *
  1319. * @param string $group_ids
  1320. * @fixme might prefer URIs as identifiers, as for replies?
  1321. * best with generalizations on user_group to support
  1322. * remote groups better.
  1323. */
  1324. function saveKnownGroups(array $group_ids)
  1325. {
  1326. $groups = array();
  1327. foreach (array_unique($group_ids) as $id) {
  1328. $group = User_group::getKV('id', $id);
  1329. if ($group instanceof User_group) {
  1330. common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
  1331. $result = $this->addToGroupInbox($group);
  1332. if (!$result) {
  1333. common_log_db_error($gi, 'INSERT', __FILE__);
  1334. }
  1335. if (common_config('group', 'addtag')) {
  1336. // we automatically add a tag for every group name, too
  1337. $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
  1338. 'notice_id' => $this->id));
  1339. if (is_null($tag)) {
  1340. $this->saveTag($group->nickname);
  1341. }
  1342. }
  1343. $groups[] = clone($group);
  1344. } else {
  1345. common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
  1346. }
  1347. }
  1348. return $groups;
  1349. }
  1350. function addToGroupInbox(User_group $group)
  1351. {
  1352. $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
  1353. 'notice_id' => $this->id));
  1354. if (!$gi instanceof Group_inbox) {
  1355. $gi = new Group_inbox();
  1356. $gi->group_id = $group->id;
  1357. $gi->notice_id = $this->id;
  1358. $gi->created = $this->created;
  1359. $result = $gi->insert();
  1360. if (!$result) {
  1361. common_log_db_error($gi, 'INSERT', __FILE__);
  1362. // TRANS: Server exception thrown when an update for a group inbox fails.
  1363. throw new ServerException(_('Problem saving group inbox.'));
  1364. }
  1365. self::blow('user_group:notice_ids:%d', $gi->group_id);
  1366. }
  1367. return true;
  1368. }
  1369. function saveAttentions(array $uris)
  1370. {
  1371. foreach ($uris as $uri=>$type) {
  1372. try {
  1373. $target = Profile::fromUri($uri);
  1374. } catch (UnknownUriException $e) {
  1375. common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
  1376. continue;
  1377. }
  1378. try {
  1379. $this->saveAttention($target);
  1380. } catch (AlreadyFulfilledException $e) {
  1381. common_debug('Attention already exists: '.var_export($e->getMessage(),true));
  1382. } catch (Exception $e) {
  1383. common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
  1384. }
  1385. }
  1386. }
  1387. /**
  1388. * Saves an attention for a profile (user or group) which means
  1389. * it shows up in their home feed and such.
  1390. */
  1391. function saveAttention(Profile $target, $reason=null)
  1392. {
  1393. if ($target->isGroup()) {
  1394. // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
  1395. // legacy notification method, will still be in use for quite a while I think
  1396. $this->addToGroupInbox($target->getGroup());
  1397. } else {
  1398. if ($target->hasBlocked($this->getProfile())) {
  1399. common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
  1400. return false;
  1401. }
  1402. }
  1403. if ($target->isLocal()) {
  1404. // legacy notification method, will still be in use for quite a while I think
  1405. $this->saveReply($target->getID());
  1406. }
  1407. $att = Attention::saveNew($this, $target, $reason);
  1408. self::blow('reply:stream:%d', $target->getID());
  1409. return true;
  1410. }
  1411. /**
  1412. * Save reply records indicating that this notice needs to be
  1413. * delivered to the local users with the given URIs.
  1414. *
  1415. * Since this is expected to be used when saving foreign-sourced
  1416. * messages, we won't deliver to any remote targets as that's the
  1417. * source service's responsibility.
  1418. *
  1419. * Mail notifications etc will be handled later.
  1420. *
  1421. * @param array $uris Array of unique identifier URIs for recipients
  1422. */
  1423. function saveKnownReplies(array $uris)
  1424. {
  1425. if (empty($uris)) {
  1426. return;
  1427. }
  1428. $sender = $this->getProfile();
  1429. foreach (array_unique($uris) as $uri) {
  1430. try {
  1431. $profile = Profile::fromUri($uri);
  1432. } catch (UnknownUriException $e) {
  1433. common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
  1434. continue;
  1435. }
  1436. if ($profile->hasBlocked($sender)) {
  1437. common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
  1438. continue;
  1439. }
  1440. $this->saveReply($profile->getID());
  1441. self::blow('reply:stream:%d', $profile->getID());
  1442. }
  1443. }
  1444. /**
  1445. * Pull @-replies from this message's content in StatusNet markup format
  1446. * and save reply records indicating that this message needs to be
  1447. * delivered to those users.
  1448. *
  1449. * Mail notifications to local profiles will be sent later.
  1450. *
  1451. * @return array of integer profile IDs
  1452. */
  1453. function saveReplies()
  1454. {
  1455. $sender = $this->getProfile();
  1456. $replied = array();
  1457. // If it's a reply, save for the replied-to author
  1458. try {
  1459. $parent = $this->getParent();
  1460. $parentauthor = $parent->getProfile();
  1461. $this->saveReply($parentauthor->getID());
  1462. $replied[$parentauthor->getID()] = 1;
  1463. self::blow('reply:stream:%d', $parentauthor->getID());
  1464. } catch (NoParentNoticeException $e) {
  1465. // Not a reply, since it has no parent!
  1466. $parent = null;
  1467. } catch (NoResultException $e) {
  1468. // Parent notice was probably deleted
  1469. $parent = null;
  1470. }
  1471. // @todo ideally this parser information would only
  1472. // be calculated once.
  1473. $mentions = common_find_mentions($this->content, $sender, $parent);
  1474. foreach ($mentions as $mention) {
  1475. foreach ($mention['mentioned'] as $mentioned) {
  1476. // skip if they're already covered
  1477. if (array_key_exists($mentioned->id, $replied)) {
  1478. continue;
  1479. }
  1480. // Don't save replies from blocked profile to local user
  1481. if ($mentioned->hasBlocked($sender)) {
  1482. continue;
  1483. }
  1484. $this->saveReply($mentioned->id);
  1485. $replied[$mentioned->id] = 1;
  1486. self::blow('reply:stream:%d', $mentioned->id);
  1487. }
  1488. }
  1489. $recipientIds = array_keys($replied);
  1490. return $recipientIds;
  1491. }
  1492. function saveReply($profileId)
  1493. {
  1494. $reply = new Reply();
  1495. $reply->notice_id = $this->id;
  1496. $reply->profile_id = $profileId;
  1497. $reply->modified = $this->created;
  1498. $reply->insert();
  1499. return $reply;
  1500. }
  1501. protected $_attentionids = array();
  1502. /**
  1503. * Pull the complete list of known activity context attentions for this notice.
  1504. *
  1505. * @return array of integer profile ids (also group profiles)
  1506. */
  1507. function getAttentionProfileIDs()
  1508. {
  1509. if (!isset($this->_attentionids[$this->getID()])) {
  1510. $atts = Attention::multiGet('notice_id', array($this->getID()));
  1511. // (array)null means empty array
  1512. $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
  1513. }
  1514. return $this->_attentionids[$this->getID()];
  1515. }
  1516. protected $_replies = array();
  1517. /**
  1518. * Pull the complete list of @-mentioned profile IDs for this notice.
  1519. *
  1520. * @return array of integer profile ids
  1521. */
  1522. function getReplies()
  1523. {
  1524. if (!isset($this->_replies[$this->getID()])) {
  1525. $mentions = Reply::multiGet('notice_id', array($this->getID()));
  1526. $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
  1527. }
  1528. return $this->_replies[$this->getID()];
  1529. }
  1530. function _setReplies($replies)
  1531. {
  1532. $this->_replies[$this->getID()] = $replies;
  1533. }
  1534. /**
  1535. * Pull the complete list of @-reply targets for this notice.
  1536. *
  1537. * @return array of Profiles
  1538. */
  1539. function getAttentionProfiles()
  1540. {
  1541. $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
  1542. $profiles = Profile::multiGet('id', (array)$ids);
  1543. return $profiles->fetchAll();
  1544. }
  1545. /**
  1546. * Send e-mail notifications to local @-reply targets.
  1547. *
  1548. * Replies must already have been saved; this is expected to be run
  1549. * from the distrib queue handler.
  1550. */
  1551. function sendReplyNotifications()
  1552. {
  1553. // Don't send reply notifications for repeats
  1554. if ($this->isRepeat()) {
  1555. return array();
  1556. }
  1557. $recipientIds = $this->getReplies();
  1558. if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
  1559. require_once INSTALLDIR.'/lib/mail.php';
  1560. foreach ($recipientIds as $recipientId) {
  1561. try {
  1562. $user = User::getByID($recipientId);
  1563. mail_notify_attn($user, $this);
  1564. } catch (NoResultException $e) {
  1565. // No such user
  1566. }
  1567. }
  1568. Event::handle('EndNotifyMentioned', array($this, $recipientIds));
  1569. }
  1570. }
  1571. /**
  1572. * Pull list of Profile IDs of groups this notice addresses.
  1573. *
  1574. * @return array of Group _profile_ IDs
  1575. */
  1576. function getGroupProfileIDs()
  1577. {
  1578. $ids = array();
  1579. foreach ($this->getGroups() as $group) {
  1580. $ids[] = $group->profile_id;
  1581. }
  1582. return $ids;
  1583. }
  1584. /**
  1585. * Pull list of groups this notice needs to be delivered to,
  1586. * as previously recorded by saveKnownGroups().
  1587. *
  1588. * @return array of Group objects
  1589. */
  1590. protected $_groups = array();
  1591. function getGroups()
  1592. {
  1593. // Don't save groups for repeats
  1594. if (!empty($this->repeat_of)) {
  1595. return array();
  1596. }
  1597. if (isset($this->_groups[$this->id])) {
  1598. return $this->_groups[$this->id];
  1599. }
  1600. $gis = Group_inbox::listGet('notice_id', array($this->id));
  1601. $ids = array();
  1602. foreach ($gis[$this->id] as $gi) {
  1603. $ids[] = $gi->group_id;
  1604. }
  1605. $groups = User_group::multiGet('id', $ids);
  1606. $this->_groups[$this->id] = $groups->fetchAll();
  1607. return $this->_groups[$this->id];
  1608. }
  1609. function _setGroups($groups)
  1610. {
  1611. $this->_groups[$this->id] = $groups;
  1612. }
  1613. /**
  1614. * Convert a notice into an activity for export.
  1615. *
  1616. * @param Profile $scoped The currently logged in/scoped profile
  1617. *
  1618. * @return Activity activity object representing this Notice.
  1619. */
  1620. function asActivity(Profile $scoped=null)
  1621. {
  1622. $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
  1623. if ($act instanceof Activity) {
  1624. return $act;
  1625. }
  1626. $act = new Activity();
  1627. if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
  1628. $act->id = $this->uri;
  1629. $act->time = strtotime($this->created);
  1630. try {
  1631. $act->link = $this->getUrl();
  1632. } catch (InvalidUrlException $e) {
  1633. // The notice is probably a share or similar, which don't
  1634. // have a representational URL of their own.
  1635. }
  1636. $act->content = common_xml_safe_str($this->getRendered());
  1637. $profile = $this->getProfile();
  1638. $act->actor = $profile->asActivityObject();
  1639. $act->actor->extra[] = $profile->profileInfo($scoped);
  1640. $act->verb = $this->verb;
  1641. if (!$this->repeat_of) {
  1642. $act->objects[] = $this->asActivityObject();
  1643. }
  1644. // XXX: should this be handled by default processing for object entry?
  1645. // Categories
  1646. $tags = $this->getTags();
  1647. foreach ($tags as $tag) {
  1648. $cat = new AtomCategory();
  1649. $cat->term = $tag;
  1650. $act->categories[] = $cat;
  1651. }
  1652. // Enclosures
  1653. // XXX: use Atom Media and/or File activity objects instead
  1654. $attachments = $this->attachments();
  1655. foreach ($attachments as $attachment) {
  1656. // Include local attachments in Activity
  1657. if (!empty($attachment->filename)) {
  1658. $act->enclosures[] = $attachment->getEnclosure();
  1659. }
  1660. }
  1661. $ctx = new ActivityContext();
  1662. try {
  1663. $reply = $this->getParent();
  1664. $ctx->replyToID = $reply->getUri();
  1665. $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
  1666. } catch (NoParentNoticeException $e) {
  1667. // This is not a reply to something
  1668. } catch (NoResultException $e) {
  1669. // Parent notice was probably deleted
  1670. }
  1671. try {
  1672. $ctx->location = Notice_location::locFromStored($this);
  1673. } catch (ServerException $e) {
  1674. $ctx->location = null;
  1675. }
  1676. $conv = null;
  1677. if (!empty($this->conversation)) {
  1678. $conv = Conversation::getKV('id', $this->conversation);
  1679. if ($conv instanceof Conversation) {
  1680. $ctx->conversation = $conv->uri;
  1681. }
  1682. }
  1683. // This covers the legacy getReplies and getGroups too which get their data
  1684. // from entries stored via Notice::saveNew (which we want to move away from)...
  1685. foreach ($this->getAttentionProfiles() as $target) {
  1686. // User and group profiles which get the attention of this notice
  1687. $ctx->attention[$target->getUri()] = $target->getObjectType();
  1688. }
  1689. switch ($this->scope) {
  1690. case Notice::PUBLIC_SCOPE:
  1691. $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
  1692. break;
  1693. case Notice::FOLLOWER_SCOPE:
  1694. $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
  1695. $ctx->attention[$surl] = ActivityObject::COLLECTION;
  1696. break;
  1697. }
  1698. $act->context = $ctx;
  1699. $source = $this->getSource();
  1700. if ($source instanceof Notice_source) {
  1701. $act->generator = ActivityObject::fromNoticeSource($source);
  1702. }
  1703. // Source
  1704. $atom_feed = $profile->getAtomFeed();
  1705. if (!empty($atom_feed)) {
  1706. $act->source = new ActivitySource();
  1707. // XXX: we should store the actual feed ID
  1708. $act->source->id = $atom_feed;
  1709. // XXX: we should store the actual feed title
  1710. $act->source->title = $profile->getBestName();
  1711. $act->source->links['alternate'] = $profile->profileurl;
  1712. $act->source->links['self'] = $atom_feed;
  1713. $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
  1714. $notice = $profile->getCurrentNotice();
  1715. if ($notice instanceof Notice) {
  1716. $act->source->updated = self::utcDate($notice->created);
  1717. }
  1718. $user = User::getKV('id', $profile->id);
  1719. if ($user instanceof User) {
  1720. $act->source->links['license'] = common_config('license', 'url');
  1721. }
  1722. }
  1723. if ($this->isLocal()) {
  1724. $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
  1725. 'format' => 'atom'));
  1726. $act->editLink = $act->selfLink;
  1727. }
  1728. Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
  1729. }
  1730. self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
  1731. return $act;
  1732. }
  1733. // This has gotten way too long. Needs to be sliced up into functional bits
  1734. // or ideally exported to a utility class.
  1735. function asAtomEntry($namespace=false,
  1736. $source=false,
  1737. $author=true,
  1738. Profile $scoped=null)
  1739. {
  1740. $act = $this->asActivity($scoped);
  1741. $act->extra[] = $this->noticeInfo($scoped);
  1742. return $act->asString($namespace, $author, $source);
  1743. }
  1744. /**
  1745. * Extra notice info for atom entries
  1746. *
  1747. * Clients use some extra notice info in the atom stream.
  1748. * This gives it to them.
  1749. *
  1750. * @param Profile $scoped The currently logged in/scoped profile
  1751. *
  1752. * @return array representation of <statusnet:notice_info> element
  1753. */
  1754. function noticeInfo(Profile $scoped=null)
  1755. {
  1756. // local notice ID (useful to clients for ordering)
  1757. $noticeInfoAttr = array('local_id' => $this->id);
  1758. // notice source
  1759. $ns = $this->getSource();
  1760. if ($ns instanceof Notice_source) {
  1761. $noticeInfoAttr['source'] = $ns->code;
  1762. if (!empty($ns->url)) {
  1763. $noticeInfoAttr['source_link'] = $ns->url;
  1764. if (!empty($ns->name)) {
  1765. $noticeInfoAttr['source'] = $ns->name;
  1766. }
  1767. }
  1768. }
  1769. // favorite and repeated
  1770. if ($scoped instanceof Profile) {
  1771. $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
  1772. }
  1773. if (!empty($this->repeat_of)) {
  1774. $noticeInfoAttr['repeat_of'] = $this->repeat_of;
  1775. }
  1776. Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
  1777. return array('statusnet:notice_info', $noticeInfoAttr, null);
  1778. }
  1779. /**
  1780. * Returns an XML string fragment with a reference to a notice as an
  1781. * Activity Streams noun object with the given element type.
  1782. *
  1783. * Assumes that 'activity' namespace has been previously defined.
  1784. *
  1785. * @param string $element one of 'subject', 'object', 'target'
  1786. * @return string
  1787. */
  1788. function asActivityNoun($element)
  1789. {
  1790. $noun = $this->asActivityObject();
  1791. return $noun->asString('activity:' . $element);
  1792. }
  1793. public function asActivityObject()
  1794. {
  1795. $object = new ActivityObject();
  1796. if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
  1797. $object->type = $this->object_type ?: ActivityObject::NOTE;
  1798. $object->id = $this->getUri();
  1799. //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
  1800. $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
  1801. $object->content = $this->getRendered();
  1802. $object->link = $this->getUrl();
  1803. $object->extra[] = array('status_net', array('notice_id' => $this->id));
  1804. Event::handle('EndActivityObjectFromNotice', array($this, &$object));
  1805. }
  1806. if (!$object instanceof ActivityObject) {
  1807. common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
  1808. throw new ServerException('Notice asActivityObject created something else.');
  1809. }
  1810. return $object;
  1811. }
  1812. /**
  1813. * Determine which notice, if any, a new notice is in reply to.
  1814. *
  1815. * For conversation tracking, we try to see where this notice fits
  1816. * in the tree. Beware that this may very well give false positives
  1817. * and add replies to wrong threads (if there have been newer posts
  1818. * by the same user as we're replying to).
  1819. *
  1820. * @param Profile $sender Author profile
  1821. * @param string $content Final notice content
  1822. *
  1823. * @return integer ID of replied-to notice, or null for not a reply.
  1824. */
  1825. static function getInlineReplyTo(Profile $sender, $content)
  1826. {
  1827. // Is there an initial @ or T?
  1828. if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
  1829. || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
  1830. $nickname = common_canonical_nickname($match[1]);
  1831. } else {
  1832. return null;
  1833. }
  1834. // Figure out who that is.
  1835. $recipient = common_relative_profile($sender, $nickname, common_sql_now());
  1836. if ($recipient instanceof Profile) {
  1837. // Get their last notice
  1838. $last = $recipient->getCurrentNotice();
  1839. if ($last instanceof Notice) {
  1840. return $last;
  1841. }
  1842. // Maybe in the future we want to handle something else below
  1843. // so don't return getCurrentNotice() immediately.
  1844. }
  1845. return null;
  1846. }
  1847. static function maxContent()
  1848. {
  1849. $contentlimit = common_config('notice', 'contentlimit');
  1850. // null => use global limit (distinct from 0!)
  1851. if (is_null($contentlimit)) {
  1852. $contentlimit = common_config('site', 'textlimit');
  1853. }
  1854. return $contentlimit;
  1855. }
  1856. static function contentTooLong($content)
  1857. {
  1858. $contentlimit = self::maxContent();
  1859. return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
  1860. }
  1861. /**
  1862. * Convenience function for posting a repeat of an existing message.
  1863. *
  1864. * @param Profile $repeater Profile which is doing the repeat
  1865. * @param string $source: posting source key, eg 'web', 'api', etc
  1866. * @return Notice
  1867. *
  1868. * @throws Exception on failure or permission problems
  1869. */
  1870. function repeat(Profile $repeater, $source)
  1871. {
  1872. $author = $this->getProfile();
  1873. // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
  1874. // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
  1875. $content = sprintf(_('RT @%1$s %2$s'),
  1876. $author->getNickname(),
  1877. $this->content);
  1878. $maxlen = self::maxContent();
  1879. if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
  1880. // Web interface and current Twitter API clients will
  1881. // pull the original notice's text, but some older
  1882. // clients and RSS/Atom feeds will see this trimmed text.
  1883. //
  1884. // Unfortunately this is likely to lose tags or URLs
  1885. // at the end of long notices.
  1886. $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
  1887. }
  1888. // Scope is same as this one's
  1889. return self::saveNew($repeater->id,
  1890. $content,
  1891. $source,
  1892. array('repeat_of' => $this->id,
  1893. 'scope' => $this->scope));
  1894. }
  1895. // These are supposed to be in chron order!
  1896. function repeatStream($limit=100)
  1897. {
  1898. $cache = Cache::instance();
  1899. if (empty($cache)) {
  1900. $ids = $this->_repeatStreamDirect($limit);
  1901. } else {
  1902. $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
  1903. if ($idstr !== false) {
  1904. if (empty($idstr)) {
  1905. $ids = array();
  1906. } else {
  1907. $ids = explode(',', $idstr);
  1908. }
  1909. } else {
  1910. $ids = $this->_repeatStreamDirect(100);
  1911. $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
  1912. }
  1913. if ($limit < 100) {
  1914. // We do a max of 100, so slice down to limit
  1915. $ids = array_slice($ids, 0, $limit);
  1916. }
  1917. }
  1918. return NoticeStream::getStreamByIds($ids);
  1919. }
  1920. function _repeatStreamDirect($limit)
  1921. {
  1922. $notice = new Notice();
  1923. $notice->selectAdd(); // clears it
  1924. $notice->selectAdd('id');
  1925. $notice->repeat_of = $this->id;
  1926. $notice->orderBy('created, id'); // NB: asc!
  1927. if (!is_null($limit)) {
  1928. $notice->limit(0, $limit);
  1929. }
  1930. return $notice->fetchAll('id');
  1931. }
  1932. static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
  1933. {
  1934. $options = array();
  1935. if (!empty($location_id) && !empty($location_ns)) {
  1936. $options['location_id'] = $location_id;
  1937. $options['location_ns'] = $location_ns;
  1938. $location = Location::fromId($location_id, $location_ns);
  1939. if ($location instanceof Location) {
  1940. $options['lat'] = $location->lat;
  1941. $options['lon'] = $location->lon;
  1942. }
  1943. } else if (!empty($lat) && !empty($lon)) {
  1944. $options['lat'] = $lat;
  1945. $options['lon'] = $lon;
  1946. $location = Location::fromLatLon($lat, $lon);
  1947. if ($location instanceof Location) {
  1948. $options['location_id'] = $location->location_id;
  1949. $options['location_ns'] = $location->location_ns;
  1950. }
  1951. } else if (!empty($profile)) {
  1952. if (isset($profile->lat) && isset($profile->lon)) {
  1953. $options['lat'] = $profile->lat;
  1954. $options['lon'] = $profile->lon;
  1955. }
  1956. if (isset($profile->location_id) && isset($profile->location_ns)) {
  1957. $options['location_id'] = $profile->location_id;
  1958. $options['location_ns'] = $profile->location_ns;
  1959. }
  1960. }
  1961. return $options;
  1962. }
  1963. function clearAttentions()
  1964. {
  1965. $att = new Attention();
  1966. $att->notice_id = $this->getID();
  1967. if ($att->find()) {
  1968. while ($att->fetch()) {
  1969. // Can't do delete() on the object directly since it won't remove all of it
  1970. $other = clone($att);
  1971. $other->delete();
  1972. }
  1973. }
  1974. }
  1975. function clearReplies()
  1976. {
  1977. $replyNotice = new Notice();
  1978. $replyNotice->reply_to = $this->id;
  1979. //Null any notices that are replies to this notice
  1980. if ($replyNotice->find()) {
  1981. while ($replyNotice->fetch()) {
  1982. $orig = clone($replyNotice);
  1983. $replyNotice->reply_to = null;
  1984. $replyNotice->update($orig);
  1985. }
  1986. }
  1987. // Reply records
  1988. $reply = new Reply();
  1989. $reply->notice_id = $this->id;
  1990. if ($reply->find()) {
  1991. while($reply->fetch()) {
  1992. self::blow('reply:stream:%d', $reply->profile_id);
  1993. $reply->delete();
  1994. }
  1995. }
  1996. $reply->free();
  1997. }
  1998. function clearLocation()
  1999. {
  2000. $loc = new Notice_location();
  2001. $loc->notice_id = $this->id;
  2002. if ($loc->find()) {
  2003. $loc->delete();
  2004. }
  2005. }
  2006. function clearFiles()
  2007. {
  2008. $f2p = new File_to_post();
  2009. $f2p->post_id = $this->id;
  2010. if ($f2p->find()) {
  2011. while ($f2p->fetch()) {
  2012. $f2p->delete();
  2013. }
  2014. }
  2015. // FIXME: decide whether to delete File objects
  2016. // ...and related (actual) files
  2017. }
  2018. function clearRepeats()
  2019. {
  2020. $repeatNotice = new Notice();
  2021. $repeatNotice->repeat_of = $this->id;
  2022. //Null any notices that are repeats of this notice
  2023. if ($repeatNotice->find()) {
  2024. while ($repeatNotice->fetch()) {
  2025. $orig = clone($repeatNotice);
  2026. $repeatNotice->repeat_of = null;
  2027. $repeatNotice->update($orig);
  2028. }
  2029. }
  2030. }
  2031. function clearTags()
  2032. {
  2033. $tag = new Notice_tag();
  2034. $tag->notice_id = $this->id;
  2035. if ($tag->find()) {
  2036. while ($tag->fetch()) {
  2037. self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
  2038. self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
  2039. self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
  2040. self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
  2041. $tag->delete();
  2042. }
  2043. }
  2044. $tag->free();
  2045. }
  2046. function clearGroupInboxes()
  2047. {
  2048. $gi = new Group_inbox();
  2049. $gi->notice_id = $this->id;
  2050. if ($gi->find()) {
  2051. while ($gi->fetch()) {
  2052. self::blow('user_group:notice_ids:%d', $gi->group_id);
  2053. $gi->delete();
  2054. }
  2055. }
  2056. $gi->free();
  2057. }
  2058. function distribute()
  2059. {
  2060. // We always insert for the author so they don't
  2061. // have to wait
  2062. Event::handle('StartNoticeDistribute', array($this));
  2063. // If there's a failure, we want to _force_
  2064. // distribution at this point.
  2065. try {
  2066. $json = json_encode((object)array('id' => $this->getID(),
  2067. 'type' => 'Notice',
  2068. ));
  2069. $qm = QueueManager::get();
  2070. $qm->enqueue($json, 'distrib');
  2071. } catch (Exception $e) {
  2072. // If the exception isn't transient, this
  2073. // may throw more exceptions as DQH does
  2074. // its own enqueueing. So, we ignore them!
  2075. try {
  2076. $handler = new DistribQueueHandler();
  2077. $handler->handle($this);
  2078. } catch (Exception $e) {
  2079. common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
  2080. }
  2081. // Re-throw so somebody smarter can handle it.
  2082. throw $e;
  2083. }
  2084. }
  2085. function insert()
  2086. {
  2087. $result = parent::insert();
  2088. if ($result === false) {
  2089. common_log_db_error($this, 'INSERT', __FILE__);
  2090. // TRANS: Server exception thrown when a stored object entry cannot be saved.
  2091. throw new ServerException('Could not save Notice');
  2092. }
  2093. // Profile::hasRepeated() abuses pkeyGet(), so we
  2094. // have to clear manually
  2095. if (!empty($this->repeat_of)) {
  2096. $c = self::memcache();
  2097. if (!empty($c)) {
  2098. $ck = self::multicacheKey('Notice',
  2099. array('profile_id' => $this->profile_id,
  2100. 'repeat_of' => $this->repeat_of));
  2101. $c->delete($ck);
  2102. }
  2103. }
  2104. // Update possibly ID-dependent columns: URI, conversation
  2105. // (now that INSERT has added the notice's local id)
  2106. $orig = clone($this);
  2107. $changed = false;
  2108. // We can only get here if it's a local notice, since remote notices
  2109. // should've bailed out earlier due to lacking a URI.
  2110. if (empty($this->uri)) {
  2111. $this->uri = sprintf('%s%s=%d:%s=%s',
  2112. TagURI::mint(),
  2113. 'noticeId', $this->id,
  2114. 'objectType', $this->getObjectType(true));
  2115. $changed = true;
  2116. }
  2117. if ($changed && $this->update($orig) === false) {
  2118. common_log_db_error($notice, 'UPDATE', __FILE__);
  2119. // TRANS: Server exception thrown when a notice cannot be updated.
  2120. throw new ServerException(_('Problem saving notice.'));
  2121. }
  2122. $this->blowOnInsert();
  2123. return $result;
  2124. }
  2125. /**
  2126. * Get the source of the notice
  2127. *
  2128. * @return Notice_source $ns A notice source object. 'code' is the only attribute
  2129. * guaranteed to be populated.
  2130. */
  2131. function getSource()
  2132. {
  2133. if (empty($this->source)) {
  2134. return false;
  2135. }
  2136. $ns = new Notice_source();
  2137. switch ($this->source) {
  2138. case 'web':
  2139. case 'xmpp':
  2140. case 'mail':
  2141. case 'omb':
  2142. case 'system':
  2143. case 'api':
  2144. $ns->code = $this->source;
  2145. break;
  2146. default:
  2147. $ns = Notice_source::getKV($this->source);
  2148. if (!$ns) {
  2149. $ns = new Notice_source();
  2150. $ns->code = $this->source;
  2151. $app = Oauth_application::getKV('name', $this->source);
  2152. if ($app) {
  2153. $ns->name = $app->name;
  2154. $ns->url = $app->source_url;
  2155. }
  2156. }
  2157. break;
  2158. }
  2159. return $ns;
  2160. }
  2161. /**
  2162. * Determine whether the notice was locally created
  2163. *
  2164. * @return boolean locality
  2165. */
  2166. public function isLocal()
  2167. {
  2168. $is_local = intval($this->is_local);
  2169. return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
  2170. }
  2171. public function getScope()
  2172. {
  2173. return intval($this->scope);
  2174. }
  2175. public function isRepeat()
  2176. {
  2177. return !empty($this->repeat_of);
  2178. }
  2179. /**
  2180. * Get the list of hash tags saved with this notice.
  2181. *
  2182. * @return array of strings
  2183. */
  2184. public function getTags()
  2185. {
  2186. $tags = array();
  2187. $keypart = sprintf('notice:tags:%d', $this->id);
  2188. $tagstr = self::cacheGet($keypart);
  2189. if ($tagstr !== false) {
  2190. $tags = explode(',', $tagstr);
  2191. } else {
  2192. $tag = new Notice_tag();
  2193. $tag->notice_id = $this->id;
  2194. if ($tag->find()) {
  2195. while ($tag->fetch()) {
  2196. $tags[] = $tag->tag;
  2197. }
  2198. }
  2199. self::cacheSet($keypart, implode(',', $tags));
  2200. }
  2201. return $tags;
  2202. }
  2203. static private function utcDate($dt)
  2204. {
  2205. $dateStr = date('d F Y H:i:s', strtotime($dt));
  2206. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  2207. return $d->format(DATE_W3C);
  2208. }
  2209. /**
  2210. * Look up the creation timestamp for a given notice ID, even
  2211. * if it's been deleted.
  2212. *
  2213. * @param int $id
  2214. * @return mixed string recorded creation timestamp, or false if can't be found
  2215. */
  2216. public static function getAsTimestamp($id)
  2217. {
  2218. if (empty($id)) {
  2219. throw new EmptyIdException('Notice');
  2220. }
  2221. $timestamp = null;
  2222. if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
  2223. // getByID throws exception if $id isn't found
  2224. $notice = Notice::getByID($id);
  2225. $timestamp = $notice->created;
  2226. }
  2227. if (empty($timestamp)) {
  2228. throw new ServerException('No timestamp found for Notice with id=='._ve($id));
  2229. }
  2230. return $timestamp;
  2231. }
  2232. /**
  2233. * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
  2234. * parameter, matching notices posted after the given one (exclusive).
  2235. *
  2236. * If the referenced notice can't be found, will return false.
  2237. *
  2238. * @param int $id
  2239. * @param string $idField
  2240. * @param string $createdField
  2241. * @return mixed string or false if no match
  2242. */
  2243. public static function whereSinceId($id, $idField='id', $createdField='created')
  2244. {
  2245. try {
  2246. $since = Notice::getAsTimestamp($id);
  2247. } catch (Exception $e) {
  2248. return false;
  2249. }
  2250. return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
  2251. }
  2252. /**
  2253. * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
  2254. * parameter, matching notices posted after the given one (exclusive), and
  2255. * if necessary add it to the data object's query.
  2256. *
  2257. * @param DB_DataObject $obj
  2258. * @param int $id
  2259. * @param string $idField
  2260. * @param string $createdField
  2261. * @return mixed string or false if no match
  2262. */
  2263. public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
  2264. {
  2265. $since = self::whereSinceId($id, $idField, $createdField);
  2266. if ($since) {
  2267. $obj->whereAdd($since);
  2268. }
  2269. }
  2270. /**
  2271. * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
  2272. * parameter, matching notices posted before the given one (inclusive).
  2273. *
  2274. * If the referenced notice can't be found, will return false.
  2275. *
  2276. * @param int $id
  2277. * @param string $idField
  2278. * @param string $createdField
  2279. * @return mixed string or false if no match
  2280. */
  2281. public static function whereMaxId($id, $idField='id', $createdField='created')
  2282. {
  2283. try {
  2284. $max = Notice::getAsTimestamp($id);
  2285. } catch (Exception $e) {
  2286. return false;
  2287. }
  2288. return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
  2289. }
  2290. /**
  2291. * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
  2292. * parameter, matching notices posted before the given one (inclusive), and
  2293. * if necessary add it to the data object's query.
  2294. *
  2295. * @param DB_DataObject $obj
  2296. * @param int $id
  2297. * @param string $idField
  2298. * @param string $createdField
  2299. * @return mixed string or false if no match
  2300. */
  2301. public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
  2302. {
  2303. $max = self::whereMaxId($id, $idField, $createdField);
  2304. if ($max) {
  2305. $obj->whereAdd($max);
  2306. }
  2307. }
  2308. function isPublic()
  2309. {
  2310. return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
  2311. ($this->is_local != Notice::GATEWAY));
  2312. }
  2313. /**
  2314. * Check that the given profile is allowed to read, respond to, or otherwise
  2315. * act on this notice.
  2316. *
  2317. * The $scope member is a bitmask of scopes, representing a logical AND of the
  2318. * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
  2319. * "only visible to people who are mentioned in the notice AND are users on this site."
  2320. * Users on the site who are not mentioned in the notice will not be able to see the
  2321. * notice.
  2322. *
  2323. * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
  2324. *
  2325. * @return boolean whether the profile is in the notice's scope
  2326. */
  2327. function inScope($profile)
  2328. {
  2329. if (is_null($profile)) {
  2330. $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
  2331. } else {
  2332. $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
  2333. }
  2334. $result = self::cacheGet($keypart);
  2335. if ($result === false) {
  2336. $bResult = false;
  2337. if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
  2338. $bResult = $this->_inScope($profile);
  2339. Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
  2340. }
  2341. $result = ($bResult) ? 1 : 0;
  2342. self::cacheSet($keypart, $result, 0, 300);
  2343. }
  2344. return ($result == 1) ? true : false;
  2345. }
  2346. protected function _inScope($profile)
  2347. {
  2348. $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
  2349. if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
  2350. return !$this->isHiddenSpam($profile);
  2351. }
  2352. // If there's scope, anon cannot be in scope
  2353. if (empty($profile)) {
  2354. return false;
  2355. }
  2356. // Author is always in scope
  2357. if ($this->profile_id == $profile->id) {
  2358. return true;
  2359. }
  2360. // Only for users on this site
  2361. if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
  2362. return false;
  2363. }
  2364. // Only for users mentioned in the notice
  2365. if ($scope & Notice::ADDRESSEE_SCOPE) {
  2366. $reply = Reply::pkeyGet(array('notice_id' => $this->id,
  2367. 'profile_id' => $profile->id));
  2368. if (!$reply instanceof Reply) {
  2369. return false;
  2370. }
  2371. }
  2372. // Only for members of the given group
  2373. if ($scope & Notice::GROUP_SCOPE) {
  2374. // XXX: just query for the single membership
  2375. $groups = $this->getGroups();
  2376. $foundOne = false;
  2377. foreach ($groups as $group) {
  2378. if ($profile->isMember($group)) {
  2379. $foundOne = true;
  2380. break;
  2381. }
  2382. }
  2383. if (!$foundOne) {
  2384. return false;
  2385. }
  2386. }
  2387. if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
  2388. if (!Subscription::exists($profile, $this->getProfile())) {
  2389. return false;
  2390. }
  2391. }
  2392. return !$this->isHiddenSpam($profile);
  2393. }
  2394. function isHiddenSpam($profile) {
  2395. // Hide posts by silenced users from everyone but moderators.
  2396. if (common_config('notice', 'hidespam')) {
  2397. try {
  2398. $author = $this->getProfile();
  2399. } catch(Exception $e) {
  2400. // If we can't get an author, keep it hidden.
  2401. // XXX: technically not spam, but, whatever.
  2402. return true;
  2403. }
  2404. if ($author->hasRole(Profile_role::SILENCED)) {
  2405. if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
  2406. return true;
  2407. }
  2408. }
  2409. }
  2410. return false;
  2411. }
  2412. public function hasParent()
  2413. {
  2414. try {
  2415. $this->getParent();
  2416. } catch (NoParentNoticeException $e) {
  2417. return false;
  2418. }
  2419. return true;
  2420. }
  2421. public function getParent()
  2422. {
  2423. $reply_to_id = null;
  2424. if (empty($this->reply_to)) {
  2425. throw new NoParentNoticeException($this);
  2426. }
  2427. // The reply_to ID in the table Notice could exist with a number
  2428. // however, the replied to notice might not exist in the database.
  2429. // Thus we need to catch the exception and throw the NoParentNoticeException else
  2430. // the timeline will not display correctly.
  2431. try {
  2432. $reply_to_id = self::getByID($this->reply_to);
  2433. } catch(Exception $e){
  2434. throw new NoParentNoticeException($this);
  2435. }
  2436. return $reply_to_id;
  2437. }
  2438. /**
  2439. * Magic function called at serialize() time.
  2440. *
  2441. * We use this to drop a couple process-specific references
  2442. * from DB_DataObject which can cause trouble in future
  2443. * processes.
  2444. *
  2445. * @return array of variable names to include in serialization.
  2446. */
  2447. function __sleep()
  2448. {
  2449. $vars = parent::__sleep();
  2450. $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
  2451. return array_diff($vars, $skip);
  2452. }
  2453. static function defaultScope()
  2454. {
  2455. $scope = common_config('notice', 'defaultscope');
  2456. if (is_null($scope)) {
  2457. if (common_config('site', 'private')) {
  2458. $scope = 1;
  2459. } else {
  2460. $scope = 0;
  2461. }
  2462. }
  2463. return $scope;
  2464. }
  2465. static function fillProfiles($notices)
  2466. {
  2467. $map = self::getProfiles($notices);
  2468. foreach ($notices as $entry=>$notice) {
  2469. try {
  2470. if (array_key_exists($notice->profile_id, $map)) {
  2471. $notice->_setProfile($map[$notice->profile_id]);
  2472. }
  2473. } catch (NoProfileException $e) {
  2474. common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
  2475. unset($notices[$entry]);
  2476. }
  2477. }
  2478. return array_values($map);
  2479. }
  2480. static function getProfiles(&$notices)
  2481. {
  2482. $ids = array();
  2483. foreach ($notices as $notice) {
  2484. $ids[] = $notice->profile_id;
  2485. }
  2486. $ids = array_unique($ids);
  2487. return Profile::pivotGet('id', $ids);
  2488. }
  2489. static function fillGroups(&$notices)
  2490. {
  2491. $ids = self::_idsOf($notices);
  2492. $gis = Group_inbox::listGet('notice_id', $ids);
  2493. $gids = array();
  2494. foreach ($gis as $id => $gi) {
  2495. foreach ($gi as $g)
  2496. {
  2497. $gids[] = $g->group_id;
  2498. }
  2499. }
  2500. $gids = array_unique($gids);
  2501. $group = User_group::pivotGet('id', $gids);
  2502. foreach ($notices as $notice)
  2503. {
  2504. $grps = array();
  2505. $gi = $gis[$notice->id];
  2506. foreach ($gi as $g) {
  2507. $grps[] = $group[$g->group_id];
  2508. }
  2509. $notice->_setGroups($grps);
  2510. }
  2511. }
  2512. static function _idsOf(array &$notices)
  2513. {
  2514. $ids = array();
  2515. foreach ($notices as $notice) {
  2516. $ids[$notice->id] = true;
  2517. }
  2518. return array_keys($ids);
  2519. }
  2520. static function fillAttachments(&$notices)
  2521. {
  2522. $ids = self::_idsOf($notices);
  2523. $f2pMap = File_to_post::listGet('post_id', $ids);
  2524. $fileIds = array();
  2525. foreach ($f2pMap as $noticeId => $f2ps) {
  2526. foreach ($f2ps as $f2p) {
  2527. $fileIds[] = $f2p->file_id;
  2528. }
  2529. }
  2530. $fileIds = array_unique($fileIds);
  2531. $fileMap = File::pivotGet('id', $fileIds);
  2532. foreach ($notices as $notice)
  2533. {
  2534. $files = array();
  2535. $f2ps = $f2pMap[$notice->id];
  2536. foreach ($f2ps as $f2p) {
  2537. $files[] = $fileMap[$f2p->file_id];
  2538. }
  2539. $notice->_setAttachments($files);
  2540. }
  2541. }
  2542. static function fillReplies(&$notices)
  2543. {
  2544. $ids = self::_idsOf($notices);
  2545. $replyMap = Reply::listGet('notice_id', $ids);
  2546. foreach ($notices as $notice) {
  2547. $replies = $replyMap[$notice->id];
  2548. $ids = array();
  2549. foreach ($replies as $reply) {
  2550. $ids[] = $reply->profile_id;
  2551. }
  2552. $notice->_setReplies($ids);
  2553. }
  2554. }
  2555. static public function beforeSchemaUpdate()
  2556. {
  2557. $table = strtolower(get_called_class());
  2558. $schema = Schema::get();
  2559. $schemadef = $schema->getTableDef($table);
  2560. // 2015-09-04 We move Notice location data to Notice_location
  2561. // First we see if we have to do this at all
  2562. if (!isset($schemadef['fields']['lat'])
  2563. && !isset($schemadef['fields']['lon'])
  2564. && !isset($schemadef['fields']['location_id'])
  2565. && !isset($schemadef['fields']['location_ns'])) {
  2566. // We have already removed the location fields, so no need to migrate.
  2567. return;
  2568. }
  2569. // Then we make sure the Notice_location table is created!
  2570. $schema->ensureTable('notice_location', Notice_location::schemaDef());
  2571. // Then we continue on our road to migration!
  2572. echo "\nFound old $table table, moving location data to 'notice_location' table... (this will probably take a LONG time, but can be aborted and continued)";
  2573. $notice = new Notice();
  2574. $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
  2575. 'WHERE lat IS NOT NULL ' .
  2576. 'OR lon IS NOT NULL ' .
  2577. 'OR location_id IS NOT NULL ' .
  2578. 'OR location_ns IS NOT NULL',
  2579. $schema->quoteIdentifier($table)));
  2580. print "\nFound {$notice->N} notices with location data, inserting";
  2581. while ($notice->fetch()) {
  2582. $notloc = Notice_location::getKV('notice_id', $notice->id);
  2583. if ($notloc instanceof Notice_location) {
  2584. print "-";
  2585. continue;
  2586. }
  2587. $notloc = new Notice_location();
  2588. $notloc->notice_id = $notice->id;
  2589. $notloc->lat= $notice->lat;
  2590. $notloc->lon= $notice->lon;
  2591. $notloc->location_id= $notice->location_id;
  2592. $notloc->location_ns= $notice->location_ns;
  2593. $notloc->insert();
  2594. print ".";
  2595. }
  2596. print "\n";
  2597. }
  2598. }