Profile.php 56 KB

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