Notice.php 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303
  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; // text
  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' => 'utf8_general_ci'),
  73. 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
  74. 'url' => array('type' => 'text', '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(array('url', 191)), // 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 bool $anchor If false, link to just the conversation root.
  208. *
  209. * @return string URL to conversation
  210. */
  211. public function getConversationUrl(bool $anchor = true): string
  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('created, id');
  1227. $root->limit(0, 1);
  1228. $root->find(true); // true means "fetch first result"
  1229. $root->free();
  1230. return $root;
  1231. }
  1232. if (is_null($profile)) {
  1233. $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
  1234. } else {
  1235. $keypart = sprintf(
  1236. 'notice:conversation_root:%d:%d',
  1237. $this->id,
  1238. $profile->id
  1239. );
  1240. }
  1241. $root = self::cacheGet($keypart);
  1242. if ($root !== false && $root->inScope($profile)) {
  1243. return $root;
  1244. }
  1245. $last = $this;
  1246. while (true) {
  1247. try {
  1248. $parent = $last->getParent();
  1249. if ($parent->inScope($profile)) {
  1250. $last = $parent;
  1251. continue;
  1252. }
  1253. } catch (NoParentNoticeException $e) {
  1254. // Latest notice has no parent
  1255. } catch (NoResultException $e) {
  1256. // Notice was not found, so we can't go further up in the tree.
  1257. // FIXME: Maybe we should do this in a more stable way where deleted
  1258. // notices won't break conversation chains?
  1259. }
  1260. // No parent, or parent out of scope
  1261. $root = $last;
  1262. break;
  1263. }
  1264. self::cacheSet($keypart, $root);
  1265. return $root;
  1266. }
  1267. /**
  1268. * Pull up a full list of local recipients who will be getting
  1269. * this notice in their inbox. Results will be cached, so don't
  1270. * change the input data wily-nilly!
  1271. *
  1272. * @param array $groups optional list of Group objects;
  1273. * if left empty, will be loaded from group_inbox records
  1274. * @param array $recipient optional list of reply profile ids
  1275. * if left empty, will be loaded from reply records
  1276. * @return array associating recipient user IDs with an inbox source constant
  1277. */
  1278. public function whoGets(array $groups = null, array $recipients = null)
  1279. {
  1280. $c = self::memcache();
  1281. if (!empty($c)) {
  1282. $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
  1283. if ($ni !== false) {
  1284. return $ni;
  1285. }
  1286. }
  1287. if (is_null($recipients)) {
  1288. $recipients = $this->getReplies();
  1289. }
  1290. $ni = array();
  1291. // Give plugins a chance to add folks in at start...
  1292. if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
  1293. $users = $this->getSubscribedUsers();
  1294. foreach ($users as $id) {
  1295. $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
  1296. }
  1297. if (is_null($groups)) {
  1298. $groups = $this->getGroups();
  1299. }
  1300. foreach ($groups as $group) {
  1301. $users = $group->getUserMembers();
  1302. foreach ($users as $id) {
  1303. if (!array_key_exists($id, $ni)) {
  1304. $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
  1305. }
  1306. }
  1307. }
  1308. $ptAtts = $this->getAttentionsFromProfileTags();
  1309. foreach ($ptAtts as $key=>$val) {
  1310. if (!array_key_exists($key, $ni)) {
  1311. $ni[$key] = $val;
  1312. }
  1313. }
  1314. foreach ($recipients as $recipient) {
  1315. if (!array_key_exists($recipient, $ni)) {
  1316. $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
  1317. }
  1318. }
  1319. // Exclude any deleted, non-local, or blocking recipients.
  1320. $profile = $this->getProfile();
  1321. $originalProfile = null;
  1322. if ($this->isRepeat()) {
  1323. // Check blocks against the original notice's poster as well.
  1324. $original = Notice::getKV('id', $this->repeat_of);
  1325. if ($original instanceof Notice) {
  1326. $originalProfile = $original->getProfile();
  1327. }
  1328. }
  1329. foreach ($ni as $id => $source) {
  1330. try {
  1331. $user = User::getKV('id', $id);
  1332. if (!$user instanceof User ||
  1333. $user->hasBlocked($profile) ||
  1334. ($originalProfile && $user->hasBlocked($originalProfile))) {
  1335. unset($ni[$id]);
  1336. }
  1337. } catch (UserNoProfileException $e) {
  1338. // User doesn't have a profile; invalid; skip them.
  1339. unset($ni[$id]);
  1340. }
  1341. }
  1342. // Give plugins a chance to filter out...
  1343. Event::handle('EndNoticeWhoGets', array($this, &$ni));
  1344. }
  1345. if (!empty($c)) {
  1346. // XXX: pack this data better
  1347. $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
  1348. }
  1349. return $ni;
  1350. }
  1351. public function getSubscribedUsers()
  1352. {
  1353. $user = new User();
  1354. $user->query(sprintf(
  1355. 'SELECT id FROM %1$s INNER JOIN subscription ' .
  1356. 'ON %1$s.id = subscription.subscriber ' .
  1357. 'WHERE subscription.subscribed = %2$d ',
  1358. $user->escapedTableName(),
  1359. $this->profile_id
  1360. ));
  1361. $ids = [];
  1362. while ($user->fetch()) {
  1363. $ids[] = $user->id;
  1364. }
  1365. $user->free();
  1366. return $ids;
  1367. }
  1368. public function getProfileTags()
  1369. {
  1370. $ptags = array();
  1371. try {
  1372. $profile = $this->getProfile();
  1373. $list = $profile->getOtherTags($profile);
  1374. while ($list->fetch()) {
  1375. $ptags[] = clone($list);
  1376. }
  1377. } catch (Exception $e) {
  1378. common_log(LOG_ERR, "Error during Notice->getProfileTags() for id=={$this->getID()}: {$e->getMessage()}");
  1379. }
  1380. return $ptags;
  1381. }
  1382. public function getAttentionsFromProfileTags()
  1383. {
  1384. $ni = array();
  1385. $ptags = $this->getProfileTags();
  1386. foreach ($ptags as $ptag) {
  1387. $users = $ptag->getUserSubscribers();
  1388. foreach ($users as $id) {
  1389. $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
  1390. }
  1391. }
  1392. return $ni;
  1393. }
  1394. /**
  1395. * Record this notice to the given group inboxes for delivery.
  1396. * Overrides the regular parsing of !group markup.
  1397. *
  1398. * @param string $group_ids
  1399. * @fixme might prefer URIs as identifiers, as for replies?
  1400. * best with generalizations on user_group to support
  1401. * remote groups better.
  1402. */
  1403. public function saveKnownGroups(array $group_ids)
  1404. {
  1405. $groups = array();
  1406. foreach (array_unique($group_ids) as $id) {
  1407. $group = User_group::getKV('id', $id);
  1408. if ($group instanceof User_group) {
  1409. common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
  1410. $result = $this->addToGroupInbox($group);
  1411. if (!$result) {
  1412. common_log_db_error($gi, 'INSERT', __FILE__);
  1413. }
  1414. if (common_config('group', 'addtag')) {
  1415. // we automatically add a tag for every group name, too
  1416. common_debug('Adding hashtag matching group nickname: '._ve($group->getNickname()));
  1417. $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->getNickname()),
  1418. 'notice_id' => $this->getID()));
  1419. if (is_null($tag)) {
  1420. $this->saveTag($group->getNickname());
  1421. }
  1422. }
  1423. $groups[] = clone($group);
  1424. } else {
  1425. common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
  1426. }
  1427. }
  1428. return $groups;
  1429. }
  1430. public function addToGroupInbox(User_group $group)
  1431. {
  1432. $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
  1433. 'notice_id' => $this->id));
  1434. if (!$gi instanceof Group_inbox) {
  1435. $gi = new Group_inbox();
  1436. $gi->group_id = $group->id;
  1437. $gi->notice_id = $this->id;
  1438. $gi->created = $this->created;
  1439. $result = $gi->insert();
  1440. if (!$result) {
  1441. common_log_db_error($gi, 'INSERT', __FILE__);
  1442. // TRANS: Server exception thrown when an update for a group inbox fails.
  1443. throw new ServerException(_('Problem saving group inbox.'));
  1444. }
  1445. self::blow('user_group:notice_ids:%d', $gi->group_id);
  1446. }
  1447. return true;
  1448. }
  1449. public function saveAttentions(array $uris)
  1450. {
  1451. foreach ($uris as $uri=>$type) {
  1452. try {
  1453. $target = Profile::fromUri($uri);
  1454. } catch (UnknownUriException $e) {
  1455. common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
  1456. continue;
  1457. }
  1458. try {
  1459. $this->saveAttention($target);
  1460. } catch (AlreadyFulfilledException $e) {
  1461. common_debug('Attention already exists: ' . var_export($e->getMessage(), true));
  1462. } catch (Exception $e) {
  1463. common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
  1464. }
  1465. }
  1466. }
  1467. /**
  1468. * Saves an attention for a profile (user or group) which means
  1469. * it shows up in their home feed and such.
  1470. */
  1471. public function saveAttention(Profile $target, $reason = null)
  1472. {
  1473. if ($target->isGroup()) {
  1474. // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
  1475. // legacy notification method, will still be in use for quite a while I think
  1476. $this->addToGroupInbox($target->getGroup());
  1477. } else {
  1478. if ($target->hasBlocked($this->getProfile())) {
  1479. common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
  1480. return false;
  1481. }
  1482. }
  1483. if ($target->isLocal()) {
  1484. // legacy notification method, will still be in use for quite a while I think
  1485. $this->saveReply($target->getID());
  1486. }
  1487. $att = Attention::saveNew($this, $target, $reason);
  1488. return true;
  1489. }
  1490. /**
  1491. * Save reply records indicating that this notice needs to be
  1492. * delivered to the local users with the given URIs.
  1493. *
  1494. * Since this is expected to be used when saving foreign-sourced
  1495. * messages, we won't deliver to any remote targets as that's the
  1496. * source service's responsibility.
  1497. *
  1498. * Mail notifications etc will be handled later.
  1499. *
  1500. * @param array $uris Array of unique identifier URIs for recipients
  1501. */
  1502. public function saveKnownReplies(array $uris)
  1503. {
  1504. if (empty($uris)) {
  1505. return;
  1506. }
  1507. $sender = $this->getProfile();
  1508. foreach (array_unique($uris) as $uri) {
  1509. try {
  1510. $profile = Profile::fromUri($uri);
  1511. } catch (UnknownUriException $e) {
  1512. common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
  1513. continue;
  1514. }
  1515. if ($profile->hasBlocked($sender)) {
  1516. common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
  1517. continue;
  1518. }
  1519. $this->saveReply($profile->getID());
  1520. self::blow('reply:stream:%d', $profile->getID());
  1521. }
  1522. }
  1523. /**
  1524. * Pull @-replies from this message's content in StatusNet markup format
  1525. * and save reply records indicating that this message needs to be
  1526. * delivered to those users.
  1527. *
  1528. * Mail notifications to local profiles will be sent later.
  1529. *
  1530. * @return array of integer profile IDs
  1531. */
  1532. public function saveReplies()
  1533. {
  1534. $sender = $this->getProfile();
  1535. $replied = array();
  1536. // If it's a reply, save for the replied-to author
  1537. try {
  1538. $parent = $this->getParent();
  1539. $parentauthor = $parent->getProfile();
  1540. $this->saveReply($parentauthor->getID());
  1541. $replied[$parentauthor->getID()] = 1;
  1542. self::blow('reply:stream:%d', $parentauthor->getID());
  1543. } catch (NoParentNoticeException $e) {
  1544. // Not a reply, since it has no parent!
  1545. $parent = null;
  1546. } catch (NoResultException $e) {
  1547. // Parent notice was probably deleted
  1548. $parent = null;
  1549. }
  1550. // @todo ideally this parser information would only
  1551. // be calculated once.
  1552. $mentions = common_find_mentions($this->content, $sender, $parent);
  1553. foreach ($mentions as $mention) {
  1554. foreach ($mention['mentioned'] as $mentioned) {
  1555. // skip if they're already covered
  1556. if (array_key_exists($mentioned->id, $replied)) {
  1557. continue;
  1558. }
  1559. // Don't save replies from blocked profile to local user
  1560. if ($mentioned->hasBlocked($sender)) {
  1561. continue;
  1562. }
  1563. $this->saveReply($mentioned->id);
  1564. $replied[$mentioned->id] = 1;
  1565. self::blow('reply:stream:%d', $mentioned->id);
  1566. }
  1567. }
  1568. $recipientIds = array_keys($replied);
  1569. return $recipientIds;
  1570. }
  1571. public function saveReply($profileId)
  1572. {
  1573. $reply = new Reply();
  1574. $reply->notice_id = $this->id;
  1575. $reply->profile_id = $profileId;
  1576. $reply->modified = $this->created;
  1577. $reply->insert();
  1578. return $reply;
  1579. }
  1580. protected $_attentionids = array();
  1581. /**
  1582. * Pull the complete list of known activity context attentions for this notice.
  1583. *
  1584. * @return array of integer profile ids (also group profiles)
  1585. */
  1586. public function getAttentionProfileIDs()
  1587. {
  1588. if (!isset($this->_attentionids[$this->getID()])) {
  1589. $atts = Attention::multiGet('notice_id', array($this->getID()));
  1590. // (array)null means empty array
  1591. $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
  1592. }
  1593. return $this->_attentionids[$this->getID()];
  1594. }
  1595. protected $_replies = array();
  1596. /**
  1597. * Pull the complete list of @-mentioned profile IDs for this notice.
  1598. *
  1599. * @return array of integer profile ids
  1600. */
  1601. public function getReplies()
  1602. {
  1603. if (!isset($this->_replies[$this->getID()])) {
  1604. $mentions = Reply::multiGet('notice_id', array($this->getID()));
  1605. $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
  1606. }
  1607. return $this->_replies[$this->getID()];
  1608. }
  1609. public function _setReplies($replies)
  1610. {
  1611. $this->_replies[$this->getID()] = $replies;
  1612. }
  1613. /**
  1614. * Pull the complete list of @-reply targets for this notice.
  1615. *
  1616. * @return array of Profiles
  1617. */
  1618. public function getAttentionProfiles()
  1619. {
  1620. $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
  1621. $profiles = Profile::multiGet('id', (array)$ids);
  1622. return $profiles->fetchAll();
  1623. }
  1624. /**
  1625. * Send e-mail notifications to local @-reply targets.
  1626. *
  1627. * Replies must already have been saved; this is expected to be run
  1628. * from the distrib queue handler.
  1629. */
  1630. public function sendReplyNotifications()
  1631. {
  1632. // Don't send reply notifications for repeats
  1633. if ($this->isRepeat()) {
  1634. return array();
  1635. }
  1636. $recipientIds = $this->getReplies();
  1637. if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
  1638. require_once INSTALLDIR . '/lib/util/mail.php';
  1639. foreach ($recipientIds as $recipientId) {
  1640. try {
  1641. $user = User::getByID($recipientId);
  1642. mail_notify_attn($user->getProfile(), $this);
  1643. } catch (NoResultException $e) {
  1644. // No such user
  1645. }
  1646. }
  1647. Event::handle('EndNotifyMentioned', array($this, $recipientIds));
  1648. }
  1649. }
  1650. /**
  1651. * Pull list of Profile IDs of groups this notice addresses.
  1652. *
  1653. * @return array of Group _profile_ IDs
  1654. */
  1655. public function getGroupProfileIDs()
  1656. {
  1657. $ids = array();
  1658. foreach ($this->getGroups() as $group) {
  1659. $ids[] = $group->profile_id;
  1660. }
  1661. return $ids;
  1662. }
  1663. /**
  1664. * Pull list of groups this notice needs to be delivered to,
  1665. * as previously recorded by saveKnownGroups().
  1666. *
  1667. * @return array of Group objects
  1668. */
  1669. protected $_groups = array();
  1670. public function getGroups()
  1671. {
  1672. // Don't save groups for repeats
  1673. if (!empty($this->repeat_of)) {
  1674. return array();
  1675. }
  1676. if (isset($this->_groups[$this->id])) {
  1677. return $this->_groups[$this->id];
  1678. }
  1679. $gis = Group_inbox::listGet('notice_id', array($this->id));
  1680. $ids = [];
  1681. foreach ($gis[$this->id] as $gi) {
  1682. $ids[] = $gi->group_id;
  1683. }
  1684. $groups = User_group::multiGet('id', $ids);
  1685. $this->_groups[$this->id] = $groups->fetchAll();
  1686. return $this->_groups[$this->id];
  1687. }
  1688. public function _setGroups($groups)
  1689. {
  1690. $this->_groups[$this->id] = $groups;
  1691. }
  1692. /**
  1693. * Convert a notice into an activity for export.
  1694. *
  1695. * @param Profile $scoped The currently logged in/scoped profile
  1696. *
  1697. * @return Activity activity object representing this Notice.
  1698. * @throws ClientException
  1699. * @throws ServerException
  1700. */
  1701. public function asActivity(Profile $scoped = null)
  1702. {
  1703. $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
  1704. if ($act instanceof Activity) {
  1705. return $act;
  1706. }
  1707. $act = new Activity();
  1708. if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
  1709. $act->id = $this->uri;
  1710. $act->time = strtotime($this->created);
  1711. try {
  1712. $act->link = $this->getUrl();
  1713. } catch (InvalidUrlException $e) {
  1714. // The notice is probably a share or similar, which don't
  1715. // have a representational URL of their own.
  1716. }
  1717. $act->content = common_xml_safe_str($this->getRendered());
  1718. $profile = $this->getProfile();
  1719. $act->actor = $profile->asActivityObject();
  1720. $act->actor->extra[] = $profile->profileInfo($scoped);
  1721. $act->verb = $this->verb;
  1722. if (!$this->repeat_of) {
  1723. $act->objects[] = $this->asActivityObject();
  1724. }
  1725. // XXX: should this be handled by default processing for object entry?
  1726. // Categories
  1727. $tags = $this->getTags();
  1728. foreach ($tags as $tag) {
  1729. $cat = new AtomCategory();
  1730. $cat->term = $tag;
  1731. $act->categories[] = $cat;
  1732. }
  1733. // Enclosures
  1734. // XXX: use Atom Media and/or File activity objects instead
  1735. $attachments = $this->attachments();
  1736. foreach ($attachments as $attachment) {
  1737. // Include local attachments in Activity
  1738. if (!empty($attachment->filename)) {
  1739. $act->enclosures[] = $attachment->getEnclosure();
  1740. }
  1741. }
  1742. $ctx = new ActivityContext();
  1743. try {
  1744. $reply = $this->getParent();
  1745. $ctx->replyToID = $reply->getUri();
  1746. $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
  1747. } catch (NoParentNoticeException $e) {
  1748. // This is not a reply to something
  1749. } catch (NoResultException $e) {
  1750. // Parent notice was probably deleted
  1751. }
  1752. try {
  1753. $ctx->location = Notice_location::locFromStored($this);
  1754. } catch (ServerException $e) {
  1755. $ctx->location = null;
  1756. }
  1757. $conv = null;
  1758. if (!empty($this->conversation)) {
  1759. $conv = Conversation::getKV('id', $this->conversation);
  1760. if ($conv instanceof Conversation) {
  1761. $ctx->conversation = $conv->uri;
  1762. $ctx->conversation_url = $conv->url;
  1763. }
  1764. }
  1765. // This covers the legacy getReplies and getGroups too which get their data
  1766. // from entries stored via Notice::saveNew (which we want to move away from)...
  1767. foreach ($this->getAttentionProfiles() as $target) {
  1768. // User and group profiles which get the attention of this notice
  1769. $ctx->attention[$target->getUri()] = $target->getObjectType();
  1770. }
  1771. switch ($this->scope) {
  1772. case Notice::PUBLIC_SCOPE:
  1773. $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
  1774. break;
  1775. case Notice::FOLLOWER_SCOPE:
  1776. $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
  1777. $ctx->attention[$surl] = ActivityObject::COLLECTION;
  1778. break;
  1779. }
  1780. $act->context = $ctx;
  1781. $source = $this->getSource();
  1782. if ($source instanceof Notice_source) {
  1783. $act->generator = ActivityObject::fromNoticeSource($source);
  1784. }
  1785. // Source
  1786. $atom_feed = $profile->getAtomFeed();
  1787. if (!empty($atom_feed)) {
  1788. $act->source = new ActivitySource();
  1789. // XXX: we should store the actual feed ID
  1790. $act->source->id = $atom_feed;
  1791. // XXX: we should store the actual feed title
  1792. $act->source->title = $profile->getBestName();
  1793. $act->source->links['alternate'] = $profile->profileurl;
  1794. $act->source->links['self'] = $atom_feed;
  1795. $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
  1796. $notice = $profile->getCurrentNotice();
  1797. if ($notice instanceof Notice) {
  1798. $act->source->updated = self::utcDate($notice->created);
  1799. }
  1800. $user = User::getKV('id', $profile->id);
  1801. if ($user instanceof User) {
  1802. $act->source->links['license'] = common_config('license', 'url');
  1803. }
  1804. }
  1805. try {
  1806. $act->selfLink = $this->getSelfLink();
  1807. } catch (InvalidUrlException $e) {
  1808. $act->selfLink = null;
  1809. }
  1810. if ($this->isLocal()) {
  1811. $act->editLink = $act->selfLink;
  1812. }
  1813. Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
  1814. }
  1815. self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
  1816. return $act;
  1817. }
  1818. // This has gotten way too long. Needs to be sliced up into functional bits
  1819. // or ideally exported to a utility class.
  1820. public function asAtomEntry($namespace = false, $source = false, $author = true, Profile $scoped = null)
  1821. {
  1822. $act = $this->asActivity($scoped);
  1823. $act->extra[] = $this->noticeInfo($scoped);
  1824. return $act->asString($namespace, $author, $source);
  1825. }
  1826. /**
  1827. * Extra notice info for atom entries
  1828. *
  1829. * Clients use some extra notice info in the atom stream.
  1830. * This gives it to them.
  1831. *
  1832. * @param Profile $scoped The currently logged in/scoped profile
  1833. *
  1834. * @return array representation of <statusnet:notice_info> element
  1835. */
  1836. public function noticeInfo(Profile $scoped = null)
  1837. {
  1838. // local notice ID (useful to clients for ordering)
  1839. $noticeInfoAttr = array('local_id' => $this->id);
  1840. // notice source
  1841. $ns = $this->getSource();
  1842. if ($ns instanceof Notice_source) {
  1843. $noticeInfoAttr['source'] = $ns->code;
  1844. if (!empty($ns->url)) {
  1845. $noticeInfoAttr['source_link'] = $ns->url;
  1846. if (!empty($ns->name)) {
  1847. $noticeInfoAttr['source'] = $ns->name;
  1848. }
  1849. }
  1850. }
  1851. // favorite and repeated
  1852. if ($scoped instanceof Profile) {
  1853. $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
  1854. }
  1855. if (!empty($this->repeat_of)) {
  1856. $noticeInfoAttr['repeat_of'] = $this->repeat_of;
  1857. }
  1858. Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
  1859. return array('statusnet:notice_info', $noticeInfoAttr, null);
  1860. }
  1861. /**
  1862. * Returns an XML string fragment with a reference to a notice as an
  1863. * Activity Streams noun object with the given element type.
  1864. *
  1865. * Assumes that 'activity' namespace has been previously defined.
  1866. *
  1867. * @param string $element one of 'subject', 'object', 'target'
  1868. * @return string
  1869. */
  1870. public function asActivityNoun($element)
  1871. {
  1872. $noun = $this->asActivityObject();
  1873. return $noun->asString('activity:' . $element);
  1874. }
  1875. public function asActivityObject()
  1876. {
  1877. $object = new ActivityObject();
  1878. if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
  1879. $object->type = $this->object_type ?: ActivityObject::NOTE;
  1880. $object->id = $this->getUri();
  1881. //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
  1882. $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
  1883. $object->content = $this->getRendered();
  1884. $object->link = $this->getUrl();
  1885. try {
  1886. $object->selfLink = $this->getSelfLink();
  1887. } catch (InvalidUrlException $e) {
  1888. $object->selfLink = null;
  1889. }
  1890. $object->extra[] = array('statusnet:notice_id', null, $this->id);
  1891. Event::handle('EndActivityObjectFromNotice', array($this, &$object));
  1892. }
  1893. if (!$object instanceof ActivityObject) {
  1894. common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
  1895. throw new ServerException('Notice asActivityObject created something else.');
  1896. }
  1897. return $object;
  1898. }
  1899. /**
  1900. * Determine which notice, if any, a new notice is in reply to.
  1901. *
  1902. * For conversation tracking, we try to see where this notice fits
  1903. * in the tree. Beware that this may very well give false positives
  1904. * and add replies to wrong threads (if there have been newer posts
  1905. * by the same user as we're replying to).
  1906. *
  1907. * @param Profile $sender Author profile
  1908. * @param string $content Final notice content
  1909. *
  1910. * @return integer ID of replied-to notice, or null for not a reply.
  1911. */
  1912. public static function getInlineReplyTo(Profile $sender, $content)
  1913. {
  1914. // Is there an initial @ or T?
  1915. if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
  1916. || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
  1917. $nickname = common_canonical_nickname($match[1]);
  1918. } else {
  1919. return null;
  1920. }
  1921. // Figure out who that is.
  1922. $recipient = common_relative_profile($sender, $nickname, common_sql_now());
  1923. if ($recipient instanceof Profile) {
  1924. // Get their last notice
  1925. $last = $recipient->getCurrentNotice();
  1926. if ($last instanceof Notice) {
  1927. return $last;
  1928. }
  1929. // Maybe in the future we want to handle something else below
  1930. // so don't return getCurrentNotice() immediately.
  1931. }
  1932. return null;
  1933. }
  1934. public static function maxContent()
  1935. {
  1936. $contentlimit = common_config('notice', 'contentlimit');
  1937. // null => use global limit (distinct from 0!)
  1938. if (is_null($contentlimit)) {
  1939. $contentlimit = common_config('site', 'textlimit');
  1940. }
  1941. return $contentlimit;
  1942. }
  1943. public static function contentTooLong($content)
  1944. {
  1945. $contentlimit = self::maxContent();
  1946. return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
  1947. }
  1948. /**
  1949. * Convenience function for posting a repeat of an existing message.
  1950. *
  1951. * @param Profile $repeater Profile which is doing the repeat
  1952. * @param string $source: posting source key, eg 'web', 'api', etc
  1953. * @return Notice
  1954. *
  1955. * @throws Exception on failure or permission problems
  1956. */
  1957. public function repeat(Profile $repeater, $source)
  1958. {
  1959. $author = $this->getProfile();
  1960. // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
  1961. // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
  1962. $content = sprintf(
  1963. _('RT @%1$s %2$s'),
  1964. $author->getNickname(),
  1965. $this->content
  1966. );
  1967. $maxlen = self::maxContent();
  1968. if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
  1969. // Web interface and current Twitter API clients will
  1970. // pull the original notice's text, but some older
  1971. // clients and RSS/Atom feeds will see this trimmed text.
  1972. //
  1973. // Unfortunately this is likely to lose tags or URLs
  1974. // at the end of long notices.
  1975. $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
  1976. }
  1977. // Scope is same as this one's
  1978. return self::saveNew(
  1979. $repeater->id,
  1980. $content,
  1981. $source,
  1982. ['repeat_of' => $this->id, 'scope' => $this->scope]
  1983. );
  1984. }
  1985. // These are supposed to be in chron order!
  1986. public function repeatStream($limit = 100)
  1987. {
  1988. $cache = Cache::instance();
  1989. if (empty($cache)) {
  1990. $ids = $this->_repeatStreamDirect($limit);
  1991. } else {
  1992. $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
  1993. if ($idstr !== false) {
  1994. if (!empty($idstr)) {
  1995. $ids = explode(',', $idstr);
  1996. } else {
  1997. $ids = [];
  1998. }
  1999. } else {
  2000. $ids = $this->_repeatStreamDirect(100);
  2001. $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
  2002. }
  2003. if ($limit < 100) {
  2004. // We do a max of 100, so slice down to limit
  2005. $ids = array_slice($ids, 0, $limit);
  2006. }
  2007. }
  2008. return NoticeStream::getStreamByIds($ids);
  2009. }
  2010. public function _repeatStreamDirect($limit)
  2011. {
  2012. $notice = new Notice();
  2013. $notice->selectAdd(); // clears it
  2014. $notice->selectAdd('id');
  2015. $notice->repeat_of = $this->id;
  2016. $notice->orderBy('created, id'); // NB: asc!
  2017. if (!is_null($limit)) {
  2018. $notice->limit(0, $limit);
  2019. }
  2020. return $notice->fetchAll('id');
  2021. }
  2022. public static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
  2023. {
  2024. $options = array();
  2025. if (!empty($location_id) && !empty($location_ns)) {
  2026. $options['location_id'] = $location_id;
  2027. $options['location_ns'] = $location_ns;
  2028. $location = Location::fromId($location_id, $location_ns);
  2029. if ($location instanceof Location) {
  2030. $options['lat'] = $location->lat;
  2031. $options['lon'] = $location->lon;
  2032. }
  2033. } elseif (!empty($lat) && !empty($lon)) {
  2034. $options['lat'] = $lat;
  2035. $options['lon'] = $lon;
  2036. $location = Location::fromLatLon($lat, $lon);
  2037. if ($location instanceof Location) {
  2038. $options['location_id'] = $location->location_id;
  2039. $options['location_ns'] = $location->location_ns;
  2040. }
  2041. } elseif (!empty($profile)) {
  2042. if (isset($profile->lat) && isset($profile->lon)) {
  2043. $options['lat'] = $profile->lat;
  2044. $options['lon'] = $profile->lon;
  2045. }
  2046. if (isset($profile->location_id) && isset($profile->location_ns)) {
  2047. $options['location_id'] = $profile->location_id;
  2048. $options['location_ns'] = $profile->location_ns;
  2049. }
  2050. }
  2051. return $options;
  2052. }
  2053. public function clearAttentions()
  2054. {
  2055. $att = new Attention();
  2056. $att->notice_id = $this->getID();
  2057. if ($att->find()) {
  2058. while ($att->fetch()) {
  2059. // Can't do delete() on the object directly since it won't remove all of it
  2060. $other = clone($att);
  2061. $other->delete();
  2062. }
  2063. }
  2064. }
  2065. public function clearReplies()
  2066. {
  2067. $replyNotice = new Notice();
  2068. $replyNotice->reply_to = $this->id;
  2069. //Null any notices that are replies to this notice
  2070. if ($replyNotice->find()) {
  2071. while ($replyNotice->fetch()) {
  2072. $orig = clone($replyNotice);
  2073. $replyNotice->reply_to = $replyNotice->sqlValue('NULL');
  2074. $replyNotice->update($orig);
  2075. }
  2076. }
  2077. // Reply records
  2078. $reply = new Reply();
  2079. $reply->notice_id = $this->id;
  2080. if ($reply->find()) {
  2081. while ($reply->fetch()) {
  2082. self::blow('reply:stream:%d', $reply->profile_id);
  2083. $reply->delete();
  2084. }
  2085. }
  2086. $reply->free();
  2087. }
  2088. public function clearLocation()
  2089. {
  2090. $loc = new Notice_location();
  2091. $loc->notice_id = $this->id;
  2092. if ($loc->find()) {
  2093. $loc->delete();
  2094. }
  2095. }
  2096. private function clearPrefs(): void
  2097. {
  2098. $prefs = new Notice_prefs();
  2099. $prefs->notice_id = $this->id;
  2100. if ($prefs->find()) {
  2101. $prefs->delete();
  2102. }
  2103. }
  2104. public function clearFiles()
  2105. {
  2106. $f2p = new File_to_post();
  2107. $f2p->post_id = $this->id;
  2108. if ($f2p->find()) {
  2109. while ($f2p->fetch()) {
  2110. $f2p->delete();
  2111. }
  2112. }
  2113. // FIXME: decide whether to delete File objects
  2114. // ...and related (actual) files
  2115. }
  2116. public function clearRepeats()
  2117. {
  2118. $repeatNotice = new Notice();
  2119. $repeatNotice->repeat_of = $this->id;
  2120. //Null any notices that are repeats of this notice
  2121. if ($repeatNotice->find()) {
  2122. while ($repeatNotice->fetch()) {
  2123. $orig = clone($repeatNotice);
  2124. $repeatNotice->repeat_of = $repeatNotice->sqlValue('NULL');
  2125. $repeatNotice->update($orig);
  2126. }
  2127. }
  2128. }
  2129. public function clearTags()
  2130. {
  2131. $tag = new Notice_tag();
  2132. $tag->notice_id = $this->id;
  2133. if ($tag->find()) {
  2134. while ($tag->fetch()) {
  2135. self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
  2136. self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
  2137. self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
  2138. self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
  2139. $tag->delete();
  2140. }
  2141. }
  2142. $tag->free();
  2143. }
  2144. public function clearGroupInboxes()
  2145. {
  2146. $gi = new Group_inbox();
  2147. $gi->notice_id = $this->id;
  2148. if ($gi->find()) {
  2149. while ($gi->fetch()) {
  2150. self::blow('user_group:notice_ids:%d', $gi->group_id);
  2151. $gi->delete();
  2152. }
  2153. }
  2154. $gi->free();
  2155. }
  2156. public function distribute()
  2157. {
  2158. // We always insert for the author so they don't
  2159. // have to wait
  2160. Event::handle('StartNoticeDistribute', array($this));
  2161. // If there's a failure, we want to _force_
  2162. // distribution at this point.
  2163. try {
  2164. $qm = QueueManager::get();
  2165. $qm->enqueue($this, 'distrib');
  2166. } catch (Exception $e) {
  2167. // If the exception isn't transient, this
  2168. // may throw more exceptions as DQH does
  2169. // its own enqueueing. So, we ignore them!
  2170. try {
  2171. $handler = new DistribQueueHandler();
  2172. $handler->handle($this);
  2173. } catch (Exception $e) {
  2174. common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
  2175. }
  2176. // Re-throw so somebody smarter can handle it.
  2177. throw $e;
  2178. }
  2179. }
  2180. public function insert()
  2181. {
  2182. $result = parent::insert();
  2183. if ($result === false) {
  2184. common_log_db_error($this, 'INSERT', __FILE__);
  2185. // TRANS: Server exception thrown when a stored object entry cannot be saved.
  2186. throw new ServerException('Could not save Notice');
  2187. }
  2188. // Profile::hasRepeated() abuses pkeyGet(), so we
  2189. // have to clear manually
  2190. if (!empty($this->repeat_of)) {
  2191. $c = self::memcache();
  2192. if (!empty($c)) {
  2193. $ck = self::multicacheKey(
  2194. 'Notice',
  2195. ['profile_id' => $this->profile_id, 'repeat_of' => $this->repeat_of]
  2196. );
  2197. $c->delete($ck);
  2198. }
  2199. }
  2200. // Update possibly ID-dependent columns: URI, conversation
  2201. // (now that INSERT has added the notice's local id)
  2202. $orig = clone($this);
  2203. $changed = false;
  2204. // We can only get here if it's a local notice, since remote notices
  2205. // should've bailed out earlier due to lacking a URI.
  2206. if (empty($this->uri)) {
  2207. $this->uri = sprintf(
  2208. '%s%s=%d:%s=%s',
  2209. TagURI::mint(),
  2210. 'noticeId',
  2211. $this->id,
  2212. 'objectType',
  2213. $this->getObjectType(true)
  2214. );
  2215. $changed = true;
  2216. }
  2217. if ($changed && $this->update($orig) === false) {
  2218. common_log_db_error($notice, 'UPDATE', __FILE__);
  2219. // TRANS: Server exception thrown when a notice cannot be updated.
  2220. throw new ServerException(_('Problem saving notice.'));
  2221. }
  2222. $this->blowOnInsert();
  2223. return $result;
  2224. }
  2225. /**
  2226. * Get the source of the notice
  2227. *
  2228. * @return Notice_source $ns A notice source object. 'code' is the only attribute
  2229. * guaranteed to be populated.
  2230. */
  2231. public function getSource()
  2232. {
  2233. if (empty($this->source)) {
  2234. return false;
  2235. }
  2236. $ns = new Notice_source();
  2237. switch ($this->source) {
  2238. case 'web':
  2239. case 'xmpp':
  2240. case 'mail':
  2241. case 'omb':
  2242. case 'system':
  2243. case 'api':
  2244. $ns->code = $this->source;
  2245. break;
  2246. default:
  2247. $ns = Notice_source::getKV($this->source);
  2248. if (!$ns) {
  2249. $ns = new Notice_source();
  2250. $ns->code = $this->source;
  2251. $app = Oauth_application::getKV('name', $this->source);
  2252. if ($app) {
  2253. $ns->name = $app->name;
  2254. $ns->url = $app->source_url;
  2255. }
  2256. }
  2257. break;
  2258. }
  2259. return $ns;
  2260. }
  2261. /**
  2262. * Determine whether the notice was locally created
  2263. *
  2264. * @return boolean locality
  2265. */
  2266. public function isLocal()
  2267. {
  2268. $is_local = intval($this->is_local);
  2269. return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
  2270. }
  2271. public function getScope()
  2272. {
  2273. return intval($this->scope);
  2274. }
  2275. public function isRepeat()
  2276. {
  2277. return !empty($this->repeat_of);
  2278. }
  2279. public function isRepeated()
  2280. {
  2281. $n = new Notice();
  2282. $n->repeat_of = $this->getID();
  2283. return $n->find() && $n->N > 0;
  2284. }
  2285. /**
  2286. * Get the list of hash tags saved with this notice.
  2287. *
  2288. * @return array of strings
  2289. */
  2290. public function getTags()
  2291. {
  2292. $tags = array();
  2293. $keypart = sprintf('notice:tags:%d', $this->id);
  2294. $tagstr = self::cacheGet($keypart);
  2295. if ($tagstr !== false) {
  2296. $tags = explode(',', $tagstr);
  2297. } else {
  2298. $tag = new Notice_tag();
  2299. $tag->notice_id = $this->id;
  2300. if ($tag->find()) {
  2301. while ($tag->fetch()) {
  2302. $tags[] = $tag->tag;
  2303. }
  2304. }
  2305. self::cacheSet($keypart, implode(',', $tags));
  2306. }
  2307. return $tags;
  2308. }
  2309. private static function utcDate($dt)
  2310. {
  2311. $dateStr = date('d F Y H:i:s', strtotime($dt));
  2312. $d = new DateTime($dateStr, new DateTimeZone('UTC'));
  2313. return $d->format(DATE_W3C);
  2314. }
  2315. /**
  2316. * Look up the creation timestamp for a given notice ID, even
  2317. * if it's been deleted.
  2318. *
  2319. * @param int $id
  2320. * @return mixed string recorded creation timestamp, or false if can't be found
  2321. */
  2322. public static function getAsTimestamp($id)
  2323. {
  2324. if (empty($id)) {
  2325. throw new EmptyPkeyValueException('Notice', 'id');
  2326. }
  2327. $timestamp = null;
  2328. if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
  2329. // getByID throws exception if $id isn't found
  2330. $notice = Notice::getByID($id);
  2331. $timestamp = $notice->created;
  2332. }
  2333. if (empty($timestamp)) {
  2334. throw new ServerException('No timestamp found for Notice with id=='._ve($id));
  2335. }
  2336. return $timestamp;
  2337. }
  2338. /**
  2339. * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
  2340. * parameter, matching notices posted after the given one (exclusive).
  2341. *
  2342. * If the referenced notice can't be found, will return false.
  2343. *
  2344. * @param int $id
  2345. * @param string $idField
  2346. * @param string $createdField
  2347. * @return mixed string or false if no match
  2348. */
  2349. public static function whereSinceId($id, $idField='id', $createdField='created')
  2350. {
  2351. try {
  2352. $since = Notice::getAsTimestamp($id);
  2353. } catch (Exception $e) {
  2354. return false;
  2355. }
  2356. return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
  2357. }
  2358. /**
  2359. * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
  2360. * parameter, matching notices posted after the given one (exclusive), and
  2361. * if necessary add it to the data object's query.
  2362. *
  2363. * @param DB_DataObject $obj
  2364. * @param int $id
  2365. * @param string $idField
  2366. * @param string $createdField
  2367. * @return mixed string or false if no match
  2368. */
  2369. public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
  2370. {
  2371. $since = self::whereSinceId($id, $idField, $createdField);
  2372. if ($since) {
  2373. $obj->whereAdd($since);
  2374. }
  2375. }
  2376. /**
  2377. * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
  2378. * parameter, matching notices posted before the given one (inclusive).
  2379. *
  2380. * If the referenced notice can't be found, will return false.
  2381. *
  2382. * @param int $id
  2383. * @param string $idField
  2384. * @param string $createdField
  2385. * @return mixed string or false if no match
  2386. */
  2387. public static function whereMaxId($id, $idField='id', $createdField='created')
  2388. {
  2389. try {
  2390. $max = Notice::getAsTimestamp($id);
  2391. } catch (Exception $e) {
  2392. return false;
  2393. }
  2394. return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
  2395. }
  2396. /**
  2397. * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
  2398. * parameter, matching notices posted before the given one (inclusive), and
  2399. * if necessary add it to the data object's query.
  2400. *
  2401. * @param DB_DataObject $obj
  2402. * @param int $id
  2403. * @param string $idField
  2404. * @param string $createdField
  2405. * @return mixed string or false if no match
  2406. */
  2407. public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
  2408. {
  2409. $max = self::whereMaxId($id, $idField, $createdField);
  2410. if ($max) {
  2411. $obj->whereAdd($max);
  2412. }
  2413. }
  2414. public function isPublic()
  2415. {
  2416. $is_local = intval($this->is_local);
  2417. return !($is_local === Notice::LOCAL_NONPUBLIC || $is_local === Notice::GATEWAY);
  2418. }
  2419. /**
  2420. * Check that the given profile is allowed to read, respond to, or otherwise
  2421. * act on this notice.
  2422. *
  2423. * The $scope member is a bitmask of scopes, representing a logical AND of the
  2424. * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
  2425. * "only visible to people who are mentioned in the notice AND are users on this site."
  2426. * Users on the site who are not mentioned in the notice will not be able to see the
  2427. * notice.
  2428. *
  2429. * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
  2430. *
  2431. * @return boolean whether the profile is in the notice's scope
  2432. */
  2433. public function inScope($profile)
  2434. {
  2435. if (is_null($profile)) {
  2436. $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
  2437. } else {
  2438. $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
  2439. }
  2440. $result = self::cacheGet($keypart);
  2441. if ($result === false) {
  2442. $bResult = false;
  2443. if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
  2444. $bResult = $this->_inScope($profile);
  2445. Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
  2446. }
  2447. $result = ($bResult) ? 1 : 0;
  2448. self::cacheSet($keypart, $result, 0, 300);
  2449. }
  2450. return ($result == 1) ? true : false;
  2451. }
  2452. protected function _inScope($profile)
  2453. {
  2454. $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
  2455. if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
  2456. return !$this->isHiddenSpam($profile);
  2457. }
  2458. // If there's scope, anon cannot be in scope
  2459. if (empty($profile)) {
  2460. return false;
  2461. }
  2462. // Author is always in scope
  2463. if ($this->profile_id == $profile->id) {
  2464. return true;
  2465. }
  2466. // Only for users on this site
  2467. if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
  2468. return false;
  2469. }
  2470. // Only for users mentioned in the notice
  2471. if ($scope & Notice::ADDRESSEE_SCOPE) {
  2472. $reply = Reply::pkeyGet(array('notice_id' => $this->id,
  2473. 'profile_id' => $profile->id));
  2474. if (!$reply instanceof Reply) {
  2475. return false;
  2476. }
  2477. }
  2478. // Only for members of the given group
  2479. if ($scope & Notice::GROUP_SCOPE) {
  2480. // XXX: just query for the single membership
  2481. $groups = $this->getGroups();
  2482. $foundOne = false;
  2483. foreach ($groups as $group) {
  2484. if ($profile->isMember($group)) {
  2485. $foundOne = true;
  2486. break;
  2487. }
  2488. }
  2489. if (!$foundOne) {
  2490. return false;
  2491. }
  2492. }
  2493. if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
  2494. if (!Subscription::exists($profile, $this->getProfile())) {
  2495. return false;
  2496. }
  2497. }
  2498. return !$this->isHiddenSpam($profile);
  2499. }
  2500. public function isHiddenSpam($profile)
  2501. {
  2502. // Hide posts by silenced users from everyone but moderators.
  2503. if (common_config('notice', 'hidespam')) {
  2504. try {
  2505. $author = $this->getProfile();
  2506. } catch (Exception $e) {
  2507. // If we can't get an author, keep it hidden.
  2508. // XXX: technically not spam, but, whatever.
  2509. return true;
  2510. }
  2511. if ($author->hasRole(Profile_role::SILENCED)) {
  2512. if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
  2513. return true;
  2514. }
  2515. }
  2516. }
  2517. return false;
  2518. }
  2519. public function hasParent()
  2520. {
  2521. try {
  2522. $this->getParent();
  2523. } catch (NoParentNoticeException $e) {
  2524. return false;
  2525. }
  2526. return true;
  2527. }
  2528. public function getParent()
  2529. {
  2530. $reply_to_id = null;
  2531. if (empty($this->reply_to)) {
  2532. throw new NoParentNoticeException($this);
  2533. }
  2534. // The reply_to ID in the table Notice could exist with a number
  2535. // however, the replied to notice might not exist in the database.
  2536. // Thus we need to catch the exception and throw the NoParentNoticeException else
  2537. // the timeline will not display correctly.
  2538. try {
  2539. $reply_to_id = self::getByID($this->reply_to);
  2540. } catch (Exception $e) {
  2541. throw new NoParentNoticeException($this);
  2542. }
  2543. return $reply_to_id;
  2544. }
  2545. /**
  2546. * Magic function called at serialize() time.
  2547. *
  2548. * We use this to drop a couple process-specific references
  2549. * from DB_DataObject which can cause trouble in future
  2550. * processes.
  2551. *
  2552. * @return array of variable names to include in serialization.
  2553. */
  2554. public function __sleep()
  2555. {
  2556. $vars = parent::__sleep();
  2557. $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
  2558. return array_diff($vars, $skip);
  2559. }
  2560. public static function defaultScope()
  2561. {
  2562. $scope = common_config('notice', 'defaultscope');
  2563. if (is_null($scope)) {
  2564. if (common_config('site', 'private')) {
  2565. $scope = 1;
  2566. } else {
  2567. $scope = 0;
  2568. }
  2569. }
  2570. return $scope;
  2571. }
  2572. public static function fillProfiles($notices)
  2573. {
  2574. $map = self::getProfiles($notices);
  2575. foreach ($notices as $entry => $notice) {
  2576. try {
  2577. if (array_key_exists($notice->profile_id, $map)) {
  2578. $notice->_setProfile($map[$notice->profile_id]);
  2579. }
  2580. } catch (NoProfileException $e) {
  2581. common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
  2582. unset($notices[$entry]);
  2583. }
  2584. }
  2585. return array_values($map);
  2586. }
  2587. public static function getProfiles(&$notices)
  2588. {
  2589. $ids = [];
  2590. foreach ($notices as $notice) {
  2591. $ids[] = $notice->profile_id;
  2592. }
  2593. $ids = array_unique($ids);
  2594. return Profile::pivotGet('id', $ids);
  2595. }
  2596. public static function fillGroups(&$notices)
  2597. {
  2598. $ids = self::_idsOf($notices);
  2599. $gis = Group_inbox::listGet('notice_id', $ids);
  2600. $gids = [];
  2601. foreach ($gis as $id => $gi) {
  2602. foreach ($gi as $g) {
  2603. $gids[] = $g->group_id;
  2604. }
  2605. }
  2606. $gids = array_unique($gids);
  2607. $group = User_group::pivotGet('id', $gids);
  2608. foreach ($notices as $notice) {
  2609. $grps = [];
  2610. $gi = $gis[$notice->id];
  2611. foreach ($gi as $g) {
  2612. $grps[] = $group[$g->group_id];
  2613. }
  2614. $notice->_setGroups($grps);
  2615. }
  2616. }
  2617. public static function _idsOf(array &$notices)
  2618. {
  2619. $ids = [];
  2620. foreach ($notices as $notice) {
  2621. $ids[$notice->id] = true;
  2622. }
  2623. return array_keys($ids);
  2624. }
  2625. public static function fillAttachments(&$notices)
  2626. {
  2627. $ids = self::_idsOf($notices);
  2628. $f2pMap = File_to_post::listGet('post_id', $ids);
  2629. $fileIds = [];
  2630. foreach ($f2pMap as $noticeId => $f2ps) {
  2631. foreach ($f2ps as $f2p) {
  2632. $fileIds[] = $f2p->file_id;
  2633. }
  2634. }
  2635. $fileIds = array_unique($fileIds);
  2636. $fileMap = File::pivotGet('id', $fileIds);
  2637. foreach ($notices as $notice) {
  2638. $files = [];
  2639. $f2ps = $f2pMap[$notice->id];
  2640. foreach ($f2ps as $f2p) {
  2641. if (!isset($fileMap[$f2p->file_id])) {
  2642. // We have probably deleted value from fileMap since
  2643. // it as a NULL entry (see the following elseif).
  2644. continue;
  2645. } elseif (is_null($fileMap[$f2p->file_id])) {
  2646. // If the file id lookup returned a NULL value, it doesn't
  2647. // exist in our file table! So this is a remnant file_to_post
  2648. // entry that is no longer valid and should be removed.
  2649. common_debug('ATTACHMENT deleting f2p for post_id='.$f2p->post_id.' file_id='.$f2p->file_id);
  2650. $f2p->delete();
  2651. unset($fileMap[$f2p->file_id]);
  2652. continue;
  2653. }
  2654. $files[] = $fileMap[$f2p->file_id];
  2655. }
  2656. $notice->_setAttachments($files);
  2657. }
  2658. }
  2659. public static function fillReplies(&$notices)
  2660. {
  2661. $ids = self::_idsOf($notices);
  2662. $replyMap = Reply::listGet('notice_id', $ids);
  2663. foreach ($notices as $notice) {
  2664. $replies = $replyMap[$notice->id];
  2665. $ids = array();
  2666. foreach ($replies as $reply) {
  2667. $ids[] = $reply->profile_id;
  2668. }
  2669. $notice->_setReplies($ids);
  2670. }
  2671. }
  2672. public static function beforeSchemaUpdate()
  2673. {
  2674. $table = strtolower(get_called_class());
  2675. $schema = Schema::get();
  2676. $schemadef = $schema->getTableDef($table);
  2677. // 2015-09-04 We move Notice location data to Notice_location
  2678. // First we see if we have to do this at all
  2679. if (isset($schemadef['fields']['lat'])
  2680. && isset($schemadef['fields']['lon'])
  2681. && isset($schemadef['fields']['location_id'])
  2682. && isset($schemadef['fields']['location_ns'])) {
  2683. // Then we make sure the Notice_location table is created!
  2684. $schema->ensureTable('notice_location', Notice_location::schemaDef());
  2685. // Then we continue on our road to migration!
  2686. 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)";
  2687. $notice = new Notice();
  2688. $notice->query(sprintf(
  2689. 'SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
  2690. 'WHERE lat IS NOT NULL ' .
  2691. 'OR lon IS NOT NULL ' .
  2692. 'OR location_id IS NOT NULL ' .
  2693. 'OR location_ns IS NOT NULL',
  2694. common_database_tablename($table)
  2695. ));
  2696. print "\nFound {$notice->N} notices with location data, inserting";
  2697. while ($notice->fetch()) {
  2698. $notloc = Notice_location::getKV('notice_id', $notice->id);
  2699. if ($notloc instanceof Notice_location) {
  2700. print "-";
  2701. continue;
  2702. }
  2703. $notloc = new Notice_location();
  2704. $notloc->notice_id = $notice->id;
  2705. $notloc->lat= $notice->lat;
  2706. $notloc->lon= $notice->lon;
  2707. $notloc->location_id= $notice->location_id;
  2708. $notloc->location_ns= $notice->location_ns;
  2709. $notloc->insert();
  2710. print ".";
  2711. }
  2712. print "\n";
  2713. }
  2714. /**
  2715. * Make sure constraints are met before upgrading, if foreign keys
  2716. * are not already in use.
  2717. * 2016-03-31
  2718. */
  2719. if (!isset($schemadef['foreign keys'])) {
  2720. $newschemadef = self::schemaDef();
  2721. printfnq("\nConstraint checking Notice table...\n");
  2722. /**
  2723. * Improve typing and make sure no NULL values in any id-related columns are 0
  2724. * 2016-03-31
  2725. */
  2726. foreach (['reply_to', 'repeat_of'] as $field) {
  2727. $notice = new Notice(); // reset the object
  2728. $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE %2$s=0', $notice->escapedTableName(), $field));
  2729. // Now we're sure that no Notice entries have repeat_of=0, only an id > 0 or NULL
  2730. unset($notice);
  2731. }
  2732. /**
  2733. * This Will find foreign keys which do not fulfill the constraints and fix
  2734. * where appropriate, such as delete when "repeat_of" ID not found in notice.id
  2735. * or set to NULL for "reply_to" in the same case.
  2736. * 2016-03-31
  2737. *
  2738. * XXX: How does this work if we would use multicolumn foreign keys?
  2739. */
  2740. foreach (['reply_to' => 'reset', 'repeat_of' => 'delete', 'profile_id' => 'delete'] as $field=>$action) {
  2741. $notice = new Notice();
  2742. $fkeyname = $notice->tableName().'_'.$field.'_fkey';
  2743. assert(isset($newschemadef['foreign keys'][$fkeyname]));
  2744. assert($newschemadef['foreign keys'][$fkeyname]);
  2745. $foreign_key = $newschemadef['foreign keys'][$fkeyname];
  2746. $fkeytable = $foreign_key[0];
  2747. assert(isset($foreign_key[1][$field]));
  2748. $fkeycol = $foreign_key[1][$field];
  2749. printfnq("* {$fkeyname} ({$field} => {$fkeytable}.{$fkeycol})\n");
  2750. // NOTE: Above we set all repeat_of to NULL if they were 0, so this really gets them all.
  2751. $notice->whereAdd(sprintf('%1$s NOT IN (SELECT %2$s FROM %3$s)', $field, $fkeycol, $fkeytable));
  2752. if ($notice->find()) {
  2753. printfnq("\tFound {$notice->N} notices with {$field} NOT IN notice.id, {$action}ing...");
  2754. switch ($action) {
  2755. case 'delete': // since it's a directly dependant notice for an unknown ID we don't want it in our DB
  2756. while ($notice->fetch()) {
  2757. $notice->delete();
  2758. }
  2759. break;
  2760. case 'reset': // just set it to NULL to be compatible with our constraints, if it was related to an unknown ID
  2761. $ids = [];
  2762. foreach ($notice->fetchAll('id') as $id) {
  2763. settype($id, 'int');
  2764. $ids[] = $id;
  2765. }
  2766. unset($notice);
  2767. $notice = new Notice();
  2768. $notice->query(sprintf(
  2769. <<<'END'
  2770. UPDATE %1$s
  2771. SET %2$s = NULL, modified = CURRENT_TIMESTAMP
  2772. WHERE id IN (%3$s)
  2773. END,
  2774. $notice->escapedTableName(),
  2775. $field,
  2776. implode(',', $ids)
  2777. ));
  2778. break;
  2779. default:
  2780. throw new ServerException('The programmer sucks, invalid action name when fixing table.');
  2781. }
  2782. printfnq("DONE.\n");
  2783. }
  2784. unset($notice);
  2785. }
  2786. }
  2787. }
  2788. public function delPref($namespace, $topic)
  2789. {
  2790. return Notice_prefs::setData($this, $namespace, $topic, null);
  2791. }
  2792. public function getPref($namespace, $topic, $default = null)
  2793. {
  2794. // If you want an exception to be thrown, call Notice_prefs::getData directly
  2795. try {
  2796. return Notice_prefs::getData($this, $namespace, $topic, $default);
  2797. } catch (NoResultException $e) {
  2798. return null;
  2799. }
  2800. }
  2801. // The same as getPref but will fall back to common_config value for the same namespace/topic
  2802. public function getConfigPref($namespace, $topic)
  2803. {
  2804. return Notice_prefs::getConfigData($this, $namespace, $topic);
  2805. }
  2806. public function setPref($namespace, $topic, $data)
  2807. {
  2808. return Notice_prefs::setData($this, $namespace, $topic, $data);
  2809. }
  2810. }