3 * @file src/Core/Item.php
5 namespace Friendica\Core;
7 use Friendica\Core\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Protocol\Diaspora;
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;
42 public function __construct($data)
44 $a = $this->get_app();
47 $this->setTemplate('wall');
48 $this->toplevel = ($this->getId() == $this->getDataValue('parent'));
50 if (is_array($_SESSION['remote'])) {
51 foreach ($_SESSION['remote'] as $visitor) {
52 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
53 $this->visiting = true;
59 $this->writable = ($this->getDataValue('writable') || $this->getDataValue('self'));
61 $ssl_state = ((local_user()) ? true : false);
62 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
64 if (Config::get('system', 'thread_allow') && $a->theme_thread_allow && !$this->isToplevel()) {
65 $this->threaded = true;
68 // Prepare the children
69 if (count($data['children'])) {
70 foreach ($data['children'] as $item) {
72 * Only add will be displayed
74 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
76 } elseif (! visible_activity($item)) {
80 // You can always comment on Diaspora items
81 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
82 $item['writable'] = true;
85 $item['pagedrop'] = $data['pagedrop'];
86 $child = new Item($item);
87 $this->addChild($child);
93 * Get data in a form usable by a conversation template
96 * _ The data requested on success
99 public function getTemplateData($conv_responses, $thread_level = 1)
101 require_once "mod/proxy.php";
105 $a = $this->get_app();
107 $item = $this->getData();
109 // If the time between "created" and "edited" differs we add
110 // a notice that the post was edited.
111 // Note: In some networks reshared items seem to have (sometimes) a difference
112 // between creation time and edit time of a second. Thats why we add the notice
113 // only if the difference is more than 1 second.
114 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
116 'label' => t('This entry was edited'),
117 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
118 'relative' => relative_date($item['edited'])
127 $isstarred = "unstarred";
131 $total_children = $this->countDescendants();
133 $conv = $this->getConversation();
135 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
136 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
137 ? t('Private Message')
139 $shareable = ((($conv->get_profile_owner() == local_user()) && ($item['private'] != 1)) ? true : false);
140 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
141 if ($item["event-id"] != 0) {
142 $edpost = array("events/event/".$item['event-id'], t("Edit"));
144 $edpost = array("editpost/".$item['id'], t("Edit"));
150 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
155 'dropping' => $dropping,
156 'pagedrop' => ((feature_enabled($conv->get_profile_owner(), 'multi_delete')) ? $item['pagedrop'] : ''),
157 'select' => t('Select'),
158 'delete' => t('Delete'),
161 $filer = (($conv->get_profile_owner() == local_user()) ? t("save to folder") : false);
163 $diff_author = ((link_compare($item['url'], $item['author-link'])) ? false : true);
164 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
165 if ($item['author-link'] && (! $item['author-name'])) {
166 $profile_name = $item['author-link'];
170 $profile_link = best_link_url($item, $sp);
171 if ($profile_link === 'mailbox') {
176 $sparkle = ' sparkle';
178 $profile_link = zrl($profile_link);
181 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
182 $author_contact = get_contact_details_by_url($item['author-link'], $conv->get_profile_owner());
183 if ($author_contact["thumb"]) {
184 $item['author-thumb'] = $author_contact["thumb"];
186 $item['author-thumb'] = $item['author-avatar'];
190 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
191 $owner_contact = get_contact_details_by_url($item['owner-link'], $conv->get_profile_owner());
192 if ($owner_contact["thumb"]) {
193 $item['owner-thumb'] = $owner_contact["thumb"];
195 $item['owner-thumb'] = $item['owner-avatar'];
199 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
200 call_hooks('render_location', $locate);
201 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
207 /*foreach(explode(',',$item['tag']) as $tag){
219 // process action responses - e.g. like/dislike/attend/agree/whatever
220 $response_verbs = array('like', 'dislike');
222 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
223 $response_verbs[] = 'attendyes';
224 $response_verbs[] = 'attendno';
225 $response_verbs[] = 'attendmaybe';
226 if ($conv->is_writable()) {
228 $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
232 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
234 foreach ($response_verbs as $value => $verbs) {
235 $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']) : '');
239 * We should avoid doing this all the time, but it depends on the conversation mode
240 * And the conv mode may change when we change the conv, or it changes its mode
241 * Maybe we should establish a way to be notified about conversation changes
243 $this->checkWallToWall();
245 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
246 $osparkle = ' sparkle';
249 if ($this->isToplevel()) {
250 if ($conv->get_profile_owner() == local_user()) {
251 $isstarred = (($item['starred']) ? "starred" : "unstarred");
254 'do' => t("add star"),
255 'undo' => t("remove star"),
256 'toggle' => t("toggle star status"),
257 'classdo' => (($item['starred']) ? "hidden" : ""),
258 'classundo' => (($item['starred']) ? "" : "hidden"),
259 'starred' => t('starred'),
261 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
262 if (DBM::is_result($r)) {
264 'do' => t("ignore thread"),
265 'undo' => t("unignore thread"),
266 'toggle' => t("toggle ignore status"),
267 'classdo' => (($r['ignored']) ? "hidden" : ""),
268 'classundo' => (($r['ignored']) ? "" : "hidden"),
269 'ignored' => t('ignored'),
274 if (feature_enabled($conv->get_profile_owner(), 'commtag')) {
276 'add' => t("add tag"),
285 if ($conv->is_writable()) {
287 'like' => array( t("I like this \x28toggle\x29"), t("like")),
288 'dislike' => ((feature_enabled($conv->get_profile_owner(), 'dislike')) ? array( t("I don't like this \x28toggle\x29"), t("dislike")) : ''),
291 $buttons['share'] = array( t('Share this'), t('share'));
295 $comment = $this->getCommentBox($indent);
297 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
301 localize_item($item);
303 $body = prepare_body($item, true);
305 list($categories, $folders) = get_cats_and_terms($item);
307 if ($a->theme['template_engine'] === 'internal') {
308 $body_e = template_escape($body);
309 $text_e = strip_tags(template_escape($body));
310 $name_e = template_escape($profile_name);
311 $title_e = template_escape($item['title']);
312 $location_e = template_escape($location);
313 $owner_name_e = template_escape($this->getOwnerName());
316 $text_e = strip_tags($body);
317 $name_e = $profile_name;
318 $title_e = $item['title'];
319 $location_e = $location;
320 $owner_name_e = $this->getOwnerName();
323 // Disable features that aren't available in several networks
325 /// @todo Add NETWORK_DIASPORA when it will pass this information
326 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
327 unset($buttons["dislike"], $isevent);
331 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
332 unset($buttons["like"]);
335 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
336 unset($buttons["like"]);
340 'template' => $this->getTemplate(),
341 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
342 'tags' => $item['tags'],
343 'hashtags' => $item['hashtags'],
344 'mentions' => $item['mentions'],
345 'txt_cats' => t('Categories:'),
346 'txt_folders' => t('Filed under:'),
347 'has_cats' => ((count($categories)) ? 'true' : ''),
348 'has_folders' => ((count($folders)) ? 'true' : ''),
349 'categories' => $categories,
350 'folders' => $folders,
353 'id' => $this->getId(),
354 'guid' => urlencode($item['guid']),
355 'isevent' => $isevent,
357 'linktitle' => sprintf(t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
358 'olinktitle' => sprintf(t('View %s\'s profile @ %s'), htmlentities($this->getOwnerName()), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
361 'wall' => t('Wall-to-Wall'),
362 'vwall' => t('via Wall-To-Wall:'),
363 'profile_url' => $profile_link,
364 'item_photo_menu' => item_photo_menu($item),
366 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
367 'osparkle' => $osparkle,
368 'sparkle' => $sparkle,
370 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
371 'ago' => (($item['app']) ? sprintf(t('%s from %s'), relative_date($item['created']), $item['app']) : relative_date($item['created'])),
372 'app' => $item['app'],
373 'created' => relative_date($item['created']),
375 'location' => $location_e,
378 'owner_url' => $this->getOwnerUrl(),
379 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
380 'owner_name' => htmlentities($owner_name_e),
381 'plink' => get_plink($item),
382 'edpost' => ((feature_enabled($conv->get_profile_owner(), 'edit_posts')) ? $edpost : ''),
383 'isstarred' => $isstarred,
384 'star' => ((feature_enabled($conv->get_profile_owner(), 'star_posts')) ? $star : ''),
385 'ignore' => ((feature_enabled($conv->get_profile_owner(), 'ignore_posts')) ? $ignore : ''),
387 'filer' => ((feature_enabled($conv->get_profile_owner(), 'filing')) ? $filer : ''),
390 'like' => $responses['like']['output'],
391 'dislike' => $responses['dislike']['output'],
392 'responses' => $responses,
393 'switchcomment' => t('Comment'),
394 'comment' => $comment,
395 'previewing' => ($conv->is_preview() ? ' preview ' : ''),
396 'wait' => t('Please wait'),
397 'thread_level' => $thread_level,
399 'network' => $item["item_network"],
400 'network_name' => network_to_name($item['item_network'], $profile_link),
401 'received' => $item['received'],
402 'commented' => $item['commented'],
403 'created_date' => $item['created'],
406 $arr = array('item' => $item, 'output' => $tmp_item);
407 call_hooks('display_item', $arr);
409 $result = $arr['output'];
411 $result['children'] = array();
412 $children = $this->getChildren();
413 $nb_children = count($children);
414 if ($nb_children > 0) {
415 foreach ($children as $child) {
416 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
419 if (($nb_children > 2) || ($thread_level > 1)) {
420 $result['children'][0]['comment_firstcollapsed'] = true;
421 $result['children'][0]['num_comments'] = sprintf(tt('%d comment', '%d comments', $total_children), $total_children);
422 $result['children'][0]['hidden_comments_num'] = $total_children;
423 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
424 $result['children'][0]['hide_text'] = t('show more');
425 if ($thread_level > 1) {
426 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
428 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
433 if ($this->isToplevel()) {
434 $result['total_comments_num'] = "$total_children";
435 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
438 $result['private'] = $item['private'];
439 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
441 if ($this->isThreaded()) {
442 $result['flatten'] = false;
443 $result['threaded'] = true;
445 $result['flatten'] = true;
446 $result['threaded'] = false;
452 public function getId()
454 return $this->getDataValue('id');
457 public function isThreaded()
459 return $this->threaded;
465 public function addChild(Item $item)
467 $item_id = $item->getId();
469 logger('[ERROR] Item::addChild : Item has no ID!!', LOGGER_DEBUG);
471 } elseif ($this->getChild($item->getId())) {
472 logger('[WARN] Item::addChild : Item already exists ('. $item->getId() .').', LOGGER_DEBUG);
476 * Only add what will be displayed
478 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
480 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
484 $item->setParent($this);
485 $this->children[] = $item;
487 return end($this->children);
491 * Get a child by its ID
493 public function getChild($id)
495 foreach ($this->getChildren() as $child) {
496 if ($child->getId() == $id) {
505 * Get all ou children
507 public function getChildren()
509 return $this->children;
515 protected function setParent($item)
517 $parent = $this->getParent();
519 $parent->removeChild($this);
522 $this->parent = $item;
523 $this->setConversation($item->getConversation());
529 protected function removeParent()
531 $this->parent = null;
532 $this->conversation = null;
538 public function removeChild($item)
540 $id = $item->getId();
541 foreach ($this->getChildren() as $key => $child) {
542 if ($child->getId() == $id) {
543 $child->removeParent();
544 unset($this->children[$key]);
545 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
546 $this->children = array_values($this->children);
550 logger('[WARN] Item::removeChild : Item is not a child ('. $id .').', LOGGER_DEBUG);
557 protected function getParent()
559 return $this->parent;
565 public function setConversation($conv)
567 $previous_mode = ($this->conversation ? $this->conversation->get_mode() : '');
569 $this->conversation = $conv;
571 // Set it on our children too
572 foreach ($this->getChildren() as $child) {
573 $child->setConversation($conv);
580 public function getConversation()
582 return $this->conversation;
588 * We shouldn't need this
590 public function getData()
602 public function getDataValue($name)
604 if (!isset($this->data[$name])) {
605 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
609 return $this->data[$name];
615 private function setTemplate($name)
617 if (!x($this->available_templates, $name)) {
618 logger('[ERROR] Item::setTemplate : Template not available ("'. $name .'").', LOGGER_DEBUG);
622 $this->template = $this->available_templates[$name];
628 private function getTemplate()
630 return $this->template;
634 * Check if this is a toplevel post
636 private function isToplevel()
638 return $this->toplevel;
642 * Check if this is writable
644 private function isWritable()
646 $conv = $this->getConversation();
649 // This will allow us to comment on wall-to-wall items owned by our friends
650 // and community forums even if somebody else wrote the post.
652 // bug #517 - this fixes for conversation owner
653 if ($conv->get_mode() == 'profile' && $conv->get_profile_owner() == local_user()) {
657 // this fixes for visitors
658 return ($this->writable || ($this->isVisiting() && $conv->get_mode() == 'profile'));
660 return $this->writable;
664 * Count the total of our descendants
666 private function countDescendants()
668 $children = $this->getChildren();
669 $total = count($children);
671 foreach ($children as $child) {
672 $total += $child->countDescendants();
680 * Get the template for the comment box
682 private function getCommentBoxTemplate()
684 return $this->comment_box_template;
688 * Get the comment box
691 * _ The comment box string (empty if no comment box)
694 private function getCommentBox($indent)
696 $a = $this->get_app();
697 if (!$this->isToplevel() && !(Config::get('system', 'thread_allow') && $a->theme_thread_allow)) {
702 $conv = $this->getConversation();
703 $template = get_markup_template($this->getCommentBoxTemplate());
705 if (($conv->get_mode() === 'network') && $this->isWallToWall()) {
709 if ($conv->is_writable() && $this->isWritable()) {
710 $qc = $qcomment = null;
713 * Hmmm, code depending on the presence of a particular plugin?
714 * This should be better if done by a hook
716 if (in_array('qcomment', $a->plugins)) {
717 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
718 $qcomment = (($qc) ? explode("\n", $qc) : null);
721 $comment_box = replace_macros(
724 '$return_path' => $a->query_string,
725 '$threaded' => $this->isThreaded(),
726 // '$jsreload' => (($conv->get_mode() === 'display') ? $_SESSION['return_url'] : ''),
728 '$type' => (($conv->get_mode() === 'profile') ? 'wall-comment' : 'net-comment'),
729 '$id' => $this->getId(),
730 '$parent' => $this->getId(),
731 '$qcomment' => $qcomment,
732 '$profile_uid' => $conv->get_profile_owner(),
733 '$mylink' => $a->remove_baseurl($a->contact['url']),
734 '$mytitle' => t('This is you'),
735 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
736 '$comment' => t('Comment'),
737 '$submit' => t('Submit'),
738 '$edbold' => t('Bold'),
739 '$editalic' => t('Italic'),
740 '$eduline' => t('Underline'),
741 '$edquote' => t('Quote'),
742 '$edcode' => t('Code'),
743 '$edimg' => t('Image'),
744 '$edurl' => t('Link'),
745 '$edvideo' => t('Video'),
746 '$preview' => ((feature_enabled($conv->get_profile_owner(), 'preview')) ? t('Preview') : ''),
747 '$indent' => $indent,
748 '$sourceapp' => t($a->sourcename),
749 '$ww' => (($conv->get_mode() === 'network') ? $ww : ''),
750 '$rand_num' => random_digits(12))
757 private function getRedirectUrl()
759 return $this->redirect_url;
763 * Check if we are a wall to wall item and set the relevant properties
765 protected function checkWallToWall()
767 $a = $this->get_app();
768 $conv = $this->getConversation();
769 $this->wall_to_wall = false;
771 if ($this->isToplevel()) {
772 if ($conv->get_mode() !== 'profile') {
773 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
774 // On the network page, I am the owner. On the display page it will be the profile owner.
775 // This will have been stored in $a->page_contact by our calling page.
776 // Put this person as the wall owner of the wall-to-wall notice.
778 $this->owner_url = zrl($a->page_contact['url']);
779 $this->owner_photo = $a->page_contact['thumb'];
780 $this->owner_name = $a->page_contact['name'];
781 $this->wall_to_wall = true;
782 } elseif ($this->getDataValue('owner-link')) {
783 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
784 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
785 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
787 if ((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
788 // The author url doesn't match the owner (typically the contact)
789 // and also doesn't match the contact alias.
790 // The name match is a hack to catch several weird cases where URLs are
791 // all over the park. It can be tricked, but this prevents you from
792 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
793 // well that it's the same Bob Smith.
795 // But it could be somebody else with the same name. It just isn't highly likely.
798 $this->owner_photo = $this->getDataValue('owner-avatar');
799 $this->owner_name = $this->getDataValue('owner-name');
800 $this->wall_to_wall = true;
801 // If it is our contact, use a friendly redirect link
802 if ((link_compare($this->getDataValue('owner-link'), $this->getDataValue('url')))
803 && ($this->getDataValue('network') === NETWORK_DFRN)
805 $this->owner_url = $this->getRedirectUrl();
807 $this->owner_url = zrl($this->getDataValue('owner-link'));
814 if (!$this->wall_to_wall) {
815 $this->setTemplate('wall');
816 $this->owner_url = '';
817 $this->owner_photo = '';
818 $this->owner_name = '';
822 private function isWallToWall()
824 return $this->wall_to_wall;
827 private function getOwnerUrl()
829 return $this->owner_url;
832 private function getOwnerPhoto()
834 return $this->owner_photo;
837 private function getOwnerName()
839 return $this->owner_name;
842 private function isVisiting()
844 return $this->visiting;