Profile_list.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * @category Notices
  18. * @package GNUsocial
  19. * @author Shashi Gowda <connect2shashi@gmail.com>
  20. * @copyright 2019 Free Software Foundation, Inc http://www.fsf.org
  21. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  22. */
  23. defined('GNUSOCIAL') || die();
  24. class Profile_list extends Managed_DataObject
  25. {
  26. public $__table = 'profile_list'; // table name
  27. public $id; // int(4) primary_key not_null
  28. public $tagger; // int(4)
  29. public $tag; // varchar(64)
  30. public $description; // text
  31. public $private; // bool default_false
  32. public $created; // datetime() not_null default_0000-00-00%2000%3A00%3A00
  33. public $modified; // datetime() not_null default_CURRENT_TIMESTAMP
  34. public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  35. public $mainpage; // varchar(191) not 255 because utf8mb4 takes more space
  36. public $tagged_count; // smallint
  37. public $subscriber_count; // smallint
  38. public static function schemaDef()
  39. {
  40. return array(
  41. 'fields' => array(
  42. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
  43. 'tagger' => array('type' => 'int', 'not null' => true, 'description' => 'user making the tag'),
  44. 'tag' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'people tag'),
  45. 'description' => array('type' => 'text', 'description' => 'description of the people tag'),
  46. 'private' => array('type' => 'bool', 'default' => false, 'description' => 'is this tag private'),
  47. 'created' => array('type' => 'datetime', 'not null' => true, 'default' => '0000-00-00 00:00:00', 'description' => 'date the tag was added'),
  48. 'modified' => array('type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date the tag was modified'),
  49. 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
  50. 'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page to link to'),
  51. 'tagged_count' => array('type' => 'int', 'default' => 0, 'description' => 'number of people tagged with this tag by this user'),
  52. 'subscriber_count' => array('type' => 'int', 'default' => 0, 'description' => 'number of subscribers to this tag'),
  53. ),
  54. 'primary key' => array('tagger', 'tag'),
  55. 'unique keys' => array(
  56. 'profile_list_id_key' => array('id'),
  57. ),
  58. 'foreign keys' => array(
  59. 'profile_list_tagger_fkey' => array('profile', array('tagger' => 'id')),
  60. ),
  61. 'indexes' => array(
  62. 'profile_list_modified_idx' => array('modified'),
  63. 'profile_list_tag_idx' => array('tag'),
  64. 'profile_list_tagger_tag_idx' => array('tagger', 'tag'),
  65. 'profile_list_tagged_count_idx' => array('tagged_count'),
  66. 'profile_list_subscriber_count_idx' => array('subscriber_count'),
  67. ),
  68. );
  69. }
  70. /**
  71. * get the tagger of this profile_list object
  72. *
  73. * @return Profile the tagger
  74. */
  75. public function getTagger()
  76. {
  77. return Profile::getByID($this->tagger);
  78. }
  79. /**
  80. * return a string to identify this
  81. * profile_list in the user interface etc.
  82. *
  83. * @return String
  84. */
  85. public function getBestName()
  86. {
  87. return $this->tag;
  88. }
  89. /**
  90. * return a uri string for this profile_list
  91. *
  92. * @return String uri
  93. */
  94. public function getUri()
  95. {
  96. $uri = null;
  97. if (Event::handle('StartProfiletagGetUri', array($this, &$uri))) {
  98. if (!empty($this->uri)) {
  99. $uri = $this->uri;
  100. } else {
  101. $uri = common_local_url(
  102. 'profiletagbyid',
  103. ['id' => $this->id, 'tagger_id' => $this->tagger]
  104. );
  105. }
  106. }
  107. Event::handle('EndProfiletagGetUri', array($this, &$uri));
  108. return $uri;
  109. }
  110. /**
  111. * return a url to the homepage of this item
  112. *
  113. * @return String home url
  114. */
  115. public function homeUrl()
  116. {
  117. $url = null;
  118. if (Event::handle('StartUserPeopletagHomeUrl', array($this, &$url))) {
  119. // normally stored in mainpage, but older ones may be null
  120. if (!empty($this->mainpage)) {
  121. $url = $this->mainpage;
  122. } else {
  123. $url = common_local_url(
  124. 'showprofiletag',
  125. [
  126. 'nickname' => $this->getTagger()->nickname,
  127. 'tag' => $this->tag,
  128. ]
  129. );
  130. }
  131. }
  132. Event::handle('EndUserPeopletagHomeUrl', array($this, &$url));
  133. return $url;
  134. }
  135. /**
  136. * return an immutable url for this object
  137. *
  138. * @return String permalink
  139. */
  140. public function permalink()
  141. {
  142. $url = null;
  143. if (Event::handle('StartProfiletagPermalink', array($this, &$url))) {
  144. $url = common_local_url(
  145. 'profiletagbyid',
  146. ['id' => $this->id]
  147. );
  148. }
  149. Event::handle('EndProfiletagPermalink', array($this, &$url));
  150. return $url;
  151. }
  152. /**
  153. * Query notices by users associated with this tag,
  154. * but first check the cache before hitting the DB.
  155. *
  156. * @param integer $offset offset
  157. * @param integer $limit maximum no of results
  158. * @param integer $since_id=null since this id
  159. * @param integer $max_id=null maximum id in result
  160. *
  161. * @return Notice the query
  162. */
  163. public function getNotices($offset, $limit, $since_id = null, $max_id = null)
  164. {
  165. // FIXME: Use something else than Profile::current() to avoid
  166. // possible confusion between session user and queue processing.
  167. $stream = new PeopletagNoticeStream($this, Profile::current());
  168. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  169. }
  170. /**
  171. * Get subscribers (local and remote) to this people tag
  172. * Order by reverse chronology
  173. *
  174. * @param integer $offset offset
  175. * @param integer $limit maximum no of results
  176. * @param integer $since_id=null since unix timestamp
  177. * @param integer $upto=null maximum unix timestamp when subscription was made
  178. *
  179. * @return Profile results
  180. */
  181. public function getSubscribers(int $offset = 0, ?int $limit = null, int $since = 0, int $upto = 0)
  182. {
  183. $subs = new Profile();
  184. $subs->joinAdd(
  185. array('id', 'profile_tag_subscription:profile_id')
  186. );
  187. $subs->whereAdd('profile_tag_subscription.profile_tag_id = ' . $this->id);
  188. if (common_config('db', 'type') !== 'mysql') {
  189. $subs->selectAdd(sprintf(
  190. '((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + ' .
  191. 'EXTRACT(MINUTE %1$s)) * 60 + FLOOR(EXTRACT(SECOND %1$s)) AS "cursor"',
  192. "FROM (profile_tag_subscription.created - TIMESTAMP '1970-01-01 00:00:00')"
  193. ));
  194. } else {
  195. $subs->selectAdd("timestampdiff(SECOND, '1970-01-01', profile_tag_subscription.created) AS `cursor`");
  196. }
  197. if ($since != 0) {
  198. $subs->whereAdd('cursor > ' . $since);
  199. }
  200. if ($upto != 0) {
  201. $subs->whereAdd('cursor <= ' . $upto);
  202. }
  203. if ($limit != null) {
  204. $subs->limit($offset, $limit);
  205. }
  206. $subs->orderBy('profile_tag_subscription.created DESC');
  207. $subs->find();
  208. return $subs;
  209. }
  210. /**
  211. * Get all and only local subscribers to this people tag
  212. * used for distributing notices to user inboxes.
  213. *
  214. * @return array ids of users
  215. */
  216. public function getUserSubscribers()
  217. {
  218. // XXX: cache this
  219. $user = new User();
  220. $user->query(sprintf(
  221. 'SELECT id ' .
  222. 'FROM %1$s INNER JOIN profile_tag_subscription ' .
  223. 'ON %1$s.id = profile_tag_subscription.profile_id ' .
  224. 'WHERE profile_tag_subscription.profile_tag_id = %2$d ',
  225. $user->escapedTableName(),
  226. $this->id
  227. ));
  228. $ids = [];
  229. while ($user->fetch()) {
  230. $ids[] = $user->id;
  231. }
  232. $user->free();
  233. return $ids;
  234. }
  235. /**
  236. * Check to see if a given profile has
  237. * subscribed to this people tag's timeline
  238. *
  239. * @param mixed $id User or Profile object or integer id
  240. *
  241. * @return boolean subscription status
  242. */
  243. public function hasSubscriber($id)
  244. {
  245. if (!is_numeric($id)) {
  246. $id = $id->id;
  247. }
  248. $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $this->id,
  249. 'profile_id' => $id));
  250. return !empty($sub);
  251. }
  252. /**
  253. * Get profiles tagged with this people tag,
  254. * include modified timestamp as a "cursor" field
  255. * order by descending order of modified time
  256. *
  257. * @param integer $offset offset
  258. * @param integer $limit maximum no of results
  259. * @param integer $since_id=null since unix timestamp
  260. * @param integer $upto=null maximum unix timestamp when subscription was made
  261. *
  262. * @return Profile results
  263. */
  264. public function getTagged(int $offset = 0, ?int $limit = null, int $since = 0, int $upto = 0)
  265. {
  266. $tagged = new Profile();
  267. $tagged->joinAdd(['id', 'profile_tag:tagged']);
  268. if (common_config('db', 'type') !== 'mysql') {
  269. $tagged->selectAdd(sprintf(
  270. '((EXTRACT(DAY %1$s) * 24 + EXTRACT(HOUR %1$s)) * 60 + ' .
  271. 'EXTRACT(MINUTE %1$s)) * 60 + FLOOR(EXTRACT(SECOND %1$s)) AS "cursor"',
  272. "FROM (profile_tag.modified - TIMESTAMP '1970-01-01 00:00:00')"
  273. ));
  274. } else {
  275. $tagged->selectAdd("timestampdiff(SECOND, '1970-01-01', profile_tag.modified) AS `cursor`");
  276. }
  277. $tagged->whereAdd('profile_tag.tagger = '.$this->tagger);
  278. $tagged->whereAdd("profile_tag.tag = '{$this->tag}'");
  279. if ($since != 0) {
  280. $tagged->whereAdd('cursor > ' . $since);
  281. }
  282. if ($upto != 0) {
  283. $tagged->whereAdd('cursor <= ' . $upto);
  284. }
  285. if ($limit != null) {
  286. $tagged->limit($offset, $limit);
  287. }
  288. $tagged->orderBy('profile_tag.modified DESC');
  289. $tagged->find();
  290. return $tagged;
  291. }
  292. /**
  293. * Gracefully delete one or many people tags
  294. * along with their members and subscriptions data
  295. *
  296. * @return boolean success
  297. */
  298. public function delete($useWhere = false)
  299. {
  300. // force delete one item at a time.
  301. if (empty($this->id)) {
  302. $this->find();
  303. while ($this->fetch()) {
  304. $this->delete();
  305. }
  306. }
  307. Profile_tag::cleanup($this);
  308. Profile_tag_subscription::cleanup($this);
  309. self::blow('profile:lists:%d', $this->tagger);
  310. return parent::delete($useWhere);
  311. }
  312. /**
  313. * Update a people tag gracefully
  314. * also change "tag" fields in profile_tag table
  315. *
  316. * @param Profile_list $dataObject Object's original form
  317. *
  318. * @return boolean success
  319. */
  320. public function update($dataObject = false)
  321. {
  322. if (!is_object($dataObject) && !$dataObject instanceof Profile_list) {
  323. return parent::update($dataObject);
  324. }
  325. $result = true;
  326. // if original tag was different
  327. // check to see if the new tag already exists
  328. // if not, rename the tag correctly
  329. if ($dataObject->tag != $this->tag || $dataObject->tagger != $this->tagger) {
  330. $existing = Profile_list::getByTaggerAndTag($this->tagger, $this->tag);
  331. if (!empty($existing)) {
  332. // TRANS: Server exception.
  333. throw new ServerException(_('The tag you are trying to rename ' .
  334. 'to already exists.'));
  335. }
  336. // move the tag
  337. // XXX: allow OStatus plugin to send out profile tag
  338. $result = Profile_tag::moveTag($dataObject, $this);
  339. }
  340. return parent::update($dataObject);
  341. }
  342. /**
  343. * return an xml string representing this people tag
  344. * as the author of an atom feed
  345. *
  346. * @return string atom author element
  347. */
  348. public function asAtomAuthor()
  349. {
  350. $xs = new XMLStringer(true);
  351. $tagger = $this->getTagger();
  352. $xs->elementStart('author');
  353. $xs->element('name', null, '@' . $tagger->nickname . '/' . $this->tag);
  354. $xs->element('uri', null, $this->permalink());
  355. $xs->elementEnd('author');
  356. return $xs->getString();
  357. }
  358. /**
  359. * return an xml string to represent this people tag
  360. * as a noun in an activitystreams feed.
  361. *
  362. * @param string $element the xml tag
  363. *
  364. * @return string activitystreams noun
  365. */
  366. public function asActivityNoun($element)
  367. {
  368. $noun = ActivityObject::fromPeopletag($this);
  369. return $noun->asString('activity:' . $element);
  370. }
  371. /**
  372. * get the cached number of profiles tagged with this
  373. * people tag, re-count if the argument is true.
  374. *
  375. * @param boolean $recount whether to ignore cache
  376. *
  377. * @return integer count
  378. */
  379. public function taggedCount($recount = false)
  380. {
  381. $keypart = sprintf(
  382. 'profile_list:tagged_count:%d:%s',
  383. $this->tagger,
  384. $this->tag
  385. );
  386. $count = self::cacheGet($keypart);
  387. if ($count === false) {
  388. $tags = new Profile_tag();
  389. $tags->tag = $this->tag;
  390. $tags->tagger = $this->tagger;
  391. $count = $tags->count('distinct tagged');
  392. self::cacheSet($keypart, $count);
  393. }
  394. return $count;
  395. }
  396. /**
  397. * get the cached number of profiles subscribed to this
  398. * people tag, re-count if the argument is true.
  399. *
  400. * @param boolean $recount whether to ignore cache
  401. *
  402. * @return integer count
  403. */
  404. public function subscriberCount($recount = false)
  405. {
  406. $keypart = sprintf(
  407. 'profile_list:subscriber_count:%d',
  408. $this->id
  409. );
  410. $count = self::cacheGet($keypart);
  411. if ($count === false) {
  412. $sub = new Profile_tag_subscription();
  413. $sub->profile_tag_id = $this->id;
  414. $count = (int) $sub->count('distinct profile_id');
  415. self::cacheSet($keypart, $count);
  416. }
  417. return $count;
  418. }
  419. /**
  420. * get the cached number of profiles subscribed to this
  421. * people tag, re-count if the argument is true.
  422. *
  423. * @param boolean $recount whether to ignore cache
  424. *
  425. * @return integer count
  426. */
  427. public function blowNoticeStreamCache($all = false)
  428. {
  429. self::blow('profile_list:notice_ids:%d', $this->id);
  430. if ($all) {
  431. self::blow('profile_list:notice_ids:%d;last', $this->id);
  432. }
  433. }
  434. /**
  435. * get the Profile_list object by the
  436. * given tagger and with given tag
  437. *
  438. * @param integer $tagger the id of the creator profile
  439. * @param integer $tag the tag
  440. *
  441. * @return integer count
  442. */
  443. public static function getByTaggerAndTag($tagger, $tag)
  444. {
  445. $ptag = Profile_list::pkeyGet(array('tagger' => $tagger, 'tag' => $tag));
  446. return $ptag;
  447. }
  448. /**
  449. * create a profile_list record for a tag, tagger pair
  450. * if it doesn't exist, return it.
  451. *
  452. * @param integer $tagger the tagger
  453. * @param string $tag the tag
  454. * @param string $description description
  455. * @param boolean $private protected or not
  456. *
  457. * @return Profile_list the people tag object
  458. */
  459. public static function ensureTag($tagger, $tag, $description = null, $private = false)
  460. {
  461. $ptag = Profile_list::getByTaggerAndTag($tagger, $tag);
  462. if (empty($ptag->id)) {
  463. $args = array(
  464. 'tag' => $tag,
  465. 'tagger' => $tagger,
  466. 'description' => $description,
  467. 'private' => $private
  468. );
  469. $new_tag = Profile_list::saveNew($args);
  470. return $new_tag;
  471. }
  472. return $ptag;
  473. }
  474. /**
  475. * get the maximum number of characters
  476. * that can be used in the description of
  477. * a people tag.
  478. *
  479. * determined by $config['peopletag']['desclimit']
  480. * if not set, falls back to $config['site']['textlimit']
  481. *
  482. * @return integer maximum number of characters
  483. */
  484. public static function maxDescription()
  485. {
  486. $desclimit = common_config('peopletag', 'desclimit');
  487. // null => use global limit (distinct from 0!)
  488. if (is_null($desclimit)) {
  489. $desclimit = common_config('site', 'textlimit');
  490. }
  491. return $desclimit;
  492. }
  493. /**
  494. * check if the length of given text exceeds
  495. * character limit.
  496. *
  497. * @param string $desc the description
  498. *
  499. * @return boolean is the descripition too long?
  500. */
  501. public static function descriptionTooLong($desc)
  502. {
  503. $desclimit = self::maxDescription();
  504. return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
  505. }
  506. /**
  507. * save a new people tag, this should be always used
  508. * since it makes uri, homeurl, created and modified
  509. * timestamps and performs checks.
  510. *
  511. * @param array $fields an array with fields and their values
  512. *
  513. * @return mixed Profile_list on success, false on fail
  514. */
  515. public static function saveNew(array $fields)
  516. {
  517. extract($fields);
  518. $ptag = new Profile_list();
  519. $ptag->query('START TRANSACTION');
  520. if (empty($tagger)) {
  521. // TRANS: Server exception saving new tag without having a tagger specified.
  522. throw new Exception(_('No tagger specified.'));
  523. }
  524. if (empty($tag)) {
  525. // TRANS: Server exception saving new tag without having a tag specified.
  526. throw new Exception(_('No tag specified.'));
  527. }
  528. if (empty($mainpage)) {
  529. $mainpage = null;
  530. }
  531. if (empty($uri)) {
  532. // fill in later...
  533. $uri = null;
  534. }
  535. if (empty($mainpage)) {
  536. $mainpage = null;
  537. }
  538. if (empty($description)) {
  539. $description = null;
  540. }
  541. if (empty($private)) {
  542. $private = false;
  543. }
  544. $ptag->tagger = $tagger;
  545. $ptag->tag = $tag;
  546. $ptag->description = $description;
  547. $ptag->private = $private;
  548. $ptag->uri = $uri;
  549. $ptag->mainpage = $mainpage;
  550. $ptag->created = common_sql_now();
  551. $ptag->modified = common_sql_now();
  552. $result = $ptag->insert();
  553. if (!$result) {
  554. common_log_db_error($ptag, 'INSERT', __FILE__);
  555. // TRANS: Server exception saving new tag.
  556. throw new ServerException(_('Could not create profile tag.'));
  557. }
  558. if (!isset($uri) || empty($uri)) {
  559. $orig = clone($ptag);
  560. $ptag->uri = common_local_url('profiletagbyid', array('id' => $ptag->id, 'tagger_id' => $ptag->tagger));
  561. $result = $ptag->update($orig);
  562. if (!$result) {
  563. common_log_db_error($ptag, 'UPDATE', __FILE__);
  564. // TRANS: Server exception saving new tag.
  565. throw new ServerException(_('Could not set profile tag URI.'));
  566. }
  567. }
  568. if (!isset($mainpage) || empty($mainpage)) {
  569. $orig = clone($ptag);
  570. $user = User::getKV('id', $ptag->tagger);
  571. if (!empty($user)) {
  572. $ptag->mainpage = common_local_url('showprofiletag', array('tag' => $ptag->tag, 'nickname' => $user->getNickname()));
  573. } else {
  574. $ptag->mainpage = $uri; // assume this is a remote peopletag and the uri works
  575. }
  576. $result = $ptag->update($orig);
  577. if (!$result) {
  578. common_log_db_error($ptag, 'UPDATE', __FILE__);
  579. // TRANS: Server exception saving new tag.
  580. throw new ServerException(_('Could not set profile tag mainpage.'));
  581. }
  582. }
  583. return $ptag;
  584. }
  585. /**
  586. * get all items at given cursor position for api
  587. *
  588. * @param callback $fn a function that takes the following arguments in order:
  589. * $offset, $limit, $since_id, $max_id
  590. * and returns a Profile_list object after making the DB query
  591. * @param array $args arguments required for $fn
  592. * @param integer $cursor the cursor
  593. * @param integer $count max. number of results
  594. *
  595. * Algorithm:
  596. * - if cursor is 0, return empty list
  597. * - if cursor is -1, get first 21 items, next_cursor = 20th prev_cursor = 0
  598. * - if cursor is +ve get 22 consecutive items before starting at cursor
  599. * - return items[1..20] if items[0] == cursor else return items[0..21]
  600. * - prev_cursor = items[1]
  601. * - next_cursor = id of the last item being returned
  602. *
  603. * - if cursor is -ve get 22 consecutive items after cursor starting at cursor
  604. * - return items[1..20]
  605. *
  606. * @returns array (array (mixed items), int next_cursor, int previous_cursor)
  607. */
  608. // XXX: This should be in Memcached_DataObject... eventually
  609. public static function getAtCursor($fn, array $args, $cursor, $count = 20)
  610. {
  611. $items = array();
  612. $since_id = 0;
  613. $max_id = 0;
  614. $next_cursor = 0;
  615. $prev_cursor = 0;
  616. if ($cursor > 0) {
  617. // if cursor is +ve fetch $count+2 items before cursor starting at cursor
  618. $max_id = $cursor;
  619. $fn_args = array_merge($args, array(0, $count+2, 0, $max_id));
  620. $list = call_user_func_array($fn, $fn_args);
  621. while ($list->fetch()) {
  622. $items[] = clone($list);
  623. }
  624. if ((isset($items[0]->cursor) && $items[0]->cursor == $cursor) ||
  625. $items[0]->id == $cursor) {
  626. array_shift($items);
  627. $prev_cursor = isset($items[0]->cursor) ?
  628. -$items[0]->cursor : -$items[0]->id;
  629. } else {
  630. if (count($items) > $count+1) {
  631. array_shift($items);
  632. }
  633. // this means the cursor item has been deleted, check to see if there are more
  634. $fn_args = array_merge($args, array(0, 1, $cursor));
  635. $more = call_user_func($fn, $fn_args);
  636. if (!$more->fetch() || empty($more)) {
  637. // no more items.
  638. $prev_cursor = 0;
  639. } else {
  640. $prev_cursor = isset($items[0]->cursor) ?
  641. -$items[0]->cursor : -$items[0]->id;
  642. }
  643. }
  644. if (count($items)==$count+1) {
  645. // this means there is a next page.
  646. $next = array_pop($items);
  647. $next_cursor = isset($next->cursor) ?
  648. $items[$count-1]->cursor : $items[$count-1]->id;
  649. }
  650. } elseif ($cursor < -1) {
  651. // if cursor is -ve fetch $count+2 items created after -$cursor-1
  652. $cursor = abs($cursor);
  653. $since_id = $cursor-1;
  654. $fn_args = array_merge($args, array(0, $count+2, $since_id));
  655. $list = call_user_func_array($fn, $fn_args);
  656. while ($list->fetch()) {
  657. $items[] = clone($list);
  658. }
  659. $end = count($items)-1;
  660. if ((isset($items[$end]->cursor) && $items[$end]->cursor == $cursor) ||
  661. $items[$end]->id == $cursor) {
  662. array_pop($items);
  663. $next_cursor = isset($items[$end-1]->cursor) ?
  664. $items[$end-1]->cursor : $items[$end-1]->id;
  665. } else {
  666. $next_cursor = isset($items[$end]->cursor) ?
  667. $items[$end]->cursor : $items[$end]->id;
  668. if ($end > $count) {
  669. // excess item
  670. array_pop($items);
  671. }
  672. // check if there are more items for next page
  673. $fn_args = array_merge($args, array(0, 1, 0, $cursor));
  674. $more = call_user_func_array($fn, $fn_args);
  675. if (!$more->fetch() || empty($more)) {
  676. $next_cursor = 0;
  677. }
  678. }
  679. if (count($items) == $count+1) {
  680. // this means there is a previous page.
  681. $prev = array_shift($items);
  682. $prev_cursor = isset($prev->cursor) ?
  683. -$items[0]->cursor : -$items[0]->id;
  684. }
  685. } elseif ($cursor == -1) {
  686. $fn_args = array_merge($args, array(0, $count+1));
  687. $list = call_user_func_array($fn, $fn_args);
  688. while ($list->fetch()) {
  689. $items[] = clone($list);
  690. }
  691. if (count($items)==$count+1) {
  692. $next = array_pop($items);
  693. if (isset($next->cursor)) {
  694. $next_cursor = $items[$count-1]->cursor;
  695. } else {
  696. $next_cursor = $items[$count-1]->id;
  697. }
  698. }
  699. }
  700. return array($items, $next_cursor, $prev_cursor);
  701. }
  702. /**
  703. * save a collection of people tags into the cache
  704. *
  705. * @param string $ckey cache key
  706. * @param Profile_list &$tag the results to store
  707. * @param integer $offset offset for slicing results
  708. * @param integer $limit maximum number of results
  709. *
  710. * @return boolean success
  711. */
  712. public static function setCache($ckey, &$tag, $offset = 0, $limit = null)
  713. {
  714. $cache = Cache::instance();
  715. if (empty($cache)) {
  716. return false;
  717. }
  718. $str = '';
  719. $tags = array();
  720. while ($tag->fetch()) {
  721. $str .= $tag->tagger . ':' . $tag->tag . ';';
  722. $tags[] = clone($tag);
  723. }
  724. $str = substr($str, 0, -1);
  725. if ($offset>=0 && !is_null($limit)) {
  726. $tags = array_slice($tags, $offset, $limit);
  727. }
  728. $tag = new ArrayWrapper($tags);
  729. return self::cacheSet($ckey, $str);
  730. }
  731. /**
  732. * get people tags from the cache
  733. *
  734. * @param string $ckey cache key
  735. * @param integer $offset offset for slicing
  736. * @param integer $limit limit
  737. *
  738. * @return Profile_list results
  739. */
  740. public static function getCached($ckey, $offset = 0, $limit = null)
  741. {
  742. $keys_str = self::cacheGet($ckey);
  743. if ($keys_str === false) {
  744. return false;
  745. }
  746. $pairs = explode(';', $keys_str);
  747. $keys = array();
  748. foreach ($pairs as $pair) {
  749. $keys[] = explode(':', $pair);
  750. }
  751. if ($offset>=0 && !is_null($limit)) {
  752. $keys = array_slice($keys, $offset, $limit);
  753. }
  754. return self::getByKeys($keys);
  755. }
  756. /**
  757. * get Profile_list objects from the database
  758. * given their (tag, tagger) key pairs.
  759. *
  760. * @param array $keys array of array(tagger, tag)
  761. *
  762. * @return Profile_list results
  763. */
  764. public static function getByKeys(array $keys)
  765. {
  766. $cache = Cache::instance();
  767. if (!empty($cache)) {
  768. $tags = array();
  769. foreach ($keys as $key) {
  770. $t = Profile_list::getByTaggerAndTag($key[0], $key[1]);
  771. if (!empty($t)) {
  772. $tags[] = $t;
  773. }
  774. }
  775. return new ArrayWrapper($tags);
  776. } else {
  777. $tag = new Profile_list();
  778. if (empty($keys)) {
  779. //if no IDs requested, just return the tag object
  780. return $tag;
  781. }
  782. $pairs = array();
  783. foreach ($keys as $key) {
  784. $pairs[] = '(' . $key[0] . ', "' . $key[1] . '")';
  785. }
  786. $tag->whereAdd('(tagger, tag) in (' . implode(', ', $pairs) . ')');
  787. $tag->find();
  788. $temp = array();
  789. while ($tag->fetch()) {
  790. $temp[$tag->tagger.'-'.$tag->tag] = clone($tag);
  791. }
  792. $wrapped = array();
  793. foreach ($keys as $key) {
  794. $id = $key[0].'-'.$key[1];
  795. if (array_key_exists($id, $temp)) {
  796. $wrapped[] = $temp[$id];
  797. }
  798. }
  799. return new ArrayWrapper($wrapped);
  800. }
  801. }
  802. public function insert()
  803. {
  804. $result = parent::insert();
  805. if ($result) {
  806. self::blow('profile:lists:%d', $this->tagger);
  807. }
  808. return $result;
  809. }
  810. }