Notice.php 107 KB

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