start.php ➔ mentions_get_views()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Provides links and notifications for using @username mentions
4
 *
5
 */
6
 /*
7
  * GC_MODIFICATION
8
  * Description: Modified notifications of mentions to use cp_notifications
9
  * Author: GCTools Team
10
  */
11
elgg_register_event_handler('init', 'system', 'mentions_init');
12
13
function mentions_init() {
14
	elgg_extend_view('css/elgg', 'css/mentions');
15
16
	elgg_extend_view('input/longtext', 'mentions/popup');
17
	elgg_extend_view('input/plaintext', 'mentions/popup');
18
19
	elgg_register_event_handler('pagesetup', 'system', 'mentions_get_views');
20
21
	// can't use notification hooks here because of many reasons
22
	elgg_register_event_handler('create', 'object', 'mentions_notification_handler');
23
	elgg_register_event_handler('create', 'annotation', 'mentions_notification_handler');
24
25
	// @todo This will result in multiple notifications for an edited entity so we don't do this
26
	//elgg_register_event_handler('update', 'all', 'mentions_notification_handler');
27
28
	// add option to the personal notifications form
29
	elgg_extend_view('notifications/subscriptions/personal', 'mentions/notification_settings');
30
	elgg_register_plugin_hook_handler('action', 'notificationsettings/save', 'mentions_save_settings');
31
}
32
33
function mentions_get_regex() {
34
	// @todo this won't work for usernames that must be html encoded.
35
	// get all chars with unicode 'letter' or 'mark' properties or a number _ or .,
36
	// preceeded by @, and possibly surrounded by word boundaries.
37
	return '/[\b]?@([\p{L}\p{M}_\.0-9]+)[\b]?/iu';
38
}
39
40
function mentions_get_views() {
41
	// allow plugins to add additional views to be processed for usernames
42
	$views = array('output/longtext', 'object/elements/summary', 'object/elements/thewire_summary');
43
	$views = elgg_trigger_plugin_hook('get_views', 'mentions', null, $views);
44
	foreach ($views as $view) {
45
		elgg_register_plugin_hook_handler('view', $view, 'mentions_rewrite');
46
	}
47
}
48
49
/**
50
 * Rewrites a view for @username mentions.
51
 *
52
 * @param string $hook    The name of the hook
53
 * @param string $type    The type of the hook
0 ignored issues
show
Bug introduced by
There is no parameter named $type. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
54
 * @param string $content The content of the page
0 ignored issues
show
Bug introduced by
There is no parameter named $content. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
55
 * @return string
56
 */
57
function mentions_rewrite($hook, $entity_type, $returnvalue, $params) {
58
59
	$regexp = mentions_get_regex();
60
	$returnvalue =  preg_replace_callback($regexp, 'mentions_preg_callback', $returnvalue);
61
62
	return $returnvalue;
63
}
64
65
/**
66
 * Used as a callback fro the preg_replace in mentions_rewrite()
67
 *
68
 * @param type $matches
69
 * @return type str
70
 */
71
function mentions_preg_callback($matches) {
72
	$user = get_user_by_username($matches[1]);
73
	$period = '';
74
	$icon = '';
75
76
	// Catch the trailing period when used as punctuation and not a username.
77
	if (!$user && substr($matches[1], -1) == '.') {
78
		$user = get_user_by_username(rtrim($matches[1], '.'));
79
		$period = '.';
80
	}
81
82
	if ($user) {
83
		if (elgg_get_plugin_setting('fancy_links', 'mentions')) {
84
			$icon = elgg_view('output/img', array(
85
				'src' => $user->getIconURL('topbar'),
86
				'class' => 'pas mentions-user-icon',
87
				'alt' => ''
88
			));
89
			$replace = elgg_view('output/url', array(
90
				'href' => $user->getURL(),
91
				'text' => $icon . $user->name,
92
				'class' => 'mentions-user-link'
93
			));
94
		} else {
95
			$replace = elgg_view('output/url', array(
96
				'href' => $user->getURL(),
97
				'text' => $user->name,
98
			));
99
		}
100
101
		return $replace .= $period;
102
	} else {
103
		return $matches[0];
104
	}
105
}
106
107
/**
108
 * Catch all create events and scan for @username tags to notify user.
109
 *
110
 * @param string   $event      The event name
111
 * @param string   $event_type The event type
112
 * @param ElggData $object     The object that was created
113
 * @return void
114
 */
115
function mentions_notification_handler($event, $event_type, $object) {
116
	// excludes messages - otherwise an endless loop of notifications occur!
117
	if (elgg_instanceof($object, 'object', 'messages') || elgg_instanceof($object, 'object', 'message')) {
118
		return;
119
	}
120
121
	$type = $object->getType();
122
	$subtype = $object->getSubtype();
123
	$owner = $object->getOwnerEntity();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ElggData as the method getOwnerEntity() does only exist in the following sub-classes of ElggData: ElggAnnotation, ElggAnswer, ElggBlog, ElggComment, ElggDiscussionReply, ElggEntity, ElggExtender, ElggFile, ElggGroup, ElggMetadata, ElggObject, ElggPad, ElggPlugin, ElggQuestion, ElggSite, ElggUpgrade, ElggUser, ElggWidget, ElggWire, FakeEntity, FilePluginFile, MultiDashboard, SiteNotification, TheWireImage, ThemeSandboxObject, TidypicsAlbum, TidypicsBatch, TidypicsImage, UploadUsersFile, WidgetManagerWidget. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
124
125
	$fields = array(
126
		'title', 'description', 'value'
127
	);
128
129
	// store the guids of notified users so they only get one notification per creation event
130
	$notified_guids = array();
131
132
	foreach ($fields as $field) {
133
		$content = $object->$field;
134
		// it's ok in this case if 0 matches == FALSE
135
		if (preg_match_all(mentions_get_regex(), $content, $matches)) {
136
			// match against the 2nd index since the first is everything
137
			foreach ($matches[1] as $username) {
138
139
				$user = get_user_by_username($username);
140
141
				// check for trailing punctuation caught by the regex
142
				if (!$user && substr($username, -1) == '.') {
143
					$user = get_user_by_username(rtrim($username, '.'));
144
				}
145
146
				if (!$user) {
147
					continue;
148
				}
149
150
				// user must have access to view object/annotation
151
				if ($type == 'annotation') {
152
					$annotated_entity = $object->getEntity();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ElggData as the method getEntity() does only exist in the following sub-classes of ElggData: ElggAnnotation, ElggExtender, ElggMetadata. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
153
					if (!$annotated_entity || !has_access_to_entity($annotated_entity, $user)) {
154
						continue;
155
					}
156
				} else {
157
					if (!has_access_to_entity($object, $user)) {
0 ignored issues
show
Compatibility introduced by
$object of type object<ElggData> is not a sub-type of object<ElggEntity>. It seems like you assume a child class of the class ElggData to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
158
						continue;
159
					}
160
				}
161
162
				if (!in_array($user->getGUID(), $notified_guids)) {
163
					$notified_guids[] = $user->getGUID();
164
165
					// if they haven't set the notification status default to sending.
166
					// Private settings are stored as strings so we check against "0"
167
					$notification_setting = elgg_get_plugin_user_setting('notify', $user->getGUID(), 'mentions');
168
					if ($notification_setting === "0") {
169
						continue;
170
					}
171
172
					$link = $object->getURL();
173
					$type_key = "mentions:notification_types:$type:$subtype";
174
175
                    $type_str = array();
176
177
					$type_str[0] = elgg_echo($type_key, array(), 'en');
178
                    $type_str[1] = elgg_echo($type_key, array(), 'fr');
179
					if ($type_str == $type_key) {
180
						// plugins can add to the list of mention objects by defining
181
						// the language string 'mentions:notification_types:<type>:<subtype>'
182
						continue;
183
					}
184
					$subject = elgg_echo('mentions:notification:subject', array($owner->name, $type_str[0]), 'en');
185
186
                    $subject .= ' / ' . elgg_echo('mentions:notification:subject', array($owner->name, $type_str[1]), 'fr');
187
188
					$body = elgg_echo('mentions:notification:body', array(
189
						$owner->name,
190
						$type_str[0],
191
						$link,
192
					), 'en');
193
194
                    $body .= elgg_echo('mentions:notification:body', array(
195
						$owner->name,
196
						$type_str[1],
197
						$link,
198
					), 'fr');
199
200
					$params = array(
201
						'object' => $object,
202
						'action' => 'mention',
203
					);
204
205
					// cyu - trigger the hook (we are re-routing the mentions to cp_notifications if it is activated)
206
					// please don't trigger if subtype is thewire
207
					if (elgg_is_active_plugin('cp_notifications') && strcmp($object->getSubtype(),'thewire') != 0) {
208
209
						if (strcmp($object->getSubtype(),'comment') == 0 || strcmp($object->getSubtype(),'thewire') == 0 || strcmp($object->getSubtype(),'discussion_reply') == 0)
210
							$container = $object->getContainerEntity();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ElggData as the method getContainerEntity() does only exist in the following sub-classes of ElggData: ElggAnswer, ElggBlog, ElggComment, ElggDiscussionReply, ElggEntity, ElggFile, ElggGroup, ElggObject, ElggPad, ElggPlugin, ElggQuestion, ElggSite, ElggUpgrade, ElggUser, ElggWidget, ElggWire, FakeEntity, FilePluginFile, MultiDashboard, SiteNotification, TheWireImage, ThemeSandboxObject, TidypicsAlbum, TidypicsBatch, TidypicsImage, UploadUsersFile, WidgetManagerWidget. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
211
						else
212
							$container = $object;
213
214
						$message = array(
215
							'cp_author' => $owner->name,
216
							'cp_content' => $container->title,
217
							'cp_link' => $link,
218
							'cp_msg_type' => 'cp_content_mention',
219
							'cp_to_user' => $user,
220
							'cp_content_desc' => $object->description,
0 ignored issues
show
Bug introduced by
The property description does not seem to exist in ElggData.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
221
						);
222
						elgg_trigger_plugin_hook('cp_overwrite_notification','all',$message);
223
					} else {
224
225
						notify_user($user->getGUID(), $owner->getGUID(), utf8_encode($subject), utf8_encode($body), $params);
226
					}
227
				}
228
			}
229
		}
230
	}
231
}
232
233
/**
234
 * Save mentions-specific info from the notification form
235
 *
236
 * @param type $hook
237
 * @param type $type
238
 * @param type $value
239
 * @param type $params
240
 */
241
function mentions_save_settings($hook, $type, $value, $params) {
242
	$notify = (bool) get_input('mentions_notify');
243
	$user = get_entity(get_input('guid'));
244
245
	if (!elgg_set_plugin_user_setting('notify', $notify, $user->getGUID(), 'mentions')) {
246
		register_error(elgg_echo('mentions:settings:failed'));
247
	}
248
249
	return;
250
}
251