3 * @file src/Object/Item.php
5 namespace Friendica\Object;
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Object\Contact;
14 require_once 'include/text.php';
15 require_once 'boot.php';
20 class Item extends BaseObject
22 private $data = array();
23 private $template = null;
24 private $available_templates = array(
25 'wall' => 'wall_thread.tpl',
26 'wall2wall' => 'wallwall_thread.tpl'
28 private $comment_box_template = 'comment_item.tpl';
29 private $toplevel = false;
30 private $writable = false;
31 private $children = array();
32 private $parent = null;
33 private $conversation = null;
34 private $redirect_url = null;
35 private $owner_url = '';
36 private $owner_photo = '';
37 private $owner_name = '';
38 private $wall_to_wall = false;
39 private $threaded = false;
40 private $visiting = false;
45 * @param array $data data array
47 public function __construct($data)
52 $this->setTemplate('wall');
53 $this->toplevel = ($this->getId() == $this->getDataValue('parent'));
55 if (is_array($_SESSION['remote'])) {
56 foreach ($_SESSION['remote'] as $visitor) {
57 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
58 $this->visiting = true;
64 $this->writable = ($this->getDataValue('writable') || $this->getDataValue('self'));
66 $ssl_state = ((local_user()) ? true : false);
67 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
69 if (Config::get('system', 'thread_allow') && $a->theme_thread_allow && !$this->isToplevel()) {
70 $this->threaded = true;
73 // Prepare the children
74 if (count($data['children'])) {
75 foreach ($data['children'] as $item) {
77 * Only add will be displayed
79 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
81 } elseif (! visible_activity($item)) {
85 // You can always comment on Diaspora items
86 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
87 $item['writable'] = true;
90 $item['pagedrop'] = $data['pagedrop'];
91 $child = new Item($item);
92 $this->addChild($child);
98 * Get data in a form usable by a conversation template
100 * @param object $conv_responses conversation responses
101 * @param integer $thread_level default = 1
103 * @return mixed The data requested on success
106 public function getTemplateData($conv_responses, $thread_level = 1)
108 require_once "mod/proxy.php";
114 $item = $this->getData();
116 // If the time between "created" and "edited" differs we add
117 // a notice that the post was edited.
118 // Note: In some networks reshared items seem to have (sometimes) a difference
119 // between creation time and edit time of a second. Thats why we add the notice
120 // only if the difference is more than 1 second.
121 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
123 'label' => t('This entry was edited'),
124 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
125 'relative' => relative_date($item['edited'])
134 $isstarred = "unstarred";
138 $total_children = $this->countDescendants();
140 $conv = $this->getConversation();
142 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
143 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
144 ? t('Private Message')
146 $shareable = ((($conv->getProfileOwner() == local_user()) && ($item['private'] != 1)) ? true : false);
147 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
148 if ($item["event-id"] != 0) {
149 $edpost = array("events/event/".$item['event-id'], t("Edit"));
151 $edpost = array("editpost/".$item['id'], t("Edit"));
157 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
162 'dropping' => $dropping,
163 'pagedrop' => ((feature_enabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
164 'select' => t('Select'),
165 'delete' => t('Delete'),
168 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
170 $diff_author = ((link_compare($item['url'], $item['author-link'])) ? false : true);
171 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
172 if ($item['author-link'] && (! $item['author-name'])) {
173 $profile_name = $item['author-link'];
177 $profile_link = best_link_url($item, $sp);
178 if ($profile_link === 'mailbox') {
183 $sparkle = ' sparkle';
185 $profile_link = zrl($profile_link);
188 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
189 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
190 if ($author_contact["thumb"]) {
191 $item['author-thumb'] = $author_contact["thumb"];
193 $item['author-thumb'] = $item['author-avatar'];
197 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
198 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
199 if ($owner_contact["thumb"]) {
200 $item['owner-thumb'] = $owner_contact["thumb"];
202 $item['owner-thumb'] = $item['owner-avatar'];
206 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
207 call_hooks('render_location', $locate);
208 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
214 /*foreach(explode(',',$item['tag']) as $tag){
226 // process action responses - e.g. like/dislike/attend/agree/whatever
227 $response_verbs = array('like', 'dislike');
229 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
230 $response_verbs[] = 'attendyes';
231 $response_verbs[] = 'attendno';
232 $response_verbs[] = 'attendmaybe';
233 if ($conv->isWritable()) {
235 $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
239 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
241 foreach ($response_verbs as $value => $verbs) {
242 $responses[$verbs]['output'] = ((x($conv_responses[$verbs], $item['uri'])) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '');
246 * We should avoid doing this all the time, but it depends on the conversation mode
247 * And the conv mode may change when we change the conv, or it changes its mode
248 * Maybe we should establish a way to be notified about conversation changes
250 $this->checkWallToWall();
252 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
253 $osparkle = ' sparkle';
256 if ($this->isToplevel()) {
257 if ($conv->getProfileOwner() == local_user()) {
258 $isstarred = (($item['starred']) ? "starred" : "unstarred");
261 'do' => t("add star"),
262 'undo' => t("remove star"),
263 'toggle' => t("toggle star status"),
264 'classdo' => (($item['starred']) ? "hidden" : ""),
265 'classundo' => (($item['starred']) ? "" : "hidden"),
266 'starred' => t('starred'),
268 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
269 if (DBM::is_result($r)) {
271 'do' => t("ignore thread"),
272 'undo' => t("unignore thread"),
273 'toggle' => t("toggle ignore status"),
274 'classdo' => (($r['ignored']) ? "hidden" : ""),
275 'classundo' => (($r['ignored']) ? "" : "hidden"),
276 'ignored' => t('ignored'),
281 if (feature_enabled($conv->getProfileOwner(), 'commtag')) {
283 'add' => t("add tag"),
292 if ($conv->isWritable()) {
294 'like' => array( t("I like this \x28toggle\x29"), t("like")),
295 'dislike' => ((feature_enabled($conv->getProfileOwner(), 'dislike')) ? array( t("I don't like this \x28toggle\x29"), t("dislike")) : ''),
298 $buttons['share'] = array( t('Share this'), t('share'));
302 $comment = $this->getCommentBox($indent);
304 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
308 localize_item($item);
310 $body = prepare_body($item, true);
312 list($categories, $folders) = get_cats_and_terms($item);
315 $text_e = strip_tags($body);
316 $name_e = $profile_name;
317 $title_e = $item['title'];
318 $location_e = $location;
319 $owner_name_e = $this->getOwnerName();
321 // Disable features that aren't available in several networks
323 /// @todo Add NETWORK_DIASPORA when it will pass this information
324 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
325 unset($buttons["dislike"], $isevent);
329 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
330 unset($buttons["like"]);
333 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
334 unset($buttons["like"]);
338 'template' => $this->getTemplate(),
339 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
340 'tags' => $item['tags'],
341 'hashtags' => $item['hashtags'],
342 'mentions' => $item['mentions'],
343 'txt_cats' => t('Categories:'),
344 'txt_folders' => t('Filed under:'),
345 'has_cats' => ((count($categories)) ? 'true' : ''),
346 'has_folders' => ((count($folders)) ? 'true' : ''),
347 'categories' => $categories,
348 'folders' => $folders,
351 'id' => $this->getId(),
352 'guid' => urlencode($item['guid']),
353 'isevent' => $isevent,
355 'linktitle' => sprintf(t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
356 'olinktitle' => sprintf(t('View %s\'s profile @ %s'), htmlentities($this->getOwnerName()), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
359 'wall' => t('Wall-to-Wall'),
360 'vwall' => t('via Wall-To-Wall:'),
361 'profile_url' => $profile_link,
362 'item_photo_menu' => item_photo_menu($item),
364 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
365 'osparkle' => $osparkle,
366 'sparkle' => $sparkle,
368 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
369 'ago' => (($item['app']) ? sprintf(t('%s from %s'), relative_date($item['created']), $item['app']) : relative_date($item['created'])),
370 'app' => $item['app'],
371 'created' => relative_date($item['created']),
373 'location' => $location_e,
376 'owner_url' => $this->getOwnerUrl(),
377 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
378 'owner_name' => htmlentities($owner_name_e),
379 'plink' => get_plink($item),
380 'edpost' => ((feature_enabled($conv->getProfileOwner(), 'edit_posts')) ? $edpost : ''),
381 'isstarred' => $isstarred,
382 'star' => ((feature_enabled($conv->getProfileOwner(), 'star_posts')) ? $star : ''),
383 'ignore' => ((feature_enabled($conv->getProfileOwner(), 'ignore_posts')) ? $ignore : ''),
385 'filer' => ((feature_enabled($conv->getProfileOwner(), 'filing')) ? $filer : ''),
388 'like' => $responses['like']['output'],
389 'dislike' => $responses['dislike']['output'],
390 'responses' => $responses,
391 'switchcomment' => t('Comment'),
392 'comment' => $comment,
393 'previewing' => ($conv->isPreview() ? ' preview ' : ''),
394 'wait' => t('Please wait'),
395 'thread_level' => $thread_level,
397 'network' => $item["item_network"],
398 'network_name' => network_to_name($item['item_network'], $profile_link),
399 'received' => $item['received'],
400 'commented' => $item['commented'],
401 'created_date' => $item['created'],
404 $arr = array('item' => $item, 'output' => $tmp_item);
405 call_hooks('display_item', $arr);
407 $result = $arr['output'];
409 $result['children'] = array();
410 $children = $this->getChildren();
411 $nb_children = count($children);
412 if ($nb_children > 0) {
413 foreach ($children as $child) {
414 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
417 if (($nb_children > 2) || ($thread_level > 1)) {
418 $result['children'][0]['comment_firstcollapsed'] = true;
419 $result['children'][0]['num_comments'] = sprintf(tt('%d comment', '%d comments', $total_children), $total_children);
420 $result['children'][0]['hidden_comments_num'] = $total_children;
421 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
422 $result['children'][0]['hide_text'] = t('show more');
423 if ($thread_level > 1) {
424 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
426 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
431 if ($this->isToplevel()) {
432 $result['total_comments_num'] = "$total_children";
433 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
436 $result['private'] = $item['private'];
437 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
439 if ($this->isThreaded()) {
440 $result['flatten'] = false;
441 $result['threaded'] = true;
443 $result['flatten'] = true;
444 $result['threaded'] = false;
453 public function getId()
455 return $this->getDataValue('id');
461 public function isThreaded()
463 return $this->threaded;
469 * @param object $item The child item to add
473 public function addChild(Item $item)
475 $item_id = $item->getId();
477 logger('[ERROR] Item::addChild : Item has no ID!!', LOGGER_DEBUG);
479 } elseif ($this->getChild($item->getId())) {
480 logger('[WARN] Item::addChild : Item already exists ('. $item->getId() .').', LOGGER_DEBUG);
484 * Only add what will be displayed
486 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
488 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
492 $item->setParent($this);
493 $this->children[] = $item;
495 return end($this->children);
499 * Get a child by its ID
501 * @param integer $id The child id
505 public function getChild($id)
507 foreach ($this->getChildren() as $child) {
508 if ($child->getId() == $id) {
517 * Get all our children
521 public function getChildren()
523 return $this->children;
529 * @param object $item The item to set as parent
533 protected function setParent($item)
535 $parent = $this->getParent();
537 $parent->removeChild($this);
540 $this->parent = $item;
541 $this->setConversation($item->getConversation());
549 protected function removeParent()
551 $this->parent = null;
552 $this->conversation = null;
558 * @param object $item The child to be removed
560 * @return boolean Success or failure
562 public function removeChild($item)
564 $id = $item->getId();
565 foreach ($this->getChildren() as $key => $child) {
566 if ($child->getId() == $id) {
567 $child->removeParent();
568 unset($this->children[$key]);
569 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
570 $this->children = array_values($this->children);
574 logger('[WARN] Item::removeChild : Item is not a child ('. $id .').', LOGGER_DEBUG);
583 protected function getParent()
585 return $this->parent;
591 * @param object $conv The conversation
595 public function setConversation($conv)
597 $previous_mode = ($this->conversation ? $this->conversation->getMode() : '');
599 $this->conversation = $conv;
601 // Set it on our children too
602 foreach ($this->getChildren() as $child) {
603 $child->setConversation($conv);
612 public function getConversation()
614 return $this->conversation;
620 * We shouldn't need this
624 public function getData()
632 * @param object $name key
634 * @return mixed value on success
637 public function getDataValue($name)
639 if (!isset($this->data[$name])) {
640 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
644 return $this->data[$name];
650 * @param object $name template name
654 private function setTemplate($name)
656 if (!x($this->available_templates, $name)) {
657 logger('[ERROR] Item::setTemplate : Template not available ("'. $name .'").', LOGGER_DEBUG);
661 $this->template = $this->available_templates[$name];
669 private function getTemplate()
671 return $this->template;
675 * Check if this is a toplevel post
679 private function isToplevel()
681 return $this->toplevel;
685 * Check if this is writable
689 private function isWritable()
691 $conv = $this->getConversation();
694 // This will allow us to comment on wall-to-wall items owned by our friends
695 // and community forums even if somebody else wrote the post.
697 // bug #517 - this fixes for conversation owner
698 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
702 // this fixes for visitors
703 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
705 return $this->writable;
709 * Count the total of our descendants
713 private function countDescendants()
715 $children = $this->getChildren();
716 $total = count($children);
718 foreach ($children as $child) {
719 $total += $child->countDescendants();
727 * Get the template for the comment box
731 private function getCommentBoxTemplate()
733 return $this->comment_box_template;
737 * Get the comment box
739 * @param string $indent Indent value
741 * @return mixed The comment box string (empty if no comment box)
744 private function getCommentBox($indent)
747 if (!$this->isToplevel() && !(Config::get('system', 'thread_allow') && $a->theme_thread_allow)) {
752 $conv = $this->getConversation();
753 $template = get_markup_template($this->getCommentBoxTemplate());
755 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
759 if ($conv->isWritable() && $this->isWritable()) {
760 $qc = $qcomment = null;
763 * Hmmm, code depending on the presence of a particular plugin?
764 * This should be better if done by a hook
766 if (in_array('qcomment', $a->plugins)) {
767 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
768 $qcomment = (($qc) ? explode("\n", $qc) : null);
771 $comment_box = replace_macros(
774 '$return_path' => $a->query_string,
775 '$threaded' => $this->isThreaded(),
776 // '$jsreload' => (($conv->getMode() === 'display') ? $_SESSION['return_url'] : ''),
778 '$type' => (($conv->getMode() === 'profile') ? 'wall-comment' : 'net-comment'),
779 '$id' => $this->getId(),
780 '$parent' => $this->getId(),
781 '$qcomment' => $qcomment,
782 '$profile_uid' => $conv->getProfileOwner(),
783 '$mylink' => $a->remove_baseurl($a->contact['url']),
784 '$mytitle' => t('This is you'),
785 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
786 '$comment' => t('Comment'),
787 '$submit' => t('Submit'),
788 '$edbold' => t('Bold'),
789 '$editalic' => t('Italic'),
790 '$eduline' => t('Underline'),
791 '$edquote' => t('Quote'),
792 '$edcode' => t('Code'),
793 '$edimg' => t('Image'),
794 '$edurl' => t('Link'),
795 '$edvideo' => t('Video'),
796 '$preview' => ((feature_enabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
797 '$indent' => $indent,
798 '$sourceapp' => t($a->sourcename),
799 '$ww' => (($conv->getMode() === 'network') ? $ww : ''),
800 '$rand_num' => random_digits(12))
810 private function getRedirectUrl()
812 return $this->redirect_url;
816 * Check if we are a wall to wall item and set the relevant properties
820 protected function checkWallToWall()
823 $conv = $this->getConversation();
824 $this->wall_to_wall = false;
826 if ($this->isToplevel()) {
827 if ($conv->getMode() !== 'profile') {
828 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
829 // On the network page, I am the owner. On the display page it will be the profile owner.
830 // This will have been stored in $a->page_contact by our calling page.
831 // Put this person as the wall owner of the wall-to-wall notice.
833 $this->owner_url = zrl($a->page_contact['url']);
834 $this->owner_photo = $a->page_contact['thumb'];
835 $this->owner_name = $a->page_contact['name'];
836 $this->wall_to_wall = true;
837 } elseif ($this->getDataValue('owner-link')) {
838 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
839 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
840 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
842 if ((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
843 // The author url doesn't match the owner (typically the contact)
844 // and also doesn't match the contact alias.
845 // The name match is a hack to catch several weird cases where URLs are
846 // all over the park. It can be tricked, but this prevents you from
847 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
848 // well that it's the same Bob Smith.
850 // But it could be somebody else with the same name. It just isn't highly likely.
853 $this->owner_photo = $this->getDataValue('owner-avatar');
854 $this->owner_name = $this->getDataValue('owner-name');
855 $this->wall_to_wall = true;
856 // If it is our contact, use a friendly redirect link
857 if ((link_compare($this->getDataValue('owner-link'), $this->getDataValue('url')))
858 && ($this->getDataValue('network') === NETWORK_DFRN)
860 $this->owner_url = $this->getRedirectUrl();
862 $this->owner_url = zrl($this->getDataValue('owner-link'));
869 if (!$this->wall_to_wall) {
870 $this->setTemplate('wall');
871 $this->owner_url = '';
872 $this->owner_photo = '';
873 $this->owner_name = '';
880 private function isWallToWall()
882 return $this->wall_to_wall;
888 private function getOwnerUrl()
890 return $this->owner_url;
896 private function getOwnerPhoto()
898 return $this->owner_photo;
904 private function getOwnerName()
906 return $this->owner_name;
912 private function isVisiting()
914 return $this->visiting;