Profile.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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. if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
  20. /**
  21. * Table Definition for profile
  22. */
  23. class Profile extends Managed_DataObject
  24. {
  25. ###START_AUTOCODE
  26. /* the code below is auto generated do not remove the above tag */
  27. public $__table = 'profile'; // table name
  28. public $id; // int(4) primary_key not_null
  29. public $nickname; // varchar(64) multiple_key not_null
  30. public $fullname; // varchar(255) multiple_key
  31. public $profileurl; // varchar(255)
  32. public $homepage; // varchar(255) multiple_key
  33. public $bio; // text() multiple_key
  34. public $location; // varchar(255) multiple_key
  35. public $lat; // decimal(10,7)
  36. public $lon; // decimal(10,7)
  37. public $location_id; // int(4)
  38. public $location_ns; // int(4)
  39. public $created; // datetime() not_null
  40. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  41. public static function schemaDef()
  42. {
  43. $def = array(
  44. 'description' => 'local and remote users have profiles',
  45. 'fields' => array(
  46. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
  47. 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
  48. 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
  49. 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
  50. 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
  51. 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
  52. 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
  53. 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
  54. 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
  55. 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
  56. 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
  57. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  58. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  59. ),
  60. 'primary key' => array('id'),
  61. 'indexes' => array(
  62. 'profile_nickname_idx' => array('nickname'),
  63. )
  64. );
  65. // Add a fulltext index
  66. if (common_config('search', 'type') == 'fulltext') {
  67. $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
  68. }
  69. return $def;
  70. }
  71. /* the code above is auto generated do not remove the tag below */
  72. ###END_AUTOCODE
  73. public static function getByEmail($email)
  74. {
  75. // in the future, profiles should have emails stored...
  76. $user = User::getKV('email', $email);
  77. if (!($user instanceof User)) {
  78. throw new NoSuchUserException(array('email'=>$email));
  79. }
  80. return $user->getProfile();
  81. }
  82. protected $_user = array();
  83. public function getUser()
  84. {
  85. if (!isset($this->_user[$this->id])) {
  86. $user = User::getKV('id', $this->id);
  87. if (!$user instanceof User) {
  88. throw new NoSuchUserException(array('id'=>$this->id));
  89. }
  90. $this->_user[$this->id] = $user;
  91. }
  92. return $this->_user[$this->id];
  93. }
  94. protected $_group = array();
  95. public function getGroup()
  96. {
  97. if (!isset($this->_group[$this->id])) {
  98. $group = User_group::getKV('profile_id', $this->id);
  99. if (!$group instanceof User_group) {
  100. throw new NoSuchGroupException(array('profile_id'=>$this->id));
  101. }
  102. $this->_group[$this->id] = $group;
  103. }
  104. return $this->_group[$this->id];
  105. }
  106. public function isGroup()
  107. {
  108. try {
  109. $this->getGroup();
  110. return true;
  111. } catch (NoSuchGroupException $e) {
  112. return false;
  113. }
  114. }
  115. public function isLocal()
  116. {
  117. try {
  118. $this->getUser();
  119. } catch (NoSuchUserException $e) {
  120. return false;
  121. }
  122. return true;
  123. }
  124. public function getObjectType()
  125. {
  126. // FIXME: More types... like peopletags and whatever
  127. if ($this->isGroup()) {
  128. return ActivityObject::GROUP;
  129. } else {
  130. return ActivityObject::PERSON;
  131. }
  132. }
  133. public function getAvatar($width, $height=null)
  134. {
  135. return Avatar::byProfile($this, $width, $height);
  136. }
  137. public function setOriginal($filename)
  138. {
  139. if ($this->isGroup()) {
  140. // Until Group avatars are handled just like profile avatars.
  141. return $this->getGroup()->setOriginal($filename);
  142. }
  143. $imagefile = new ImageFile($this->id, Avatar::path($filename));
  144. $avatar = new Avatar();
  145. $avatar->profile_id = $this->id;
  146. $avatar->width = $imagefile->width;
  147. $avatar->height = $imagefile->height;
  148. $avatar->mediatype = image_type_to_mime_type($imagefile->type);
  149. $avatar->filename = $filename;
  150. $avatar->original = true;
  151. $avatar->url = Avatar::url($filename);
  152. $avatar->created = common_sql_now();
  153. // XXX: start a transaction here
  154. if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
  155. // If we can't delete the old avatars, let's abort right here.
  156. @unlink(Avatar::path($filename));
  157. return null;
  158. }
  159. return $avatar;
  160. }
  161. /**
  162. * Gets either the full name (if filled) or the nickname.
  163. *
  164. * @return string
  165. */
  166. function getBestName()
  167. {
  168. return ($this->fullname) ? $this->fullname : $this->nickname;
  169. }
  170. /**
  171. * Takes the currently scoped profile into account to give a name
  172. * to list in notice streams. Preferences may differ between profiles.
  173. */
  174. function getStreamName()
  175. {
  176. $user = common_current_user();
  177. if ($user instanceof User && $user->streamNicknames()) {
  178. return $this->nickname;
  179. }
  180. return $this->getBestName();
  181. }
  182. /**
  183. * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
  184. * if no fullname is provided.
  185. *
  186. * @return string
  187. */
  188. function getFancyName()
  189. {
  190. if ($this->fullname) {
  191. // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
  192. return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
  193. } else {
  194. return $this->nickname;
  195. }
  196. }
  197. /**
  198. * Get the most recent notice posted by this user, if any.
  199. *
  200. * @return mixed Notice or null
  201. */
  202. function getCurrentNotice()
  203. {
  204. $notice = $this->getNotices(0, 1);
  205. if ($notice->fetch()) {
  206. if ($notice instanceof ArrayWrapper) {
  207. // hack for things trying to work with single notices
  208. return $notice->_items[0];
  209. }
  210. return $notice;
  211. }
  212. return null;
  213. }
  214. function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
  215. {
  216. $stream = new TaggedProfileNoticeStream($this, $tag);
  217. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  218. }
  219. function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
  220. {
  221. $stream = new ProfileNoticeStream($this, $scoped);
  222. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  223. }
  224. function isMember(User_group $group)
  225. {
  226. $groups = $this->getGroups(0, null);
  227. while ($groups instanceof User_group && $groups->fetch()) {
  228. if ($groups->id == $group->id) {
  229. return true;
  230. }
  231. }
  232. return false;
  233. }
  234. function isAdmin(User_group $group)
  235. {
  236. $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
  237. 'group_id' => $group->id));
  238. return (!empty($gm) && $gm->is_admin);
  239. }
  240. function isPendingMember($group)
  241. {
  242. $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
  243. 'group_id' => $group->id));
  244. return !empty($request);
  245. }
  246. function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
  247. {
  248. $ids = array();
  249. $keypart = sprintf('profile:groups:%d', $this->id);
  250. $idstring = self::cacheGet($keypart);
  251. if ($idstring !== false) {
  252. $ids = explode(',', $idstring);
  253. } else {
  254. $gm = new Group_member();
  255. $gm->profile_id = $this->id;
  256. if ($gm->find()) {
  257. while ($gm->fetch()) {
  258. $ids[] = $gm->group_id;
  259. }
  260. }
  261. self::cacheSet($keypart, implode(',', $ids));
  262. }
  263. if (!is_null($offset) && !is_null($limit)) {
  264. $ids = array_slice($ids, $offset, $limit);
  265. }
  266. try {
  267. return User_group::multiGet('id', $ids);
  268. } catch (NoResultException $e) {
  269. return null; // throw exception when we handle it everywhere
  270. }
  271. }
  272. function getGroupCount() {
  273. $groups = $this->getGroups(0, null);
  274. return $groups instanceof User_group
  275. ? $groups->N
  276. : 0;
  277. }
  278. function isTagged($peopletag)
  279. {
  280. $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
  281. 'tagged' => $this->id,
  282. 'tag' => $peopletag->tag));
  283. return !empty($tag);
  284. }
  285. function canTag($tagged)
  286. {
  287. if (empty($tagged)) {
  288. return false;
  289. }
  290. if ($tagged->id == $this->id) {
  291. return true;
  292. }
  293. $all = common_config('peopletag', 'allow_tagging', 'all');
  294. $local = common_config('peopletag', 'allow_tagging', 'local');
  295. $remote = common_config('peopletag', 'allow_tagging', 'remote');
  296. $subs = common_config('peopletag', 'allow_tagging', 'subs');
  297. if ($all) {
  298. return true;
  299. }
  300. $tagged_user = $tagged->getUser();
  301. if (!empty($tagged_user)) {
  302. if ($local) {
  303. return true;
  304. }
  305. } else if ($subs) {
  306. return (Subscription::exists($this, $tagged) ||
  307. Subscription::exists($tagged, $this));
  308. } else if ($remote) {
  309. return true;
  310. }
  311. return false;
  312. }
  313. function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
  314. {
  315. $ids = array();
  316. $keypart = sprintf('profile:lists:%d', $this->id);
  317. $idstr = self::cacheGet($keypart);
  318. if ($idstr !== false) {
  319. $ids = explode(',', $idstr);
  320. } else {
  321. $list = new Profile_list();
  322. $list->selectAdd();
  323. $list->selectAdd('id');
  324. $list->tagger = $this->id;
  325. $list->selectAdd('id as "cursor"');
  326. if ($since_id>0) {
  327. $list->whereAdd('id > '.$since_id);
  328. }
  329. if ($max_id>0) {
  330. $list->whereAdd('id <= '.$max_id);
  331. }
  332. if($offset>=0 && !is_null($limit)) {
  333. $list->limit($offset, $limit);
  334. }
  335. $list->orderBy('id DESC');
  336. if ($list->find()) {
  337. while ($list->fetch()) {
  338. $ids[] = $list->id;
  339. }
  340. }
  341. self::cacheSet($keypart, implode(',', $ids));
  342. }
  343. $showPrivate = (($auth_user instanceof User ||
  344. $auth_user instanceof Profile) &&
  345. $auth_user->id === $this->id);
  346. $lists = array();
  347. foreach ($ids as $id) {
  348. $list = Profile_list::getKV('id', $id);
  349. if (!empty($list) &&
  350. ($showPrivate || !$list->private)) {
  351. if (!isset($list->cursor)) {
  352. $list->cursor = $list->id;
  353. }
  354. $lists[] = $list;
  355. }
  356. }
  357. return new ArrayWrapper($lists);
  358. }
  359. /**
  360. * Get tags that other people put on this profile, in reverse-chron order
  361. *
  362. * @param (Profile|User) $auth_user Authorized user (used for privacy)
  363. * @param int $offset Offset from latest
  364. * @param int $limit Max number to get
  365. * @param datetime $since_id max date
  366. * @param datetime $max_id min date
  367. *
  368. * @return Profile_list resulting lists
  369. */
  370. function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
  371. {
  372. $list = new Profile_list();
  373. $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
  374. 'from profile_tag join profile_list '.
  375. 'on (profile_tag.tagger = profile_list.tagger ' .
  376. ' and profile_tag.tag = profile_list.tag) ' .
  377. 'where profile_tag.tagged = %d ',
  378. $this->id);
  379. if ($auth_user instanceof User || $auth_user instanceof Profile) {
  380. $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
  381. 'OR ( profile_list.tagger = %d AND ' .
  382. 'profile_list.private = true ) )',
  383. $auth_user->id);
  384. } else {
  385. $qry .= 'AND profile_list.private = 0 ';
  386. }
  387. if ($since_id > 0) {
  388. $qry .= sprintf('AND (cursor > %d) ', $since_id);
  389. }
  390. if ($max_id > 0) {
  391. $qry .= sprintf('AND (cursor < %d) ', $max_id);
  392. }
  393. $qry .= 'ORDER BY profile_tag.modified DESC ';
  394. if ($offset >= 0 && !is_null($limit)) {
  395. $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
  396. }
  397. $list->query($qry);
  398. return $list;
  399. }
  400. function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
  401. {
  402. $tags = new Profile_list();
  403. $tags->private = true;
  404. $tags->tagger = $this->id;
  405. if ($since_id>0) {
  406. $tags->whereAdd('id > '.$since_id);
  407. }
  408. if ($max_id>0) {
  409. $tags->whereAdd('id <= '.$max_id);
  410. }
  411. if($offset>=0 && !is_null($limit)) {
  412. $tags->limit($offset, $limit);
  413. }
  414. $tags->orderBy('id DESC');
  415. $tags->find();
  416. return $tags;
  417. }
  418. function hasLocalTags()
  419. {
  420. $tags = new Profile_tag();
  421. $tags->joinAdd(array('tagger', 'user:id'));
  422. $tags->whereAdd('tagged = '.$this->id);
  423. $tags->whereAdd('tagger != '.$this->id);
  424. $tags->limit(0, 1);
  425. $tags->fetch();
  426. return ($tags->N == 0) ? false : true;
  427. }
  428. function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
  429. {
  430. $lists = new Profile_list();
  431. $subs = new Profile_tag_subscription();
  432. $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
  433. #@fixme: postgres (round(date_part('epoch', my_date)))
  434. $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
  435. $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
  436. if ($since_id>0) {
  437. $lists->whereAdd('cursor > '.$since_id);
  438. }
  439. if ($max_id>0) {
  440. $lists->whereAdd('cursor <= '.$max_id);
  441. }
  442. if($offset>=0 && !is_null($limit)) {
  443. $lists->limit($offset, $limit);
  444. }
  445. $lists->orderBy('"cursor" DESC');
  446. $lists->find();
  447. return $lists;
  448. }
  449. /**
  450. * Request to join the given group.
  451. * May throw exceptions on failure.
  452. *
  453. * @param User_group $group
  454. * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
  455. */
  456. function joinGroup(User_group $group)
  457. {
  458. $join = null;
  459. if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
  460. $join = Group_join_queue::saveNew($this, $group);
  461. } else {
  462. if (Event::handle('StartJoinGroup', array($group, $this))) {
  463. $join = Group_member::join($group->id, $this->id);
  464. self::blow('profile:groups:%d', $this->id);
  465. self::blow('group:member_ids:%d', $group->id);
  466. self::blow('group:member_count:%d', $group->id);
  467. Event::handle('EndJoinGroup', array($group, $this));
  468. }
  469. }
  470. if ($join) {
  471. // Send any applicable notifications...
  472. $join->notify();
  473. }
  474. return $join;
  475. }
  476. /**
  477. * Leave a group that this profile is a member of.
  478. *
  479. * @param User_group $group
  480. */
  481. function leaveGroup(User_group $group)
  482. {
  483. if (Event::handle('StartLeaveGroup', array($group, $this))) {
  484. Group_member::leave($group->id, $this->id);
  485. self::blow('profile:groups:%d', $this->id);
  486. self::blow('group:member_ids:%d', $group->id);
  487. self::blow('group:member_count:%d', $group->id);
  488. Event::handle('EndLeaveGroup', array($group, $this));
  489. }
  490. }
  491. function avatarUrl($size=AVATAR_PROFILE_SIZE)
  492. {
  493. return Avatar::urlByProfile($this, $size);
  494. }
  495. function getSubscribed($offset=0, $limit=null)
  496. {
  497. $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
  498. try {
  499. $profiles = Profile::multiGet('id', $subs);
  500. } catch (NoResultException $e) {
  501. return $e->obj;
  502. }
  503. return $profiles;
  504. }
  505. function getSubscribers($offset=0, $limit=null)
  506. {
  507. $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
  508. try {
  509. $profiles = Profile::multiGet('id', $subs);
  510. } catch (NoResultException $e) {
  511. return $e->obj;
  512. }
  513. return $profiles;
  514. }
  515. function getTaggedSubscribers($tag, $offset=0, $limit=null)
  516. {
  517. $qry =
  518. 'SELECT profile.* ' .
  519. 'FROM profile JOIN subscription ' .
  520. 'ON profile.id = subscription.subscriber ' .
  521. 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
  522. 'AND profile_tag.tagger = subscription.subscribed) ' .
  523. 'WHERE subscription.subscribed = %d ' .
  524. "AND profile_tag.tag = '%s' " .
  525. 'AND subscription.subscribed != subscription.subscriber ' .
  526. 'ORDER BY subscription.created DESC ';
  527. if ($offset) {
  528. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  529. }
  530. $profile = new Profile();
  531. $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
  532. return $profile;
  533. }
  534. function getTaggedSubscriptions($tag, $offset=0, $limit=null)
  535. {
  536. $qry =
  537. 'SELECT profile.* ' .
  538. 'FROM profile JOIN subscription ' .
  539. 'ON profile.id = subscription.subscribed ' .
  540. 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
  541. 'AND profile_tag.tagger = subscription.subscriber) ' .
  542. 'WHERE subscription.subscriber = %d ' .
  543. "AND profile_tag.tag = '%s' " .
  544. 'AND subscription.subscribed != subscription.subscriber ' .
  545. 'ORDER BY subscription.created DESC ';
  546. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  547. $profile = new Profile();
  548. $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
  549. return $profile;
  550. }
  551. /**
  552. * Get pending subscribers, who have not yet been approved.
  553. *
  554. * @param int $offset
  555. * @param int $limit
  556. * @return Profile
  557. */
  558. function getRequests($offset=0, $limit=null)
  559. {
  560. $qry =
  561. 'SELECT profile.* ' .
  562. 'FROM profile JOIN subscription_queue '.
  563. 'ON profile.id = subscription_queue.subscriber ' .
  564. 'WHERE subscription_queue.subscribed = %d ' .
  565. 'ORDER BY subscription_queue.created DESC ';
  566. if ($limit != null) {
  567. if (common_config('db','type') == 'pgsql') {
  568. $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
  569. } else {
  570. $qry .= ' LIMIT ' . $offset . ', ' . $limit;
  571. }
  572. }
  573. $members = new Profile();
  574. $members->query(sprintf($qry, $this->id));
  575. return $members;
  576. }
  577. function subscriptionCount()
  578. {
  579. $c = Cache::instance();
  580. if (!empty($c)) {
  581. $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
  582. if (is_integer($cnt)) {
  583. return (int) $cnt;
  584. }
  585. }
  586. $sub = new Subscription();
  587. $sub->subscriber = $this->id;
  588. $cnt = (int) $sub->count('distinct subscribed');
  589. $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
  590. if (!empty($c)) {
  591. $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
  592. }
  593. return $cnt;
  594. }
  595. function subscriberCount()
  596. {
  597. $c = Cache::instance();
  598. if (!empty($c)) {
  599. $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
  600. if (is_integer($cnt)) {
  601. return (int) $cnt;
  602. }
  603. }
  604. $sub = new Subscription();
  605. $sub->subscribed = $this->id;
  606. $sub->whereAdd('subscriber != subscribed');
  607. $cnt = (int) $sub->count('distinct subscriber');
  608. if (!empty($c)) {
  609. $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
  610. }
  611. return $cnt;
  612. }
  613. /**
  614. * Is this profile subscribed to another profile?
  615. *
  616. * @param Profile $other
  617. * @return boolean
  618. */
  619. function isSubscribed(Profile $other)
  620. {
  621. return Subscription::exists($this, $other);
  622. }
  623. /**
  624. * Check if a pending subscription request is outstanding for this...
  625. *
  626. * @param Profile $other
  627. * @return boolean
  628. */
  629. function hasPendingSubscription(Profile $other)
  630. {
  631. return Subscription_queue::exists($this, $other);
  632. }
  633. /**
  634. * Are these two profiles subscribed to each other?
  635. *
  636. * @param Profile $other
  637. * @return boolean
  638. */
  639. function mutuallySubscribed(Profile $other)
  640. {
  641. return $this->isSubscribed($other) &&
  642. $other->isSubscribed($this);
  643. }
  644. function noticeCount()
  645. {
  646. $c = Cache::instance();
  647. if (!empty($c)) {
  648. $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
  649. if (is_integer($cnt)) {
  650. return (int) $cnt;
  651. }
  652. }
  653. $notices = new Notice();
  654. $notices->profile_id = $this->id;
  655. $cnt = (int) $notices->count('distinct id');
  656. if (!empty($c)) {
  657. $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
  658. }
  659. return $cnt;
  660. }
  661. function blowSubscriberCount()
  662. {
  663. $c = Cache::instance();
  664. if (!empty($c)) {
  665. $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
  666. }
  667. }
  668. function blowSubscriptionCount()
  669. {
  670. $c = Cache::instance();
  671. if (!empty($c)) {
  672. $c->delete(Cache::key('profile:subscription_count:'.$this->id));
  673. }
  674. }
  675. function blowNoticeCount()
  676. {
  677. $c = Cache::instance();
  678. if (!empty($c)) {
  679. $c->delete(Cache::key('profile:notice_count:'.$this->id));
  680. }
  681. }
  682. static function maxBio()
  683. {
  684. $biolimit = common_config('profile', 'biolimit');
  685. // null => use global limit (distinct from 0!)
  686. if (is_null($biolimit)) {
  687. $biolimit = common_config('site', 'textlimit');
  688. }
  689. return $biolimit;
  690. }
  691. static function bioTooLong($bio)
  692. {
  693. $biolimit = self::maxBio();
  694. return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
  695. }
  696. function update($dataObject=false)
  697. {
  698. if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
  699. try {
  700. $local = $this->getUser();
  701. common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
  702. $origuser = clone($local);
  703. $local->nickname = $this->nickname;
  704. // updateWithKeys throws exception on failure.
  705. $local->updateWithKeys($origuser);
  706. // Clear the site owner, in case nickname changed
  707. if ($local->hasRole(Profile_role::OWNER)) {
  708. User::blow('user:site_owner');
  709. }
  710. } catch (NoSuchUserException $e) {
  711. // Nevermind...
  712. }
  713. }
  714. return parent::update($dataObject);
  715. }
  716. function delete($useWhere=false)
  717. {
  718. $this->_deleteNotices();
  719. $this->_deleteSubscriptions();
  720. $this->_deleteTags();
  721. $this->_deleteBlocks();
  722. $this->_deleteAttentions();
  723. Avatar::deleteFromProfile($this, true);
  724. // Warning: delete() will run on the batch objects,
  725. // not on individual objects.
  726. $related = array('Reply',
  727. 'Group_member',
  728. );
  729. Event::handle('ProfileDeleteRelated', array($this, &$related));
  730. foreach ($related as $cls) {
  731. $inst = new $cls();
  732. $inst->profile_id = $this->id;
  733. $inst->delete();
  734. }
  735. return parent::delete($useWhere);
  736. }
  737. function _deleteNotices()
  738. {
  739. $notice = new Notice();
  740. $notice->profile_id = $this->id;
  741. if ($notice->find()) {
  742. while ($notice->fetch()) {
  743. $other = clone($notice);
  744. $other->delete();
  745. }
  746. }
  747. }
  748. function _deleteSubscriptions()
  749. {
  750. $sub = new Subscription();
  751. $sub->subscriber = $this->id;
  752. $sub->find();
  753. while ($sub->fetch()) {
  754. $other = Profile::getKV('id', $sub->subscribed);
  755. if (empty($other)) {
  756. continue;
  757. }
  758. if ($other->id == $this->id) {
  759. continue;
  760. }
  761. Subscription::cancel($this, $other);
  762. }
  763. $subd = new Subscription();
  764. $subd->subscribed = $this->id;
  765. $subd->find();
  766. while ($subd->fetch()) {
  767. $other = Profile::getKV('id', $subd->subscriber);
  768. if (empty($other)) {
  769. continue;
  770. }
  771. if ($other->id == $this->id) {
  772. continue;
  773. }
  774. Subscription::cancel($other, $this);
  775. }
  776. $self = new Subscription();
  777. $self->subscriber = $this->id;
  778. $self->subscribed = $this->id;
  779. $self->delete();
  780. }
  781. function _deleteTags()
  782. {
  783. $tag = new Profile_tag();
  784. $tag->tagged = $this->id;
  785. $tag->delete();
  786. }
  787. function _deleteBlocks()
  788. {
  789. $block = new Profile_block();
  790. $block->blocked = $this->id;
  791. $block->delete();
  792. $block = new Group_block();
  793. $block->blocked = $this->id;
  794. $block->delete();
  795. }
  796. function _deleteAttentions()
  797. {
  798. $att = new Attention();
  799. $att->profile_id = $this->getID();
  800. if ($att->find()) {
  801. while ($att->fetch()) {
  802. // Can't do delete() on the object directly since it won't remove all of it
  803. $other = clone($att);
  804. $other->delete();
  805. }
  806. }
  807. }
  808. // XXX: identical to Notice::getLocation.
  809. public function getLocation()
  810. {
  811. $location = null;
  812. if (!empty($this->location_id) && !empty($this->location_ns)) {
  813. $location = Location::fromId($this->location_id, $this->location_ns);
  814. }
  815. if (is_null($location)) { // no ID, or Location::fromId() failed
  816. if (!empty($this->lat) && !empty($this->lon)) {
  817. $location = Location::fromLatLon($this->lat, $this->lon);
  818. }
  819. }
  820. if (is_null($location)) { // still haven't found it!
  821. if (!empty($this->location)) {
  822. $location = Location::fromName($this->location);
  823. }
  824. }
  825. return $location;
  826. }
  827. public function shareLocation()
  828. {
  829. $cfg = common_config('location', 'share');
  830. if ($cfg == 'always') {
  831. return true;
  832. } else if ($cfg == 'never') {
  833. return false;
  834. } else { // user
  835. $share = common_config('location', 'sharedefault');
  836. // Check if user has a personal setting for this
  837. $prefs = User_location_prefs::getKV('user_id', $this->id);
  838. if (!empty($prefs)) {
  839. $share = $prefs->share_location;
  840. $prefs->free();
  841. }
  842. return $share;
  843. }
  844. }
  845. function hasRole($name)
  846. {
  847. $has_role = false;
  848. if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
  849. $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
  850. 'role' => $name));
  851. $has_role = !empty($role);
  852. Event::handle('EndHasRole', array($this, $name, $has_role));
  853. }
  854. return $has_role;
  855. }
  856. function grantRole($name)
  857. {
  858. if (Event::handle('StartGrantRole', array($this, $name))) {
  859. $role = new Profile_role();
  860. $role->profile_id = $this->id;
  861. $role->role = $name;
  862. $role->created = common_sql_now();
  863. $result = $role->insert();
  864. if (!$result) {
  865. throw new Exception("Can't save role '$name' for profile '{$this->id}'");
  866. }
  867. if ($name == 'owner') {
  868. User::blow('user:site_owner');
  869. }
  870. Event::handle('EndGrantRole', array($this, $name));
  871. }
  872. return $result;
  873. }
  874. function revokeRole($name)
  875. {
  876. if (Event::handle('StartRevokeRole', array($this, $name))) {
  877. $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
  878. 'role' => $name));
  879. if (empty($role)) {
  880. // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
  881. // TRANS: %1$s is the role name, %2$s is the user ID (number).
  882. throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
  883. }
  884. $result = $role->delete();
  885. if (!$result) {
  886. common_log_db_error($role, 'DELETE', __FILE__);
  887. // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
  888. // TRANS: %1$s is the role name, %2$s is the user ID (number).
  889. throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
  890. }
  891. if ($name == 'owner') {
  892. User::blow('user:site_owner');
  893. }
  894. Event::handle('EndRevokeRole', array($this, $name));
  895. return true;
  896. }
  897. }
  898. function isSandboxed()
  899. {
  900. return $this->hasRole(Profile_role::SANDBOXED);
  901. }
  902. function isSilenced()
  903. {
  904. return $this->hasRole(Profile_role::SILENCED);
  905. }
  906. function sandbox()
  907. {
  908. $this->grantRole(Profile_role::SANDBOXED);
  909. }
  910. function unsandbox()
  911. {
  912. $this->revokeRole(Profile_role::SANDBOXED);
  913. }
  914. function silence()
  915. {
  916. $this->grantRole(Profile_role::SILENCED);
  917. if (common_config('notice', 'hidespam')) {
  918. $this->flushVisibility();
  919. }
  920. }
  921. function unsilence()
  922. {
  923. $this->revokeRole(Profile_role::SILENCED);
  924. if (common_config('notice', 'hidespam')) {
  925. $this->flushVisibility();
  926. }
  927. }
  928. function flushVisibility()
  929. {
  930. // Get all notices
  931. $stream = new ProfileNoticeStream($this, $this);
  932. $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
  933. foreach ($ids as $id) {
  934. self::blow('notice:in-scope-for:%d:null', $id);
  935. }
  936. }
  937. /**
  938. * Does this user have the right to do X?
  939. *
  940. * With our role-based authorization, this is merely a lookup for whether the user
  941. * has a particular role. The implementation currently uses a switch statement
  942. * to determine if the user has the pre-defined role to exercise the right. Future
  943. * implementations may allow per-site roles, and different mappings of roles to rights.
  944. *
  945. * @param $right string Name of the right, usually a constant in class Right
  946. * @return boolean whether the user has the right in question
  947. */
  948. public function hasRight($right)
  949. {
  950. $result = false;
  951. if ($this->hasRole(Profile_role::DELETED)) {
  952. return false;
  953. }
  954. if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
  955. switch ($right)
  956. {
  957. case Right::DELETEOTHERSNOTICE:
  958. case Right::MAKEGROUPADMIN:
  959. case Right::SANDBOXUSER:
  960. case Right::SILENCEUSER:
  961. case Right::DELETEUSER:
  962. case Right::DELETEGROUP:
  963. case Right::TRAINSPAM:
  964. case Right::REVIEWSPAM:
  965. $result = $this->hasRole(Profile_role::MODERATOR);
  966. break;
  967. case Right::CONFIGURESITE:
  968. $result = $this->hasRole(Profile_role::ADMINISTRATOR);
  969. break;
  970. case Right::GRANTROLE:
  971. case Right::REVOKEROLE:
  972. $result = $this->hasRole(Profile_role::OWNER);
  973. break;
  974. case Right::NEWNOTICE:
  975. case Right::NEWMESSAGE:
  976. case Right::SUBSCRIBE:
  977. case Right::CREATEGROUP:
  978. $result = !$this->isSilenced();
  979. break;
  980. case Right::PUBLICNOTICE:
  981. case Right::EMAILONREPLY:
  982. case Right::EMAILONSUBSCRIBE:
  983. case Right::EMAILONFAVE:
  984. $result = !$this->isSandboxed();
  985. break;
  986. case Right::WEBLOGIN:
  987. $result = !$this->isSilenced();
  988. break;
  989. case Right::API:
  990. $result = !$this->isSilenced();
  991. break;
  992. case Right::BACKUPACCOUNT:
  993. $result = common_config('profile', 'backup');
  994. break;
  995. case Right::RESTOREACCOUNT:
  996. $result = common_config('profile', 'restore');
  997. break;
  998. case Right::DELETEACCOUNT:
  999. $result = common_config('profile', 'delete');
  1000. break;
  1001. case Right::MOVEACCOUNT:
  1002. $result = common_config('profile', 'move');
  1003. break;
  1004. default:
  1005. $result = false;
  1006. break;
  1007. }
  1008. }
  1009. return $result;
  1010. }
  1011. // FIXME: Can't put Notice typing here due to ArrayWrapper
  1012. public function hasRepeated($notice)
  1013. {
  1014. // XXX: not really a pkey, but should work
  1015. $notice = Notice::pkeyGet(array('profile_id' => $this->id,
  1016. 'repeat_of' => $notice->id));
  1017. return !empty($notice);
  1018. }
  1019. /**
  1020. * Returns an XML string fragment with limited profile information
  1021. * as an Atom <author> element.
  1022. *
  1023. * Assumes that Atom has been previously set up as the base namespace.
  1024. *
  1025. * @param Profile $cur the current authenticated user
  1026. *
  1027. * @return string
  1028. */
  1029. function asAtomAuthor($cur = null)
  1030. {
  1031. $xs = new XMLStringer(true);
  1032. $xs->elementStart('author');
  1033. $xs->element('name', null, $this->nickname);
  1034. $xs->element('uri', null, $this->getUri());
  1035. if ($cur != null) {
  1036. $attrs = Array();
  1037. $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
  1038. $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
  1039. $xs->element('statusnet:profile_info', $attrs, null);
  1040. }
  1041. $xs->elementEnd('author');
  1042. return $xs->getString();
  1043. }
  1044. /**
  1045. * Extra profile info for atom entries
  1046. *
  1047. * Clients use some extra profile info in the atom stream.
  1048. * This gives it to them.
  1049. *
  1050. * @param Profile $scoped The currently logged in/scoped profile
  1051. *
  1052. * @return array representation of <statusnet:profile_info> element or null
  1053. */
  1054. function profileInfo(Profile $scoped=null)
  1055. {
  1056. $profileInfoAttr = array('local_id' => $this->id);
  1057. if ($scoped instanceof Profile) {
  1058. // Whether the current user is a subscribed to this profile
  1059. $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
  1060. // Whether the current user is has blocked this profile
  1061. $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
  1062. }
  1063. return array('statusnet:profile_info', $profileInfoAttr, null);
  1064. }
  1065. /**
  1066. * Returns an XML string fragment with profile information as an
  1067. * Activity Streams <activity:actor> element.
  1068. *
  1069. * Assumes that 'activity' namespace has been previously defined.
  1070. *
  1071. * @return string
  1072. */
  1073. function asActivityActor()
  1074. {
  1075. return $this->asActivityNoun('actor');
  1076. }
  1077. /**
  1078. * Returns an XML string fragment with profile information as an
  1079. * Activity Streams noun object with the given element type.
  1080. *
  1081. * Assumes that 'activity', 'georss', and 'poco' namespace has been
  1082. * previously defined.
  1083. *
  1084. * @param string $element one of 'actor', 'subject', 'object', 'target'
  1085. *
  1086. * @return string
  1087. */
  1088. function asActivityNoun($element)
  1089. {
  1090. $noun = $this->asActivityObject();
  1091. return $noun->asString('activity:' . $element);
  1092. }
  1093. public function asActivityObject()
  1094. {
  1095. $object = new ActivityObject();
  1096. if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
  1097. $object->type = $this->getObjectType();
  1098. $object->id = $this->getUri();
  1099. $object->title = $this->getBestName();
  1100. $object->link = $this->getUrl();
  1101. $object->summary = $this->getDescription();
  1102. try {
  1103. $avatar = Avatar::getUploaded($this);
  1104. $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
  1105. } catch (NoAvatarException $e) {
  1106. // Could not find an original avatar to link
  1107. }
  1108. $sizes = array(
  1109. AVATAR_PROFILE_SIZE,
  1110. AVATAR_STREAM_SIZE,
  1111. AVATAR_MINI_SIZE
  1112. );
  1113. foreach ($sizes as $size) {
  1114. $alink = null;
  1115. try {
  1116. $avatar = Avatar::byProfile($this, $size);
  1117. $alink = AvatarLink::fromAvatar($avatar);
  1118. } catch (NoAvatarException $e) {
  1119. $alink = new AvatarLink();
  1120. $alink->type = 'image/png';
  1121. $alink->height = $size;
  1122. $alink->width = $size;
  1123. $alink->url = Avatar::defaultImage($size);
  1124. }
  1125. $object->avatarLinks[] = $alink;
  1126. }
  1127. if (isset($this->lat) && isset($this->lon)) {
  1128. $object->geopoint = (float)$this->lat
  1129. . ' ' . (float)$this->lon;
  1130. }
  1131. $object->poco = PoCo::fromProfile($this);
  1132. if ($this->isLocal()) {
  1133. $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
  1134. }
  1135. Event::handle('EndActivityObjectFromProfile', array($this, &$object));
  1136. }
  1137. return $object;
  1138. }
  1139. /**
  1140. * Returns the profile's canonical url, not necessarily a uri/unique id
  1141. *
  1142. * @return string $profileurl
  1143. */
  1144. public function getUrl()
  1145. {
  1146. if (empty($this->profileurl) ||
  1147. !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
  1148. throw new InvalidUrlException($this->profileurl);
  1149. }
  1150. return $this->profileurl;
  1151. }
  1152. public function getNickname()
  1153. {
  1154. return $this->nickname;
  1155. }
  1156. public function getDescription()
  1157. {
  1158. return $this->bio;
  1159. }
  1160. /**
  1161. * Returns the best URI for a profile. Plugins may override.
  1162. *
  1163. * @return string $uri
  1164. */
  1165. public function getUri()
  1166. {
  1167. $uri = null;
  1168. // give plugins a chance to set the URI
  1169. if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
  1170. // check for a local user first
  1171. $user = User::getKV('id', $this->id);
  1172. if ($user instanceof User) {
  1173. $uri = $user->getUri();
  1174. }
  1175. Event::handle('EndGetProfileUri', array($this, &$uri));
  1176. }
  1177. return $uri;
  1178. }
  1179. /**
  1180. * Returns an assumed acct: URI for a profile. Plugins are required.
  1181. *
  1182. * @return string $uri
  1183. */
  1184. public function getAcctUri()
  1185. {
  1186. $acct = null;
  1187. if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
  1188. Event::handle('EndGetProfileAcctUri', array($this, &$acct));
  1189. }
  1190. if ($acct === null) {
  1191. throw new ProfileNoAcctUriException($this);
  1192. }
  1193. return $acct;
  1194. }
  1195. function hasBlocked($other)
  1196. {
  1197. $block = Profile_block::exists($this, $other);
  1198. return !empty($block);
  1199. }
  1200. function getAtomFeed()
  1201. {
  1202. $feed = null;
  1203. if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
  1204. $user = User::getKV('id', $this->id);
  1205. if (!empty($user)) {
  1206. $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
  1207. 'format' => 'atom'));
  1208. }
  1209. Event::handle('EndProfileGetAtomFeed', array($this, $feed));
  1210. }
  1211. return $feed;
  1212. }
  1213. /*
  1214. * Get a Profile object by URI. Will call external plugins for help
  1215. * using the event StartGetProfileFromURI.
  1216. *
  1217. * @param string $uri A unique identifier for a resource (profile/group/whatever)
  1218. */
  1219. static function fromUri($uri)
  1220. {
  1221. $profile = null;
  1222. if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
  1223. // Get a local user when plugin lookup (like OStatus) fails
  1224. $user = User::getKV('uri', $uri);
  1225. if ($user instanceof User) {
  1226. $profile = $user->getProfile();
  1227. }
  1228. Event::handle('EndGetProfileFromURI', array($uri, $profile));
  1229. }
  1230. if (!$profile instanceof Profile) {
  1231. throw new UnknownUriException($uri);
  1232. }
  1233. return $profile;
  1234. }
  1235. function canRead(Notice $notice)
  1236. {
  1237. if ($notice->scope & Notice::SITE_SCOPE) {
  1238. $user = $this->getUser();
  1239. if (empty($user)) {
  1240. return false;
  1241. }
  1242. }
  1243. if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
  1244. $replies = $notice->getReplies();
  1245. if (!in_array($this->id, $replies)) {
  1246. $groups = $notice->getGroups();
  1247. $foundOne = false;
  1248. foreach ($groups as $group) {
  1249. if ($this->isMember($group)) {
  1250. $foundOne = true;
  1251. break;
  1252. }
  1253. }
  1254. if (!$foundOne) {
  1255. return false;
  1256. }
  1257. }
  1258. }
  1259. if ($notice->scope & Notice::FOLLOWER_SCOPE) {
  1260. $author = $notice->getProfile();
  1261. if (!Subscription::exists($this, $author)) {
  1262. return false;
  1263. }
  1264. }
  1265. return true;
  1266. }
  1267. static function current()
  1268. {
  1269. $user = common_current_user();
  1270. if (empty($user)) {
  1271. $profile = null;
  1272. } else {
  1273. $profile = $user->getProfile();
  1274. }
  1275. return $profile;
  1276. }
  1277. /**
  1278. * Magic function called at serialize() time.
  1279. *
  1280. * We use this to drop a couple process-specific references
  1281. * from DB_DataObject which can cause trouble in future
  1282. * processes.
  1283. *
  1284. * @return array of variable names to include in serialization.
  1285. */
  1286. function __sleep()
  1287. {
  1288. $vars = parent::__sleep();
  1289. $skip = array('_user', '_group');
  1290. return array_diff($vars, $skip);
  1291. }
  1292. public function getProfile()
  1293. {
  1294. return $this;
  1295. }
  1296. /**
  1297. * This will perform shortenLinks with the connected User object.
  1298. *
  1299. * Won't work on remote profiles or groups, so expect a
  1300. * NoSuchUserException if you don't know it's a local User.
  1301. *
  1302. * @param string $text String to shorten
  1303. * @param boolean $always Disrespect minimum length etc.
  1304. *
  1305. * @return string link-shortened $text
  1306. */
  1307. public function shortenLinks($text, $always=false)
  1308. {
  1309. return $this->getUser()->shortenLinks($text, $always);
  1310. }
  1311. public function delPref($namespace, $topic) {
  1312. return Profile_prefs::setData($this, $namespace, $topic, null);
  1313. }
  1314. public function getPref($namespace, $topic, $default=null) {
  1315. // If you want an exception to be thrown, call Profile_prefs::getData directly
  1316. try {
  1317. return Profile_prefs::getData($this, $namespace, $topic, $default);
  1318. } catch (NoResultException $e) {
  1319. return null;
  1320. }
  1321. }
  1322. // The same as getPref but will fall back to common_config value for the same namespace/topic
  1323. public function getConfigPref($namespace, $topic)
  1324. {
  1325. return Profile_prefs::getConfigData($this, $namespace, $topic);
  1326. }
  1327. public function setPref($namespace, $topic, $data) {
  1328. return Profile_prefs::setData($this, $namespace, $topic, $data);
  1329. }
  1330. }