source: subversion/trunk/roundcubemail/program/steps/addressbook/save.inc @ 4973

Last change on this file since 4973 was 4973, checked in by alec, 22 months ago
  • Generate display name before record validation
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 10.5 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/addressbook/save.inc                                    |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Save a contact entry or to add a new one                            |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22$CONTACTS = rcmail_contact_source(null, true);
23$cid      = get_input_value('_cid', RCUBE_INPUT_POST);
24$return_action = empty($cid) ? 'add' : 'edit';
25
26
27// Source changed, display the form again
28if (!empty($_GET['_reload'])) {
29  rcmail_overwrite_action($return_action);
30  return;
31}
32
33// cannot edit record
34if ($CONTACTS->readonly) {
35  $OUTPUT->show_message('contactreadonly', 'error');
36  rcmail_overwrite_action($return_action);
37  return;
38}
39
40
41// handle photo upload for contacts
42if ($RCMAIL->action == 'upload-photo') {
43    // clear all stored output properties (like scripts and env vars)
44    $OUTPUT->reset();
45
46    if ($filepath = $_FILES['_photo']['tmp_name']) {
47        // check file type and resize image
48        $imageprop = rcmail::imageprops($_FILES['_photo']['tmp_name']);
49
50        if ($imageprop['width'] && $imageprop['height']) {
51            $maxsize = intval($RCMAIL->config->get('contact_photo_size', 160));
52            $tmpfname = tempnam($RCMAIL->config->get('temp_dir'), 'rcmImgConvert');
53            $save_hook = 'attachment_upload';
54
55            // scale image to a maximum size
56            if (($imageprop['width'] > $maxsize || $imageprop['height'] > $maxsize) &&
57                  (rcmail::imageconvert(array('in' => $filepath, 'out' => $tmpfname, 'size' => $maxsize.'x'.$maxsize, 'type' => $imageprop['type'])) !== false)) {
58                $filepath = $tmpfname;
59                $save_hook = 'attachment_save';
60            }
61
62            // save uploaded file in storage backend
63            $attachment = $RCMAIL->plugins->exec_hook($save_hook, array(
64                'path' => $filepath,
65                'size' => $_FILES['_photo']['size'],
66                'name' => $_FILES['_photo']['name'],
67                'mimetype' => 'image/' . $imageprop['type'],
68                'group' => 'contact',
69            ));
70        }
71        else
72            $attachment['error'] = rcube_label('invalidimageformat');
73
74        if ($attachment['status'] && !$attachment['abort']) {
75            $file_id = $attachment['id'];
76            $_SESSION['contacts']['files'][$file_id] = $attachment;
77            $OUTPUT->command('replace_contact_photo', $file_id);
78        }
79        else {  // upload failed
80            $err = $_FILES['_photo']['error'];
81            if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE)
82                $msg = rcube_label(array('name' => 'filesizeerror', 'vars' => array('size' => show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
83            else if ($attachment['error'])
84                $msg = $attachment['error'];
85            else
86                $msg = rcube_label('fileuploaderror');
87           
88            $OUTPUT->command('display_message', $msg, 'error');
89        }
90    }
91    else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
92        // if filesize exceeds post_max_size then $_FILES array is empty,
93        // show filesizeerror instead of fileuploaderror
94        if ($maxsize = ini_get('post_max_size'))
95            $msg = rcube_label(array('name' => 'filesizeerror', 'vars' => array('size' => show_bytes(parse_bytes($maxsize)))));
96        else
97            $msg = rcube_label('fileuploaderror');
98
99        $OUTPUT->command('display_message', $msg, 'error');
100    }
101
102    $OUTPUT->command('photo_upload_end');
103    $OUTPUT->send('iframe');
104}
105
106// read POST values into hash array
107$a_record = array();
108foreach ($GLOBALS['CONTACT_COLTYPES'] as $col => $colprop) {
109  $fname = '_'.$col;
110  if ($colprop['composite'])
111    continue;
112  // gather form data of composite fields
113  if ($colprop['childs']) {
114    $values = array();
115    foreach ($colprop['childs'] as $childcol => $cp) {
116      $vals = get_input_value('_'.$childcol, RCUBE_INPUT_POST, true);
117      foreach ((array)$vals as $i => $val)
118        $values[$i][$childcol] = $val;
119    }
120    $subtypes = get_input_value('_subtype_' . $col, RCUBE_INPUT_POST);
121    foreach ($subtypes as $i => $subtype)
122      if ($values[$i])
123        $a_record[$col.':'.$subtype][] = $values[$i];
124  }
125  // assign values and subtypes
126  else if (is_array($_POST[$fname])) {
127    $values = get_input_value($fname, RCUBE_INPUT_POST, true);
128    $subtypes = get_input_value('_subtype_' . $col, RCUBE_INPUT_POST);
129    foreach ($values as $i => $val) {
130      $subtype = $subtypes[$i] ? ':'.$subtypes[$i] : '';
131      $a_record[$col.$subtype][] = $val;
132    }
133  }
134  else if (isset($_POST[$fname])) {
135    $a_record[$col] = get_input_value($fname, RCUBE_INPUT_POST, true);
136  }
137}
138
139// Generate contact's display name (must be before validation)
140if (empty($a_record['name'])) {
141    $a_record['name'] = rcube_addressbook::compose_display_name($a_record, true);
142    // Reset it if equals to email address (from compose_display_name())
143    if ($a_record['name'] == $a_record['email'][0])
144        $a_record['name'] = '';
145}
146
147// do input checks (delegated to $CONTACTS instance)
148if (!$CONTACTS->validate($a_record)) {
149    $err = (array)$CONTACTS->get_error() + array('message' => 'formincomplete', 'type' => 'warning');
150    $OUTPUT->show_message($err['message'], $err['type']);
151    $GLOBALS['EDIT_RECORD'] = $a_record;  // store submitted data to be used in edit form
152    rcmail_overwrite_action($return_action);
153    return;
154}
155
156// get raw photo data if changed
157if (isset($a_record['photo'])) {
158    if ($a_record['photo'] == '-del-') {
159        $a_record['photo'] = '';
160    }
161    else if ($tempfile = $_SESSION['contacts']['files'][$a_record['photo']]) {
162        $tempfile = $RCMAIL->plugins->exec_hook('attachment_get', $tempfile);
163        if ($tempfile['status'])
164            $a_record['photo'] = $tempfile['data'] ? $tempfile['data'] : @file_get_contents($tempfile['path']);
165    }
166    else
167        unset($a_record['photo']);
168
169    // cleanup session data
170    $RCMAIL->plugins->exec_hook('attachments_cleanup', array('group' => 'contact'));
171    $RCMAIL->session->remove('contacts');
172}
173
174
175// update an existing contact
176if (!empty($cid))
177{
178  $plugin = $RCMAIL->plugins->exec_hook('contact_update',
179    array('id' => $cid, 'record' => $a_record, 'source' => get_input_value('_source', RCUBE_INPUT_GPC)));
180  $a_record = $plugin['record'];
181
182  if (!$plugin['abort'])
183    $result = $CONTACTS->update($cid, $a_record);
184  else
185    $result = $plugin['result'];
186
187  if ($result) {
188    // LDAP DN change
189    if (is_string($result) && strlen($result)>1) {
190      $newcid = $result;
191      // change cid in POST for 'show' action
192      $_POST['_cid'] = $newcid;
193    }
194
195    // define list of cols to be displayed
196    $a_js_cols = array();
197    $record = $CONTACTS->get_record($newcid ? $newcid : $cid, true);
198    $record['email'] = reset($CONTACTS->get_col_values('email', $record, true));
199    if (empty($record['name']))
200      $record['name']  = rcube_addressbook::compose_display_name($record, true);
201
202    foreach (array('name', 'email') as $col)
203      $a_js_cols[] = Q((string)$record[$col]);
204
205    // update the changed col in list
206    $OUTPUT->command('parent.update_contact_row', $cid, $a_js_cols, $newcid);
207
208    // show confirmation
209    $OUTPUT->show_message('successfullysaved', 'confirmation', null, false);
210    rcmail_overwrite_action('show');
211  }
212  else {
213    // show error message
214    $err = $CONTACTS->get_error();
215    $OUTPUT->show_message($plugin['message'] ? $plugin['message'] : ($err['message'] ? $err['message'] : 'errorsaving'), 'error', null, false);
216    rcmail_overwrite_action('show');
217  }
218}
219
220// insert a new contact
221else {
222  $source = get_input_value('_source', RCUBE_INPUT_GPC);
223
224  // show notice if existing contacts with same e-mail are found
225  $existing = false;
226  foreach ($CONTACTS->get_col_values('email', $a_record, true) as $email) {
227      if (($res = $CONTACTS->search('email', $email, false, false, true)) && $res->count) {
228          $OUTPUT->show_message('contactexists', 'notice', null, false);
229          break;
230      }
231  }
232
233  $plugin = $RCMAIL->plugins->exec_hook('contact_create', array(
234    'record' => $a_record, 'source' => $source));
235  $a_record = $plugin['record'];
236
237  // insert record and send response
238  if (!$plugin['abort'])
239    $insert_id = $CONTACTS->insert($a_record);
240  else
241    $insert_id = $plugin['result'];
242
243  if ($insert_id) {
244    // add new contact to the specified group
245    if ($CONTACTS->groups && $CONTACTS->group_id) {
246      $plugin = $RCMAIL->plugins->exec_hook('group_addmembers', array(
247        'group_id' => $CONTACTS->group_id, 'ids' => $insert_id, 'source' => $source));
248
249      if (!$plugin['abort']) {
250        if (($maxnum = $RCMAIL->config->get('max_group_members', 0)) && ($CONTACTS->count()->count + 1 > $maxnum))
251          $OUTPUT->show_message('maxgroupmembersreached', 'warning', array('max' => $maxnum));
252
253        $CONTACTS->add_to_group($gid, $plugin['ids']);
254      }
255    }
256
257    // Name of the addressbook already selected on the list
258    $orig_source = get_input_value('_orig_source', RCUBE_INPUT_GPC);
259
260    if ((string)$source === (string)$orig_source) {
261      // add contact row or jump to the page where it should appear
262      $CONTACTS->reset();
263      $result = $CONTACTS->search($CONTACTS->primary_key, $insert_id);
264
265      rcmail_js_contacts_list($result, 'parent.');
266      $OUTPUT->command('parent.contact_list.select', html_identifier($insert_id));
267
268      // update record count display
269      $CONTACTS->reset();
270      $OUTPUT->command('parent.set_rowcount', rcmail_get_rowcount_text());
271    }
272    else {
273      // re-set iframe
274      $OUTPUT->command('parent.show_contentframe');
275    }
276
277    // show confirmation
278    $OUTPUT->show_message('successfullysaved', 'confirmation', null, false);
279    $OUTPUT->send('iframe');
280  }
281  else {
282    // show error message
283    $err = $CONTACTS->get_error();
284    $OUTPUT->show_message($plugin['message'] ? $plugin['message'] : ($err['message'] ? $err['message'] : 'errorsaving'), 'error', null, false);
285    rcmail_overwrite_action('add');
286  }
287}
Note: See TracBrowser for help on using the repository browser.