Project

General

Profile

Download (32.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2

    
3
/*
4
 * @todo hide default value php code field in widget settings; values in there are not used.
5
 */
6

    
7
/*
8
 * Definition of privacy levels
9
 */
10
define('PRIVACY_CONTACT_PRIVATE', 'ContactPrivate');
11
define('PRIVACY_PRIVATE', 'Private');
12
define('PRIVACY_PUBLIC', 'Public');
13

    
14
/**
15
 * Implementation of hook_perm()
16
 *
17
 * Valid permissions for this module
18
 * @return array An array of valid permissions for the portfolio module
19
 */
20
function expertsdb_email_perm() {
21
	return array(
22
    	'view private expertsdb_email addresses',
23
  		'access expertsdb_email mail form',
24
  		'create email for other users',
25
	//TODO which else permission are required?
26
	);
27
}
28

    
29
/**
30
 * Implementation of hook_help().
31
 *
32
 * @param unknown_type $section
33
 * @return unknown
34
 */
35
function expertsdb_email_help($section) {
36
	switch ($section) {
37
		case 'admin/modules#description':
38
			return t('Defines a field type for email addresses. Data will be integrated as serialized array into the according content type database. <em>Note: Requires content.module.</em>');
39
	}
40
}
41

    
42
/**
43
 * Implementation of hook_menu().
44
 *
45
 * @param unknown_type $may_cache
46
 * @return unknown
47
 */
48
function expertsdb_email_menu($may_cache) {
49
	$items = array();
50
	if ($may_cache) {
51

    
52
		$items[] = array('path' => 'expertsdb_email',
53
      'title' => t('Email Contact Form'),
54
      'callback' => 'expertsdb_email_mail_page',
55
      'access' => user_access('access content'),
56
      'type' => MENU_CALLBACK,
57
		);
58

    
59
		// implement js callback
60
		$items[] = array(
61
      'path' => 'expertsdb_email/widget/js',
62
      'callback' => 'expertsdb_email_widget_js',
63
      'access' => user_access('access content'),
64
      'type' => MENU_CALLBACK,
65
		);
66
	}
67
	return $items;
68
}
69

    
70
/**
71
 * Implementation of hook_user().
72
 */
73
function expertsdb_email_user($op, &$edit, &$account, $category = NULL) {
74

    
75
	switch ($op) {
76
		case 'update':
77

    
78
			// only invoke update, if user updated his account manually
79
			if(!$edit['mail'] || !count($edit)>1 || !$edit['timezone'] || $category != 'account') return;
80

    
81
			// find cck expertsdb_email field tables
82
			// search through them for matching user ids and load those nodes
83
			$types = content_types();
84

    
85
			// Find the table and columns to search through, if the same
86
			// table comes up in more than one content type, we only need
87
			// to search it once.
88
			$search_tables = array();
89
			$field_names = array();
90
			foreach ($types as $type_name => $type) {
91
				foreach ($type['fields'] as $field) {
92
					// Only add tables where the expertsdb_field is present
93
					if ($field['type'] == 'expertsdb_email') {
94
						$db_info = content_database_info($field);
95
						$search_tables[$db_info['table']] = $db_info['columns']['expertsdb_email']['column'];
96
						$field_names[$db_info['table']] = $field['field_name'];
97
					}
98
				}
99
			}
100

    
101
			foreach ($search_tables as $table => $column) {
102
				$ids = db_query(db_rewrite_sql("SELECT DISTINCT(n.nid), " . $column . " FROM {node} n LEFT JOIN {" . $table . "} f ON n.vid = f.vid WHERE n.uid=" . $account->uid . " AND f." . $column . " IS NOT NULL AND n.status = 1"));
103
				while ($data = db_fetch_object($ids)) {
104
					// load the node and extract the email data
105
					$node = node_load($data->nid);
106
					$node_field = $node->$field_names[$table];
107

    
108
					if($node_field && strstr($node_field[0]['expertsdb_email'],':{')){
109
						$node_field = unserialize($node_field[0]['expertsdb_email']);
110

    
111
						// check, if new email is already present in email list
112
						// if present, set to preferred; set all other emails to not preferred
113
						foreach($node_field as $delta => $item){
114
							if($item['email'] == $edit['mail']){
115
								if($item['preferred_email']['preferred_email'] === 'preferred_email') return; // nothing to do!
116
								$node_field[$delta]['preferred_email']['preferred_email'] = 'preferred_email';
117
								$email_present = TRUE;
118
							}
119
							else{
120
								$node_field[$delta]['preferred_email']['preferred_email'] = FALSE;
121
							}
122
						}
123

    
124
						// add email to the top if not already present and set preferred
125
						if(!$email_present){
126
							$delta++;
127
							$node_field[$delta]['email'] = $edit['mail'];
128
							$node_field[$delta]['preferred_email']['preferred_email'] = 'preferred_email';
129
						}
130
					}
131
					// clean up and sort
132
					_expertsdb_email_cleanup_and_sort($node_field);
133

    
134
					// serialize data and write back to db
135
					_expertsdb_email_serialize($node_field);
136

    
137
					// write to db
138
					$node->$field_names[$table] = $node_field;
139
					node_save($node);
140

    
141
					// notify user about change
142
					if($email_present){
143
						drupal_set_message(t('Your user account email address has been set as your preferred email address.'));
144
					}
145
					else{
146
						drupal_set_message(t('Your user account email address has been added to your list as your preferred email address.'));
147
					}
148

    
149
				}
150
			}
151

    
152
			return;
153
	}
154
}
155

    
156
/**
157
 * Implementation of hook_field_info().
158
 *
159
 * @return unknown
160
 */
161
function expertsdb_email_field_info() {
162
	return array(
163
    'expertsdb_email' => array('label' => t('Expertsdb E-Mail')),
164
	);
165
}
166

    
167
/**
168
 *  Implementation of hook_field_settings().
169
 *
170
 * @param unknown_type $op
171
 * @param unknown_type $field
172
 * @return unknown
173
 */
174
function expertsdb_email_field_settings($op, $field) {
175

    
176
	switch ($op) {
177

    
178
		case 'database columns':
179
			$columns = array(
180
        'expertsdb_email' => array('type' => 'mediumtext', 'not null' => FALSE),
181
			);
182
			return $columns;
183

    
184
		case 'form':
185
			$form = array();
186

    
187
			$form['user_email_default'] = array(
188
          '#type' => 'checkbox',
189
          '#title' => t('Use user account email as default'),
190
          '#default_value' => isset($field['user_email_default']) ? $field['user_email_default'] : 1,
191
          '#description' => t('Checking will force the users account email into the list of email addresses and will keep the preferred email address in sync with the user account.'),
192
			);
193

    
194
			// disable multiple
195
			$form['multiple'] = array('#type' => 'hidden','#value' => '0');
196
			return $form;
197

    
198
		case 'save':
199
			return array('user_email_default');
200

    
201
		case 'callbacks': //pairs up with cck_fullname_field::view
202
			return array(
203
        'view' => CONTENT_CALLBACK_CUSTOM,
204
			);
205
	}
206
}
207

    
208
/**
209
 * Implemantation of hook_field()
210
 *
211
 * @param unknown_type $op
212
 * @param unknown_type $node
213
 * @param unknown_type $field
214
 * @param unknown_type $items
215
 * @param unknown_type $teaser
216
 * @param unknown_type $page
217
 * @return unknown
218
 */
219
function expertsdb_email_field($op, &$node, $field, &$items, $teaser, $page) {
220
	switch ($op) {
221

    
222
		case 'view':
223
			$context = $teaser ? 'teaser' : 'full';
224
			$formatter = isset($field['display_settings'][$context]['format']) ? $field['display_settings'][$context]['format'] : 'default';
225
			$items = content_format($field, $items, $formatter, $node);
226
			if(!empty($items) && is_array($items) && count($items) > 0){
227
				return theme('expertsdb_email_container', $node, $field, $items, $teaser, $page);
228
			}
229
			return;
230
	}
231
}
232

    
233
/**
234
 * Implementation of hook_widget_info().
235
 *
236
 * @return unknown
237
 */
238
function expertsdb_email_widget_info() {
239
	return array(
240
    'expertsdb_email' => array(
241
      'label' => t('Text Fields for Email Addresses'),
242
      'field types' => array('expertsdb_email'),
243
	),
244
	);
245
}
246

    
247
/**
248
 * Implementation of hook_widget_settings().
249
 *
250
 * @param unknown_type $op
251
 * @param unknown_type $widget
252
 * @return unknown
253
 */
254
function expertsdb_email_widget_settings($op, $widget) {
255

    
256
	switch ($op) {
257

    
258
		case 'form':
259
			$form = array();
260
			$form['size'] = array(
261
        '#type' => 'textfield',
262
        '#title' => t('Size'),
263
        '#default_value' => isset($widget['size']) ? $widget['size'] : 60,
264
        '#required' => FALSE,
265
        '#description' => t('Size of textfield'),
266
			);
267

    
268
			return $form;
269

    
270
		case 'validate':
271
			if (!empty($widget['size']) && (!is_numeric($widget['size']) || intval($widget['size']) != $widget['size'] || $widget['size'] <= 0)) {
272
				form_set_error('size', t('"Size" must be a positive integer.'));
273
			}
274
			break;
275

    
276
		case 'save':
277
			return array('size');
278

    
279
	}
280
}
281

    
282
/**
283
 * Implementation of hook_widget().
284
 *
285
 * @param unknown_type $op
286
 * @param unknown_type $node
287
 * @param unknown_type $field
288
 * @param unknown_type $node_field
289
 * @return unknown
290
 */
291
function expertsdb_email_widget($op, &$node, $field, &$node_field) {
292

    
293
	switch ($op) {
294

    
295
		case 'prepare form values':
296
			// unserialize and prepare data
297
			_expertsdb_email_widget_prepare($node_field);
298

    
299
			// get posted values in both node edit and profile edit mode
300
			if ($_POST[$field['field_name']] || $_POST[$field['type_name'].'_node_form'][$field['field_name']]) {
301
				$node_field = ($_POST['form_id'] == 'user_edit') ?  $_POST[$field['type_name'].'_node_form'][$field['field_name']] : $_POST[$field['field_name']];
302
				unset($node_field['count'], $node_field['more-url'], $node_field['more']);
303
			}
304
			return;
305

    
306
		case 'form':
307
			$form = array();
308
			$form[$field['field_name']] = array(
309
        '#tree' => TRUE,
310
        '#theme' => 'expertsdb_email_widget_form',
311
        '#type' => 'fieldset',
312
        '#collapsible' => TRUE,
313
        '#collapsed' => FALSE,
314
        '#title' => t($field['widget']['label']),
315
        '#description' => t($field['widget']['description']),
316
        '#weight' => $field['widget']['weight'],
317
			);
318

    
319
			// render multiple values
320
			if(module_exists('jquery_plugin')){
321
				// pull in jquery checkbox plugin to make radioCheckboxes
322
				jquery_plugin_add('checkboxes');
323
			}
324
			// add javascript for 'more' button
325
			drupal_add_js(drupal_get_path('module', 'expertsdb_email') .'/expertsdb_email.js');
326

    
327
			$delta = 0;
328
			// Render expertsdb_email fields for all the entered values
329
			if(is_array($node_field)){
330
				foreach ($node_field as $data) {
331
					if (is_array($data) && $data['email']) {
332
						_expertsdb_email_widget_form($form[$field['field_name']][$delta], $field, $data, $delta);
333
						$delta++;
334
					}
335
				}
336
			}
337
			// Render one more new expertsdb_email field
338
			_expertsdb_email_widget_form($form[$field['field_name']][$delta], $field, array(), $delta);
339

    
340
			// Create a wrapper for additional fields
341
			$form[$field['field_name']]['wrapper'] = array(
342
          '#type' => 'markup',
343
          '#value' => '<div id="' . str_replace('_', '-', $field['field_name']) . '-wrapper" class="clear-block"></div>',
344
			);
345

    
346
			// Add 'More' Javascript Callback
347
			$form[$field['field_name']]['more-url'] = array(
348
          '#type' => 'hidden',
349
          '#value' => url('expertsdb_email/widget/js/' . $field['type_name'] . '/' . $field['field_name'], NULL, NULL, TRUE),
350
          '#attributes' => array('class' => 'more-email-addresses'),
351
          '#id' => str_replace('_', '-', $field['field_name']) . '-more-url',
352
			);
353

    
354
			// Add Current Field Count
355
			$form[$field['field_name']]['count'] = array(
356
          '#type' => 'hidden',
357
          '#value' => $delta,
358
          '#id' => str_replace('_', '-', $field['field_name']) . '-count',
359
			);
360

    
361
			// Add More Button
362
			$form[$field['field_name']]['more'] = array(
363
        '#name' => 'more',
364
        '#id' => str_replace('_', '-', $field['field_name']) . '-more',
365
        '#weight' => 10,
366
				'#type' => 'views_imagebutton',
367
				'#title' => t('More Emails'),
368
    		'#image' => drupal_get_path('module','expertsdb_email') . '/images/button_add_element.png',  // provide the path to your image here
369
    		'#default_value' => t('More emails'), // original value of button text
370
			);
371

    
372
			return $form;
373

    
374
		case 'validate':
375
			if (is_array($node_field)) {
376

    
377
				$email_counter = 0;
378
				$preferred_counter = 0;
379
				foreach ($node_field as $delta => $item) {
380
					if(is_numeric($delta) && $item['email']){
381
						$email_counter ++;
382
					}
383
					// check for empty or invalid email addresses
384
					if(is_numeric($delta) && $item['email'] != '' && !valid_email_address(trim($item['email']))) {
385
						form_set_error($field['field_name'] .']['. $delta. '][email', t('"%mail" is not a valid email address',array('%mail' => $item['expertsdb_email'])));
386
					}
387

    
388
					// check for multiple preferred emails and if new preferred email already exists as another users email account
389
					if(is_numeric($delta) && $item['preferred_email']['preferred_email'] === 'preferred_email'){
390
						$preferred_counter ++;
391

    
392
						global $user;
393
						// check, if new preferred email is not the current users account email
394
						if(!user_access('create email for other users') && $user->mail != $item['email']){
395
							if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $user->uid, $item['email'])) > 0) {
396
								form_set_error($field['field_name'] .']['. $delta. '][email', t('Sorry, but "%mail" is already in use as preferred email address of another user account. Please choose a different preferred email address.',array('%mail' => $item['email'])));
397
							}
398
						}
399
						else if(user_access('create email for other users')){
400
							$alien_user = user_load(array('uid' => $node->uid));
401
							if($alien_user->mail != $item['email']){
402
								if (db_num_rows(db_query("SELECT uid FROM {users} WHERE uid != %d AND LOWER(mail) = LOWER('%s')", $alien_user->uid, $item['email'])) > 0) {
403
									form_set_error($field['field_name'] .']['. $delta. '][email', t('Sorry, but "%mail" is already in use as preferred email address of another user account. Please choose a different preferred email address.',array('%mail' => $item['email'])));
404
								}
405
							}
406
						}
407

    
408
						// warn in case of multiple preferred email addresses
409
						if($preferred_counter != 1){
410
							form_set_error($field['field_name'] .']['. $delta. '][email', t('Please select exactly one preferred email address.'));
411
						}
412

    
413
						if($email_counter < 1 && $field['required']){
414
							form_set_error($field['field_name'] .'][0][email', t('Please provide at least one email address as your preferred email address.'));
415
						}
416

    
417
					}
418
				}
419
			}
420
			return;
421

    
422
		case 'process form values':
423
			// run a cleanup cycle
424
			if(!strstr($node_field[0]['expertsdb_email'],':{')){
425
				_expertsdb_email_cleanup_and_sort($node_field);
426
			}
427
			// apply some trimming
428
			_expertsdb_email_widget_process($node_field);
429
			return;
430

    
431
		case 'submit':
432
			if($field['user_email_default']){
433
				// make sure, that the users account email address is present
434
				_expertsdb_email_force_default($node_field);
435
			}
436

    
437
			// do not save empty values and bring preferred email to the top
438
			_expertsdb_email_cleanup_and_sort($node_field);
439
			// apply some trimming
440
			_expertsdb_email_widget_process($node_field);
441

    
442
			if($field['user_email_default']){
443
				// sync the (potentially new) preferred email addres to user account
444
				_expertsdb_email_sync_primary_email($node->uid, $node_field[0]['email']);
445
			}
446

    
447
			// serialize data
448
			_expertsdb_email_serialize($node_field);
449
			return;
450

    
451
	}
452
}
453

    
454
/**
455
 * AHAH generation of additional form fields
456
 *
457
 * @param unknown_type $type_name
458
 * @param unknown_type $field_name
459
 */
460
function expertsdb_email_widget_js($type_name, $field_name) {
461
	$field = content_fields($field_name, $type_name);
462
	$type = content_types($type_name);
463
	// get the correct delta and field_name depending on being in node_form or user_edit
464
	// $delta = ($_POST['form_id'] == 'user_edit') ? $_POST[$type['type'].'_node_form'][$field_name]['count']: $_POST[$field_name]['count'];
465
	$delta = $_POST[$field_name]['count'];
466
	$form = array();
467

    
468
	_expertsdb_email_widget_form($form, $field, $node_field, $delta);
469

    
470
	// Assign parents matching the original form
471
	foreach (element_children($form) as $key) {
472
		$form[$key]['#parents'] = array($field_name, $delta, $key);
473
	}
474

    
475
	// Add names, ids, and other form properties
476
	foreach (module_implements('form_alter') as $module) {
477
		$function = $module .'_form_alter';
478
		$function('expertsdb_email_widget_js', $form);
479
	}
480
	$form = form_builder('expertsdb_email_widget_js', $form);
481

    
482
	// if form is rendered as part of the user profile page, we need to alter name and id of newly generated form elements
483
	/*	if($_POST['form_id'] == 'user_edit'){
484
	foreach (element_children($form) as $key) {
485
	$element_name = explode('[',$form[$key]['#name']);
486
	array_walk($element_name,'_expertsdb_email_widget_alter_elements');
487
	$form[$key]['#name'] = $type['type'] . '_node_form' . '[' . implode('][',$element_name).']';
488
	}
489
	}*/
490

    
491
	$output = drupal_render($form);
492

    
493
	print drupal_to_js(array('status' => TRUE, 'data' => $output));
494
	exit;
495
}
496

    
497
/**
498
 * Helper function renders the expertsdb_email widget only for multiple values.
499
 *
500
 * @param unknown_type $form_item
501
 * @param unknown_type $field
502
 * @param unknown_type $node_field
503
 * @param integer $delta
504
 */
505
function _expertsdb_email_widget_form(&$form_item, $field, $node_field, $delta = 0) {
506
	global $user;
507
	$form_item = array(
508
    '#tree' => TRUE,
509
    '#theme' => 'expertsdb_email_widget_form_row',
510
	);
511

    
512
	$default_value = "";
513
	// pull in users account email address as default value
514
	if ($delta === 0 && $field['user_email_default']) {
515
		$default_value = $user->mail;
516
	}
517

    
518
	// always use the email address set in the user account as default value for the first item
519
	$form_item['email'] = array(
520
		'#type' => 'textfield',
521
		'#title' => ($delta === 0) ? t('Email address') : NULL,
522
		'#default_value' =>  ($node_field['email']) ? $node_field['email'] : (($default_value) ? $default_value : NULL),
523
		'#required' =>  FALSE,
524
		'#maxlength' => 255,
525
		'#size' => isset($field['widget']['size']) ? $field['widget']['size'] : 60,
526
		'#description' => ($delta === 0) ? t('Enter a fully qualified email address here.') : NULL,
527
	);
528

    
529
	// add preferred_email flag for multiple values; first item is always the preferred email
530
	$form_item['preferred_email'] = array(
531
  	'#type' => 'checkboxes',
532
		'#title' => ($delta === 0) ? t('Preferred email') : NULL,
533
   	'#description' => ($delta === 0) ? t("Check, if this address is your preferred email address.") : NULL,
534
    '#required' => FALSE,
535
    '#default_value' => ($node_field['preferred_email']['preferred_email'] === 'preferred_email') ? 'preferred_email' : (($delta === 0) ? 'preferred_email' : NULL),
536
		'#attributes' => array(
537
			'class' => 'preferred-email',
538
	),
539
    '#options' => array(
540
    	'preferred_email' => t("Preferred email address"),
541
	),
542
	);
543
}
544

    
545
function _expertsdb_email_widget_process(&$node_field) {
546
	foreach($node_field as $delta => $value) {
547
		if (is_numeric($delta)) {
548
			// Trim whitespace from email and
549
			$node_field[$delta]['email'] = check_plain(trim($node_field[$delta]['email']));
550
		}
551
	}
552
}
553

    
554
function _expertsdb_email_widget_alter_elements(&$element){
555
	$element = preg_replace('@\]@', '', $element);
556
}
557

    
558
/**
559
 * Theme the display of a single form row
560
 *
561
 * @param unknown_type $element
562
 * @return unknown
563
 */
564
function theme_expertsdb_email_widget_form_row($element) {
565
	$output = '';
566
	$output .= '<div class="expertsdb-email-field-row clear-block"><div class="expertsdb-email-field-subrow clear-block">';
567
	$output .= '<div class="expertsdb-email-field-preferred-email preferred-email-field-column">' . drupal_render($element['preferred_email']) . '</div>';
568
	$output .= '<div class="expertsdb-email-field-expertsdb-email">' . drupal_render($element['email']) . '</div>';
569
	$output .= '</div>';
570
	$output .= '</div>';
571
	return $output;
572
}
573

    
574
/**
575
 * Theme the display of the entire expertsdb_email set
576
 *
577
 * @param unknown_type $element
578
 * @return unknown
579
 */
580
function theme_expertsdb_email_widget_form($element) {
581
	// pull in the stylesheet
582
	drupal_add_css(drupal_get_path('module', 'expertsdb_email') .'/expertsdb_email_form.css');
583
	$output = drupal_render($element);
584
	return $output;
585
}
586

    
587
/**
588
 * Theme to display a complete container with all email addresses in view mode
589
 *
590
 * @param unknown_type $node
591
 * @param unknown_type $field
592
 * @param unknown_type $items
593
 * @param unknown_type $teaser
594
 * @param unknown_type $page
595
 * @return unknown
596
 */
597
function theme_expertsdb_email_container($node, $field, $items, $teaser, $page){
598
	// pull in the stylesheet
599
	drupal_add_css(drupal_get_path('module', 'expertsdb_email') .'/expertsdb_email_view.css');
600
	$output = '';
601
	$output .= '<div class="expertsdb-email-container">';
602
	$output .= theme('field', $node, $field, $items, $teaser, $page);
603
	$output .= '</div>';
604
	return $output;
605
}
606

    
607

    
608
/**
609
 * Helper function to unserailize serialized data
610
 *
611
 * @param unknown_type $node_field
612
 */
613
function _expertsdb_email_widget_prepare(&$node_field){
614
	// only prepare, if data is actually serialized
615
	if(strstr($node_field[0]['expertsdb_email'],':{')){
616
		$node_field[0] = unserialize($node_field[0]['expertsdb_email']);
617
		if(count($node_field) > 0){
618
			// return content of first array element
619
			$node_field = $node_field[0];
620
		}
621
	}
622
}
623

    
624
/**
625
 * Helper function to serialize data
626
 *
627
 * @param unknown_type $node_field
628
 */
629
function _expertsdb_email_serialize(&$node_field){
630
	$node_field = array(array('expertsdb_email' => serialize($node_field)));
631
}
632

    
633
/**
634
 * function to overwrite the user account email address with the newly set preferred email address
635
 *
636
 * @param unknown_type $new_mail
637
 */
638
function _expertsdb_email_sync_primary_email($uid = FALSE, $new_mail = FALSE){
639
	if(!$new_mail || !$uid) return;
640

    
641
	global $user;
642
	// determine, wether actual user is the owner of this node
643
	if($foreign_account = ($user && $uid != $user->uid)){
644
		// replace current user object with authors user object
645
		$account = user_load(array('uid' => $uid));
646
		
647
	} 
648
	else {
649
		$account = $user;	
650
	}
651
	if($account && $new_mail != $account->mail){
652
		// invoke account update: write preferred email address to users account
653
		$result = user_save($account,array('mail' => $new_mail));
654
		drupal_set_message($foreign_account? t('The users preferred email address has been set as his user account email.') : t('Your preferred email address has been set as your user account email.'));
655
	}
656

    
657
}
658

    
659
/**
660
 * Function to ensure, that the users account email is present in the list of emails
661
 * which might occure in case of submitting a completely emptied form
662
 * or by submitting a form, where no email is set to preferred
663
 *
664
 * @param array $node_field
665
 */
666
function _expertsdb_email_force_default(&$node_field){
667
	global $user;
668
	$preferred_email = FALSE;
669
	$account_email = array();
670

    
671
	// Remove the JS helper fields
672
	unset($node_field['count'], $node_field['more-url'], $node_field['more']);
673

    
674
	foreach($node_field as $delta => $data){
675
		if($data['preferred_email']['preferred_email'] === 'preferred_email'){
676
			$preferred_email = $data['email'];
677
		}
678
		if($data['email'] == $user->mail){
679
			$account_email = array($user->mail => $delta);
680
		}
681
	}
682
	// inject users account email, if not present and if no preferred email is choosen
683
	if(count($account_email)<1 && !$preferred_email){
684
		$default = array('email' => $user->mail, 'preferred_email' => array('preferred_email' => 'preferred_email'));
685
		array_unshift($node_field,$default);
686
		drupal_set_message(t("Your account email address has been re-appended to the list of your email addresses."));
687
		return;
688
	}
689

    
690
	if(!$preferred_email){
691
		$node_field[$account_email[$user->mail]]['preferred_email']['preferred_email'] = 'preferred_email';
692
	}
693
}
694

    
695
/**
696
 * Function to remove unwanted elements from the node_field array
697
 * and to move the preffered email address to the top of the list
698
 *
699
 * @param array $node_field
700
 */
701
function _expertsdb_email_cleanup_and_sort(&$node_field){
702
	$save_field = array();
703
	$registered_emails =array();
704

    
705
	// Remove the JS helper fields
706
	unset($node_field['count'], $node_field['more-url'], $node_field['more']);
707

    
708
	// keep privacy settings
709
	array_push($save_field,$node_field['custom_privacy']);
710

    
711
	foreach ($node_field as $delta => $value) {
712
		if (!empty($value['email']) || $delta == 0) {
713
			// skip duplicates emails
714
			if(in_array($value['email'], $registered_emails)){
715
				continue;
716
			}
717
			// register email to avoid duplicates
718
			array_push($registered_emails, $value['email']);
719

    
720
			// resort email addresses; preferred address goes to top
721
			if($node_field[$delta]['preferred_email'] && $node_field[$delta]['preferred_email']['preferred_email'] === 'preferred_email'){
722
				// put email as first element into the list of emails to save
723
				array_unshift($save_field,$node_field[$delta]);
724
			}else{
725
				$node_field[$delta]['preferred_email']['preferred_email'] = FALSE;
726
				array_push($save_field,$node_field[$delta]);
727
			}
728
		}
729
	}
730
	$node_field = $save_field;
731
}
732

    
733
/**
734
 * Implementation of hook_field_formatter_info().
735
 *
736
 * @return array array of available formats
737
 */
738
function expertsdb_email_field_formatter_info() {
739
	$formats = array(
740
    'default' => array(
741
      'label' => 'Default Email-Link',
742
      'field types' => array('expertsdb_email'),
743
	),
744
    'contact' => array(
745
      'label' => 'Email-Contact Form',
746
      'field types' => array('expertsdb_email'),
747
	),
748
	);
749

    
750
	if (module_exists('invisimail')) {
751
		$formats['invisi'] = array(
752
      'label' => 'Email-Invisimail',
753
      'field types' => array('expertsdb_email'),
754
		);
755
	}
756
	return $formats;
757
}
758

    
759

    
760
/**
761
 * implementationof field_formatter()
762
 *
763
 * @param unknown_type $field
764
 * @param unknown_type $item
765
 * @param unknown_type $formatter
766
 * @param unknown_type $node
767
 * @return unknown
768
 */
769
function expertsdb_email_field_formatter($field, $item, $formatter, $node) {
770
	// item comes in as either serialized or unserilaized item
771
	if (empty($item[0]['expertsdb_email']) && empty($item[0]['email'])) {
772
		return array();
773
	}
774
	if(strstr($item[0]['expertsdb_email'],':{')){
775
		$items = unserialize($item[0]['expertsdb_email']);
776
	}else{
777
		unset($item['count'], $item['more-url'], $item['more']);
778
		$items = $item;
779
	}
780

    
781
	/*
782
	 * Force formatter depending of privacy level
783
	 * - use contact forms, if
784
	 * 	- privacy level is set to ContactPrivate
785
	 * 	- AND current user is not the author of this node
786
	 * 	- AND current user is not Admin or Director
787
	 *
788
	 * - use normal email addresses, if
789
	 * 	- current user is the author of this node
790
	 */
791
	if($node->field_privacy){
792
		global $user;
793
		$term = taxonomy_get_term($node->field_privacy[0]['tid']);
794
		switch($term->name){
795

    
796
			case PRIVACY_CONTACT_PRIVATE:
797
				if($user->uid != $node->uid && !user_access('view private expertsdb_email addresses',$user)){
798
					$formatter = 'contact';
799
				}else{
800
					$formatter = ($formatter == 'invisi') ? 'invisi' : 'default';
801
				}
802
				break;
803

    
804
			case PRIVACY_PRIVATE:
805
				// show information only to roles with access and node author
806
				if($user->uid != $node->uid && !user_access('view private expertsdb_email addresses',$user)){
807
					return;
808
				}
809
				break;
810

    
811
			case PRIVACY_PUBLIC:
812
				// allow everybody to view email addresses as configured in the field formatter (display field)
813
				break;
814

    
815
		}
816
	}
817

    
818
	foreach ($items as $delta => $item) {
819
		if (empty($item['email'])) {
820
			// don't stop on empty values
821
			continue;
822
		}
823
		else {
824

    
825
			// prepare label
826
			$wrapper = ($item['preferred_email']['preferred_email']) ? '<div class="item-label label-column">' . t('Primary Email:') . ' </div><div class="field-email email-data-column">%s</div>' : '<div class="item-label label-column">' . t('Additional Email:') . ' </div><div class="field-email email-data-column">%s</div>' ;
827
			if ($formatter == 'contact') {
828
				$entry = $delta+1; // avoid NULL values
829
				$mailto = l(t('Email Contact Form'), 'expertsdb_email/'.$node->nid.'/'.$field['field_name'].'/'.$entry);
830

    
831
				// only display the first email address, which is the preferred email address
832
				// attach wrapper and put into items
833
				$items[$delta]['view'] = sprintf($wrapper,$mailto);
834
				break;
835
			}
836
			elseif ($formatter == 'invisi' && module_exists('invisimail')) {
837
				// use html filter format as default format.
838
				$format = ($GLOBALS['invisimail_format']) ? $GLOBALS['invisimail_format'] : 1;
839
				if (!(variable_get('invisimail_link_'.$format, TRUE))) {
840
					variable_set('invisimail_link_'.$format, TRUE);
841
					variable_set('invisimail_js_'.$format, TRUE);
842
				}
843
				$js = variable_get('invisimail_js_'.$format, FALSE);
844
				$link = variable_get('invisimail_link_'.$format, FALSE);
845

    
846
				$mailto = invisimail_ascii_encode($item['email'], $js, $link);
847
			}
848
			else {
849
				$mailto =  '<a href="mailto:'. $item['email']. '">'. check_plain($item['email']) .'</a>';
850
			}
851

    
852
			// attach wrapper and put into items
853
			$items[$delta]['view'] = sprintf($wrapper,$mailto);
854
		}
855

    
856
	}
857
	return $items;
858
}
859

    
860
/**
861
 * The contact form page.
862
 *
863
 * @param unknown_type $nid
864
 * @param unknown_type $fieldname
865
 * @return unknown
866
 */
867
function expertsdb_email_mail_page($nid = NULL, $fieldname = NULL, $item = NULL) {
868
	global $user;
869

    
870
	if (empty($nid) || empty($fieldname)) {
871
		drupal_not_found();
872
		return;
873
	}
874
	$node = node_load(intval($nid));
875
	if (!$node) {
876
		drupal_not_found();
877
		return;
878
	}
879
	// Validate field name
880
	$types = content_types($node->type);
881
	if (!isset($types['fields'][$fieldname]) ||
882
	$types['fields'][$fieldname]['type'] != 'expertsdb_email') {
883
		drupal_not_found();
884
		return;
885
	}
886
	if(!user_access('access expertsdb_email mail form',$user)){
887
		drupal_access_denied();
888
		return;
889
	}
890
	$field = $node->$fieldname;
891
	if (empty($field) || empty($field[0]['expertsdb_email'])) {
892
		drupal_not_found();
893
		return;
894
	}
895

    
896
	if (!flood_is_allowed('expertsdb_email', variable_get('expertsdb_email_hourly_threshold', 3))) {
897
		$output = t("You cannot send more than %number messages per hour. Please try again later.", array('%number' => variable_get('expertsdb_email_hourly_threshold', 3)));
898
	}
899
	else {
900
		$output = drupal_get_form('expertsdb_email_mail_page_form');
901
	}
902

    
903
	return $output;
904
}
905

    
906
/**
907
 * Enter description here...
908
 *
909
 * @return unknown
910
 */
911
function expertsdb_email_mail_page_form() {
912
	global $user;
913

    
914
	if ($user->uid) {
915
		$edit['name'] = $user->name;
916
		$edit['mail'] = $user->mail;
917
	}
918

    
919
	$form['#token'] = $user->name . $user->mail;
920
	$form['name'] = array('#type' => 'textfield',
921
    '#title' => t('Your name'),
922
    '#maxlength' => 255,
923
    '#default_value' => $edit['name'],
924
    '#required' => TRUE,
925
	);
926
	$form['mail'] = array('#type' => 'textfield',
927
    '#title' => t('Your e-mail address'),
928
    '#maxlength' => 255,
929
    '#default_value' => $edit['mail'],
930
    '#required' => TRUE,
931
	);
932
	$form['subject'] = array('#type' => 'textfield',
933
    '#title' => t('Subject'),
934
    '#maxlength' => 255,
935
    '#required' => TRUE,
936
	);
937
	$form['message'] = array('#type' => 'textarea',
938
    '#title' => t('Message'),
939
    '#required' => TRUE,
940
	);
941
	$form['submit'] = array('#type' => 'submit',
942
    '#value' => t('Send e-mail'),
943
	);
944
	return $form;
945
}
946

    
947
/**
948
 * Validate the site-wide contact page form submission.
949
 *
950
 * @param unknown_type $form_id
951
 * @param unknown_type $form_values
952
 */
953
function expertsdb_email_mail_page_form_validate($form_id, $form_values) {
954
	if (!valid_email_address($form_values['mail'])) {
955
		form_set_error('mail', t('You must enter a valid e-mail address.'));
956
	}
957
	if (preg_match("/\r|\n/", $form_values['subject'])) {
958
		form_set_error('subject', t('The subject cannot contain linebreaks.'));
959
		watchdog('mail', 'Email injection exploit attempted in email form subject: '.check_plain($form_values['subject']), WATCHDOG_NOTICE);
960
	}
961
}
962

    
963
/**
964
 * Process the site-wide contact page form submission.
965
 *
966
 * @param unknown_type $form_id
967
 * @param unknown_type $edit
968
 * @return unknown
969
 */
970
function expertsdb_email_mail_page_form_submit($form_id, $edit) {
971
	$nid = intval(arg(1));
972
	$fieldname = arg(2);
973
	$email_entry = intval(arg(3));
974
	if (empty($nid) || empty($fieldname) || empty($email_entry)) {
975
		drupal_not_found();
976
		return;
977
	}
978
	$node = node_load($nid);
979
	if (!$node) {
980
		drupal_not_found();
981
		return;
982
	}
983
	// Validate field name
984
	$types = content_types($node->type);
985
	if (!isset($types['fields'][$fieldname]) ||
986
	$types['fields'][$fieldname]['type'] != 'expertsdb_email') {
987
		drupal_not_found();
988
		return;
989
	}
990
	$field = $node->$fieldname;
991
	if (empty($field) || empty($field[0]['expertsdb_email'])) {
992
		drupal_not_found();
993
		return;
994
	}
995
	$email_addresses = unserialize($field[0]['expertsdb_email']);
996
	$delta = $email_entry-1;
997
	$email = $email_addresses[$delta]['expertsdb_email'];
998

    
999
	// E-mail address of the sender: as the form field is a text field,
1000
	// all instances of \r and \n have been automatically stripped from it.
1001
	$from = $edit['mail'];
1002

    
1003
	// Compose the body:
1004
	$message[] = t("@name sent a message using the contact form at @form.", array('@name' => $edit['name'], '@form' => url($_GET['q'], NULL, NULL, TRUE)));
1005
	$message[] = $edit['message'];
1006

    
1007
	// Tidy up the body:
1008
	foreach ($message as $key => $value) {
1009
		$message[$key] = wordwrap($value);
1010
	}
1011

    
1012
	// Format the category:
1013
	$subject = t('[@title - @contact] @subject', array('@title' => preg_replace("/\r|\n/",'',$node->title), '@contact' => $types['fields'][$fieldname]['widget']['label'], '@subject' => $edit['subject']));
1014

    
1015
	// Prepare the body:
1016
	$body = implode("\n\n", $message);
1017

    
1018
	// Send the e-mail to the recipients:
1019
	drupal_mail($fieldname, $email, $subject, $body, $from);
1020

    
1021
	// Log the operation:
1022
	flood_register_event('expertsdb_email');
1023
	watchdog('mail', t('%name-from sent an e-mail at %form.', array('%name-from' => theme('placeholder', $edit['name'] ." <$from>"), '%form' => url($_GET['q'], NULL, NULL, TRUE))));
1024

    
1025
	// Update user:
1026
	drupal_set_message(t('Your message has been sent.'));
1027

    
1028
	// Jump to home page rather than back to contact page to avoid contradictory messages if flood control has been activated.
1029
	return 'node/'.$node->nid;
1030
}
1031

    
1032

    
1033
/**
1034
 * Token Integration
1035
 *
1036
 * @param unknown_type $type
1037
 * @return unknown
1038
 */
1039
function expertsdb_email_token_list($type = 'all') {
1040
	if ($type == 'field' || $type == 'all') {
1041
		$tokens['email']['email'] = t("Email Address");
1042
		return $tokens;
1043
	}
1044
}
1045

    
1046
/**
1047
 * Implementation of hook token_values
1048
 *
1049
 * @param unknown_type $type
1050
 * @param unknown_type $object
1051
 * @param unknown_type $options
1052
 * @return unknown
1053
 */
1054
function expertsdb_email_token_values($type, $object = NULL, $options = array()) {
1055
	if ($type == 'field') {
1056
		$item = $object[0];
1057
		$tokens['email'] = check_plain($item['expertsdb_email']);
1058
		return $tokens;
1059
	}
1060
}
(23-23/47)