1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8class Search_GlobalSource_SocialSource implements Search_GlobalSource_Interface
9{
10	private $sociallib;
11	private $userlib;
12
13	function __construct()
14	{
15		$this->sociallib = TikiLib::lib('social');
16		$this->userlib = TikiLib::lib('user');
17	}
18
19	function getProvidedFields()
20	{
21		return [
22			'user_groups',
23			'user_followers',
24			'like_list',
25		];
26	}
27
28	function getGlobalFields()
29	{
30		return [];
31	}
32
33	function getData($objectType, $objectId, Search_Type_Factory_Interface $typeFactory, array $data = [])
34	{
35		$groups = [];
36		$followers = [];
37
38		foreach ($this->getUsers($data, $objectType, $objectId) as $user) {
39			$groups = array_merge($groups, $this->userlib->get_user_groups_inclusion($user));
40			$userfollowers = $this->getFollowers($user);
41			if (is_array($userfollowers)) {
42				$followers = array_merge($followers, $userfollowers);
43			}
44		}
45
46		unset($groups['Anonymous'], $groups['Registered']);
47
48		$like_list = $this->sociallib->getLikes($objectType, $objectId);
49
50		return [
51			'user_groups' => $typeFactory->multivalue(array_keys($groups)),
52			'user_followers' => $typeFactory->multivalue(array_unique($followers)),
53			'like_list' => $typeFactory->multivalue($like_list),
54		];
55	}
56
57	private function getUsers($data, $objectType, $objectId)
58	{
59		$users = [];
60		if (isset($data['contributors'])) {
61			$users = $this->read($data['contributors']);
62		}
63
64		if (isset($data['user'])) {
65			$users[] = $this->read($data['user']);
66		}
67
68		if ($objectType == 'user') {
69			$users[] = $objectId;
70		}
71
72		return $users;
73	}
74
75	private function read($value)
76	{
77		if (! $value instanceof Search_Type_Interface) {
78			return $value;
79		} elseif ($value instanceof Search_Type_MultivalueText) {
80			return $value->getRawValue();
81		} else {
82			return $value->getValue();
83		}
84	}
85
86	private function getFollowers($user)
87	{
88		static $localCache = [];
89
90		if (! isset($localCache[$user])) {
91			$list = $this->sociallib->listFollowers($user);
92			$localCache[$user] = array_map(
93				function ($entry) {
94					return $entry['user'];
95				},
96				$list
97			);
98		}
99
100		return $localCache[$user];
101	}
102}
103