Notice.php 116 KB

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