Profile_list.php 28 KB

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