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
8/**
9 * Main class to manage the functionality
10 * of the periodic reports.
11 *
12 * @package Tiki
13 * @subpackage Reports
14 */
15class Reports_Manager
16{
17	protected $reportsUsers;
18
19	protected $reportsCache;
20
21	protected $reportsSend;
22
23	protected $userlib;
24
25	public function __construct(Reports_Users $reportsUsers, Reports_Cache $reportsCache, Reports_Send $reportsSend, UsersLib $userlib)
26	{
27		$this->reportsUsers = $reportsUsers;
28		$this->reportsCache = $reportsCache;
29		$this->reportsSend = $reportsSend;
30		$this->userlib = $userlib;
31	}
32
33	/**
34	 * Send report to subscribed users.
35	 * @return null
36	 */
37	public function send()
38	{
39		$users = $this->reportsUsers->getUsersForReport();
40
41		foreach ($users as $user) {
42			$userReportPreferences = $this->reportsUsers->get($user);
43			$userData = $this->userlib->get_user_info($user);
44
45			// if email address isn't set, do nothing but clear the cache
46			if (! empty($userData['email'])) {
47				$cache = $this->reportsCache->get($user);
48
49				if (! empty($cache) || $userReportPreferences['always_email']) {
50					$this->reportsSend->sendEmail($userData, $userReportPreferences, $cache);
51					$this->reportsUsers->updateLastReport($userData['login']);
52				}
53			}
54
55			$this->reportsCache->delete($userData['login']);
56		}
57	}
58
59	/**
60	 * Remove user preferences for reports and the
61	 * changes cache for this user.
62	 *
63	 * @param string $user user name
64	 * @return TikiDb_Pdo_Result|TikiDb_Adodb_Result
65	 */
66	public function delete($user)
67	{
68		$this->reportsCache->delete($user);
69		return $this->reportsUsers->delete($user);
70	}
71
72	/**
73	 * @see Reports_Users::save()
74	 * @param string $user
75	 * @param string $interval
76	 * @param string $view
77	 * @param string $type
78	 * @param int $always_email
79	 * @return int|TikiDb_Pdo_Result|TikiDb_Adodb_Result
80	 */
81	public function save($user, $interval, $view, $type, $always_email)
82	{
83		return $this->reportsUsers->save($user, $interval, $view, $type, $always_email);
84	}
85
86	/**
87	 * Add a new event to the periodic reports cache instead
88	 * of sending an notification e-mail to the users.
89	 *
90	 * @param array $watches a list of users watching the changed object and some information about the object itself
91	 * @param array $data information about the changed object
92	 * @return null
93	 */
94	public function addToCache(&$watches, $data)
95	{
96		$users = $this->reportsUsers->getAllUsers();
97		$this->reportsCache->add($watches, $data, $users);
98	}
99}
100