Notice.php 116 KB

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