-
Notifications
You must be signed in to change notification settings - Fork 1
/
ding_serendipity.module
444 lines (397 loc) · 15.2 KB
/
ding_serendipity.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
<?php
/**
* @file
* Proxy module assembling serendipity from sub modules
*/
define('DING_SERENDIPITY_FUNCTION_POSTFIX', '_serendipity_add');
/**
* Implements hook_menu()
*/
function ding_serendipity_menu() {
// Serendipity admin page
$items['admin/config/ding/serendipity'] = array(
'title' => 'Ding serendipity',
'description' => 'Ding serendipity settings and overview',
'page callback' => 'drupal_get_form',
'page arguments' => array('ding_serendipity_admin_form'),
'access arguments' => array('administer ding serendipity'),
'file' => 'ding_serendipity.admin.inc'
);
$items['admin/config/ding/serendipity/settings'] = array(
'title' => 'Settings',
'description' => 'View serendipity specific settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -90,
);
$items['admin/config/ding/serendipity/key_overview'] = array(
'title' => 'Key overview',
'description' => 'Get an overview of the current registered serendipity functions and keys',
'type' => MENU_LOCAL_TASK,
'page arguments' => array('ding_serendipity_admin_overview'),
'access arguments' => array('administer ding serendipity'),
'file' => 'ding_serendipity.admin.inc'
);
return $items;
}
/**
* Implements hook_permission().
*/
function ding_serendipity_permission() {
return array(
'administer ding serendipity' => array(
'title' => t('Administer Ding serendipity'),
),
);
}
/**
* Collect serendipity content from all modules implementing hook_serendipity_info.
* Set the module variable and ensure that the access callback and callback
* functions are set.
*/
function ding_serendipity_get_info() {
$callbacks = array();
foreach (module_implements('serendipity_info') as $module) {
$info = call_user_func($module . '_serendipity_info');
$info_return = array();
if (isset($info) && is_array($info)) {
foreach ($info as $key => $value) {
// Set module information, and create the object name.
$info[$key]['module'] = $module;
$name = $module . '_' . $key;
// Use our default access callback if no specific is set.
if (!isset($info[$key]['access callback'])) {
$info[$key]['access callback'] = 'ding_serendipity_access';
}
// If there's no callback, assume the standard naming convention.
if (!isset($info[$key]['callback'])) {
$info[$key]['callback'] = $name . DING_SERENDIPITY_FUNCTION_POSTFIX;
}
$info_return[$name] = $info[$key];
}
$callbacks = array_merge($callbacks, $info_return);
}
}
return $callbacks;
}
/**
* Collect content matching the given context.
* Results are cached by context for 10 minutes.
*
* @param array $context
* Possible option values are:
* - "view_mode": The view mode to use when viewing the content collected through serendipity.
* - "sort_weight": If true the collected content will be sorted by weight.
* - "max": The maximum amount of items in the final content array.
* - "min": The minimum amount of items in the content array, if there are fewer system will try to
* add content from the fallback hook.
* - "random": If true the results will be randomized.
* The other context values should be keys which represent the context of this call as well as additional
* values which are valuable for the serendipity function. A list of active keys can be seen on the serendipity
* admin page: /admin/config/ding/serendipity/key_overview. If the values for any given key is a token the
* the ding_serendipity_serendipity_context_alter function will replace this value with the appropriate
* value from the url if applicable.
* @see ding_serendipity_access
* This default access callback uses the keys of the context array to compare with the keys from
* hook_serendipity_info to determine if a serendipity function is eligible to provide content.
*
* @return array $results
*/
function ding_serendipity_fetch($context = NULL) {
// Allow modules to modify the provided context
drupal_alter('serendipity_context', $context);
if(variable_get('ding_serendipity_enable_cache', FALSE)) {
// Caching of serendipity
$cache_id = implode(':', $context);
$cache = cache_get($cache_id, 'cache_variable');
if (!empty($cache) && REQUEST_TIME < $cache->expire) {
$cache->data['cache'] = REQUEST_TIME . ':' . $cache->expire . '<br/>';
return $cache->data;
}
}
// Collect all serendipity plugins
$info = ding_serendipity_get_info();
$results = array(
'source' => 'raw',
'items' => array(),
'context' => $context,
'plugins' => $info,
);
$isslow = FALSE;
foreach ($info as $name => $values) {
// Skip additional serendipity hooks if we have already spent too much time
if (ding_serendipity_isslow('serendipity', variable_get('ding_serendipity_isslow_timeout', 10))) {
$isslow = TRUE;
$results['is_slow'] = true;
break;
}
$content = array();
// Determine access to the current serendipity result
if (call_user_func($values['access callback'], $context, $values['keys'])) {
// If access is accepted then determine if the #callback function exists.
if (function_exists($values['callback'])) {
// If it is found get content from the #callback function.
$content = call_user_func($values['callback'], $context);
}
else {
// If the #callback function could not be found commit a watchdog warning.
$path = drupal_get_path('module', $values['module']);
watchdog('ding_serendipity', "Serendipity can't find function: @func", array('@func' => $values['callback']), WATCHDOG_WARNING, $path);
drupal_set_message(t("Serendipity can't find function: @func", array('@func' => $values['callback'])), 'error');
}
} else {
$results['plugins'][$name]['status'] = "No access";
}
// Append source information
// The 'info' array may contain all sorts of extra details on the resulting object
// Info is kept seperate to preserve caching of objects
foreach ($content as $index => $item) {
$content[$index]['source'] = $values;
$content[$index]['source']['info'] = isset($content[$index]['info']) ? $content[$index]['info'] : array();
}
$results['items'] = array_merge($results['items'], $content);
}
// Allow for alteration of the results.
// Removing items are recommended in this hook
drupal_alter('ding_serendipity_results', $results);
// Sort the array by it's ['weight'].
if ($context['sort_weight'] == TRUE && !empty($results['items']) && !$context['random']) {
uasort($results['items'], 'drupal_sort_weight');
}
// Randomize will overwrite sort_weight.
if ($context['random'] == TRUE) {
shuffle($results['items']);
}
// Append fallback content if submodules fail to deliver required count.
if (count($results['items']) < $context['min']) {
ding_serendipity_append_fallback($results['items'], $context);
}
// Skip caching of partial results
if (!$isslow && variable_get('ding_serendipity_enable_cache', FALSE)) {
$expire = variable_get('ding_serendipity_cache_lifetime', 600);
cache_set($cache_id, $results, 'cache_variable', REQUEST_TIME + $expire);
}
return $results;
}
/**
* Default serendipity access function
*
* @param array $context
* An array of key => value pairs where the keys possible context values.
* @param array keys
* An array of values representing the context values with have to be present before
* the current serendipity function is called.
*
* @return boolean
* Return true if all the values in the keys array are present in the context array.
*/
function ding_serendipity_access($context = array(), $keys = array()) {
$result = array_intersect(array_keys($context), $keys);
return (!empty($result) && count($result) == count($keys));
}
/**
* implements hook_serendipity_context_alter()
*/
function ding_serendipity_serendipity_context_alter(&$context) {
$data = array();
$path = isset($context['path']) ? $context['path'] : NULL;
// If this is a taxonomy page populate this data entry
if ($term = menu_get_object('taxonomy_term', 2, $path)) {
$data['term'] = $term;
}
// If this is a user page populate this data entry
if ($account = menu_get_object('user', 1, $path)) {
$data['user'] = $account;
}
// If this is a ding object page populate this data entry
if ($obj = menu_get_object('ding_entity', 2, $path)) {
$data['ding_entity'] = $obj;
}
// If this is a node page populate this data entry
if ($node = menu_get_object('node', 1, $path)) {
$data['node'] = $node;
}
// Insert user fallback
if (!isset($context['user']) && !isset($context['current-user'])) {
$context['current-user'] = '[current-user:uid]';
}
// Run token replace on context values to provide current ids.
foreach ($context as $key => &$value) {
$value = token_replace($value, $data);
}
// Frontpage taxonomy does not work with tokens
if (drupal_is_front_page() && isset($context['taxonomy_tid'])) {
$context['taxonomy_tid'] = 5;
}
}
/**
* Get a render array for the context.
*
* @param array $context
* An array of context and option values.
* Possible option values are:
* - "view_mode": The view mode to use when viewing the content collected through serendipity.
* - "sort_weight": If true the collected content will be sorted by weight.
* - "max": The maximum amount of items in the final content array.
* - "min": The minimum amount of items in the content array, if there are fewer system will try to
* add content from the fallback hook.
* - "random": If true the results will be randomized.
* The other context values should be keys which represent the context of this call as well as additional
* values which are valuable for the serendipity function. A list of active keys can be seen on the serendipity
* admin page: /admin/config/ding/serendipity/key_overview.
*
* @return array $results
*/
function ding_serendipity_render($context = NULL) {
global $user;
$rendered = array();
// Fill in the default options.
$context += array(
'view_mode' => 'full',
'sort_weight' => FALSE,
'max' => 0,
'min' => 0,
'random' => FALSE,
);
// Fetch the list of ids from all serendipity plugins based on $context
$results = ding_serendipity_fetch($context);
$items = $results['items'];
// Jump ship if we have no results.
if (empty($items)) {
return array();
}
// Remove any exceeding items.
if ($context['max'] > 0 && count($items) > $context['max']) {
array_splice($items, $context['max']);
}
// Combine all the ids of a single entity type, so we can utilize the
// ENTITY_load_multiple() function.
$sources = array();
$load_multiple = array();
foreach ($items as $item) {
$load_multiple[$item['type']][] = rawurldecode($item['id']);
$sources[$item['type'] . '_' . rawurldecode($item['id'])] = $item['source'];
}
// Add the render arrays to the result.
foreach ($load_multiple as $type => $ids) {
// Get the objects of the current entity type.
// And run through the all the objects, using the ENTITY_view() function to
// get the render array.
$conditions = array();
if($type == 'ting_object') {
$conditions['ding_entity_id'] = $ids;
$ids = FALSE;
}
$objects = entity_load($type, $ids, $conditions);
foreach ($objects as $oid => $object) {
$content = entity_view($type, array($object), $context['view_mode']);
// Eliminate the type & id arrays
$content = current(current($content));
$iid = $oid;
if (!empty($object->ding_entity_type) && $object->ding_entity_type == 'ding_entity') {
$iid = $object->ding_entity_id;
}
// Extract optional source information ( via ?debug=s )
if (isset($_GET['debug']) && $_GET['debug'] == 's') {
$source = $sources[$type . '_' . $iid];
$content['#source'] = $results['source'] . ' > ' . $source['title'] ;
if (isset($source['info'])) {
foreach($source['info'] as $key => $value) {
$content['#source'] .= "<br/>$key : $value ";
}
}
}
$rendered[] = $content;
}
}
if (isset($_GET['debug']) && $_GET['debug']=='s') {
b14dpm(-1,$results);
}
return $rendered;
}
/**
* Implements hook_ctools_plugin_directory().
*/
function ding_serendipity_ctools_plugin_directory($module, $plugin) {
if ($module == 'ctools') {
return 'plugins/' . $plugin;
}
}
/**
* Append non serendipity content to assure number of items
*
* @param array $list
* The list of collected content to be filled with fallback content.
* @param array $context
* The current context array.
*/
function ding_serendipity_append_fallback(&$list, $context) {
$limit = $context['min'] - count($list);
if ($limit < 1) {
return;
}
$ids = array();
foreach ($list as $item) {
$ids[] = $item['id'];
}
$items = module_invoke_all('serendipity_fallback', $ids, $context);
$list = array_merge($list, $items);
}
/**
* Ask if something is to slow.
*
* The way this works is, you either use the default $group, or you make up
* your own.
* The first time a you test a group (which in the default group is in an init
* hook), the timestamp is saved. Next time you check the group it tells you if
* you've exceeded your max time since the first call.
*
* @param $group
* The name of the group. The default group name is 'default', use this if
* you want to use the default group, but with a different max time.
* @param $time
* This is the max amount of time you want to pass since your first call.
*
* @return
* Returns TRUE if your script is to slow, and FALSE if you're withing your
* boundaries.
*/
function ding_serendipity_isslow($group = 'default', $time = 5) {
$groups = &drupal_static(__FUNCTION__, array());
if (!isset($groups[$group])) {
$groups[$group] = microtime(TRUE);
}
$too_slow = (microtime(TRUE) - $groups[$group]) > $time;
if ($too_slow) {
// Debugging if it's too slow.
$backtrace = debug_backtrace();
if(user_access('access devel information')) {
drupal_set_message(t(
'isslow(@group) @func():@line',
array(
'@func' => $backtrace[1]['function'],
'@line' => $backtrace[1]['line'],
'@group' => $group
)
));
}
watchdog(
'Is slow',
'isslow(@group) @func():@line',
array(
'@func' => $backtrace[1]['function'],
'@line' => $backtrace[1]['line'],
'@group' => $group,
),
WATCHDOG_ALERT
);
}
return $too_slow;
}
/**
* Implements hook_init().
*
* Initate the first isslow, so the 'default' group is set.
*/
function ding_serendipity_init() {
ding_serendipity_isslow();
}