Profile_list.php 30 KB

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