public function execute()
 {
     // Layout caching is forbidden
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Expires: " . date("r"));
     $this->executeAction('sidebar', new contactsBackendSidebarAction());
     $fields = array();
     // normally this is done with waContactFields::getInfo() but we don't need most of the info
     // so we loop through fields manually.
     foreach (waContactFields::getAll('enabled') as $field_id => $f) {
         /**
          * @var $f waContactField
          */
         $fields[$field_id] = array();
         $fields[$field_id]['id'] = $field_id;
         $fields[$field_id]['name'] = $f->getName();
         $fields[$field_id]['fields'] = $f instanceof waContactCompositeField;
         if ($ext = $f->getParameter('ext')) {
             $fields[$field_id]['ext'] = $ext;
             foreach ($fields[$field_id]['ext'] as &$v) {
                 $v = _ws($v);
             }
         }
     }
     // Plugin assets
     if ($this->getConfig()->getInfo('edition') === 'full') {
         wa()->event('assets');
     }
     $this->view->assign('admin', wa()->getUser()->getRights('contacts', 'backend') > 1);
     $this->view->assign('global_admin', wa()->getUser()->getRights('webasyst', 'backend') > 0);
     $this->view->assign('fields', $fields);
     $this->view->assign('versionFull', $this->getConfig()->getInfo('edition') === 'full');
 }
 public function execute()
 {
     $field = waRequest::get('field', null, waRequest::TYPE_STRING_TRIM);
     if (!$field) {
         throw new waException(_w("Unknown field"));
     }
     // List of field values
     $cfvm = new waContactFieldValuesModel();
     $fields = $cfvm->getInfo($field);
     // Possible parent fields this conditional field may depend on
     $parent_fields = array();
     foreach (waContactFields::getAll('person') as $f) {
         /** @var waContactField $f */
         if (!$f instanceof waContactCompositeField && !$f->isMulti()) {
             $parent_fields[$f->getId()] = $f->getName();
         }
     }
     $field_ids = explode(':', $field);
     $f = waContactFields::get($field_ids[0]);
     if (!empty($field_ids[1]) && $f && $f instanceof waContactCompositeField) {
         $subfields = $f->getFields();
         foreach ($subfields as $sfid => $sf) {
             $pid = $f->getId() . ':' . $sfid;
             if ($pid !== $field) {
                 $parent_fields[$pid] = $f->getName() . ' — ' . $sf->getName();
             }
         }
     }
     // Selected parent field
     $parent_selected = null;
     if ($fields) {
         $parent_selected = reset($fields);
         $parent_selected = $parent_selected['field'];
     }
     // Human readable name of current field
     if (!empty($field_ids[1]) && !empty($subfields[$field_ids[1]])) {
         $title = $subfields[$field_ids[1]]->getName();
     } else {
         if ($f) {
             $title = $f->getName();
         } else {
             // Loose guess on whether this field has just been created
             $new_field = false;
             if (substr($field, 0, 2) == '__') {
                 $new_field = true;
             } else {
                 if (!empty($field_ids[1]) && substr($field_ids[1], 0, 2) == '__') {
                     $new_field = true;
                 }
             }
             if ($new_field) {
                 $title = _w('Conditional field');
             } else {
                 $title = _w(ucfirst($field));
             }
         }
     }
     $this->view->assign(array('field' => $field, 'title' => $title, 'fields' => $fields, 'parent_fields' => $parent_fields, 'parent_selected' => $parent_selected));
 }
 public function execute()
 {
     if (!$this->getRights('create')) {
         throw new waRightsException('Access denied.');
     }
     $type = waRequest::get('company') ? 'company' : 'person';
     $fields = array();
     foreach (waContactFields::getAll($type, true) as $field_id => $field) {
         $fields[$field_id] = $field->getInfo();
         $fields[$field_id]['top'] = $field->getParameter('top');
     }
     $this->view->assign('contactFields', $fields);
     $this->view->assign('contactType', $type);
 }
 public function execute()
 {
     $this->contact = wa()->getUser();
     $data = json_decode(waRequest::post('data'), true);
     if (!$data || !is_array($data)) {
         $this->response = array('errors' => array(), 'data' => array());
         return;
     }
     // Make sure only allowed fields are saved
     $allowed = array();
     foreach (waContactFields::getAll('person') as $f) {
         if ($f->getParameter('allow_self_edit')) {
             $allowed[$f->getId()] = true;
         }
     }
     $data = array_intersect_key($data, $allowed);
     $oldLocale = $this->getUser()->getLocale();
     // Validate and save contact if no errors found
     $errors = $this->contact->save($data, true);
     if ($errors) {
         $response = array();
     } else {
         // New data formatted for JS
         $response['name'] = $this->contact->get('name', 'js');
         foreach ($data as $field_id => $field_value) {
             if (!isset($errors[$field_id])) {
                 $response[$field_id] = $this->contact->get($field_id, 'js');
             }
         }
         // Top fields
         $response['top'] = array();
         foreach (array('email', 'phone', 'im') as $f) {
             if ($v = $this->contact->get($f, 'top,html')) {
                 $response['top'][] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
             }
         }
     }
     // Reload page with new language if user just changed it in own profile
     if ($oldLocale != $this->contact->getLocale()) {
         $response['reload'] = TRUE;
     }
     $this->response = array('errors' => $errors, 'data' => $response);
 }
 public function execute()
 {
     $domain = siteHelper::getDomain();
     $fields = array();
     $default_fields = array('firstname' => true, 'lastname' => true, 'middlename' => true, 'email' => true, 'phone' => true, 'password' => true);
     $auth_config = wa()->getAuthConfig($domain);
     if (!empty($auth_config['app']) && $auth_config['app'] == 'shop') {
         $settings = wa('shop')->getConfig()->getCheckoutSettings();
         if (!isset($settings['contactinfo'])) {
             $settings = wa('shop')->getConfig()->getCheckoutSettings(true);
         }
         if (!empty($settings['contactinfo']['fields'])) {
             $default_fields = array();
             foreach ($settings['contactinfo']['fields'] as $field_id => $f) {
                 $default_fields[$field_id] = true;
             }
         }
     }
     $domain_config_path = wa('site')->getConfig()->getConfigPath('domains/' . $domain . '.php');
     if (file_exists($domain_config_path)) {
         $domain_config = (include $domain_config_path);
     } else {
         $domain_config = array();
     }
     if (!isset($domain_config['personal_fields'])) {
         $domain_config['personal_fields'] = $default_fields;
     }
     if (!empty($auth_config['app']) && isset($domain_config['personal'][$auth_config['app']]) && !$domain_config['personal'][$auth_config['app']]) {
         $this->view->assign('profile_disabled', true);
         $this->view->assign('auth_app', wa()->getAppInfo($auth_config['app']));
     }
     $contacts_fields = array('photo' => new waContactHiddenField('photo', _ws('Photo'))) + waContactFields::getAll('person', true) + array('password' => new waContactPasswordField('password', _ws('Password')));
     foreach ($contacts_fields as $fiels_name => $field) {
         $name = $field->getName();
         if ($name && $fiels_name !== 'name') {
             $fields[] = array('id' => $fiels_name, 'name' => $name, 'checked' => isset($domain_config['personal_fields'][$fiels_name]) && $domain_config['personal_fields'][$fiels_name] === true ? true : false);
         }
     }
     $this->view->assign('domain', $domain);
     $this->view->assign('fields', $fields);
 }
 public static function getFieldsDescription($field_ids, $skip = false)
 {
     $fields = array();
     $all_fields = waContactFields::getAll('enabled');
     if ($skip) {
         foreach ($field_ids as $field_id) {
             if (isset($all_fields[$field_id])) {
                 unset($all_fields[$field_id]);
             }
         }
         $field_ids = array_keys($all_fields);
     }
     foreach ($field_ids as $field_id) {
         $f = $all_fields[$field_id];
         if (!$f) {
             continue;
         }
         /**
          * @var $f waContactField
          */
         $fields[$field_id] = array();
         $fields[$field_id]['id'] = $field_id;
         $fields[$field_id]['name'] = $f->getName();
         $fields[$field_id]['type'] = $f->getType();
         if ($fields[$field_id]['type'] === 'Select') {
             $fields[$field_id]['options'] = $f->getOptions();
         }
         $fields[$field_id]['fields'] = $f instanceof waContactCompositeField;
         if ($ext = $f->getParameter('ext')) {
             $fields[$field_id]['ext'] = $ext;
             foreach ($fields[$field_id]['ext'] as &$v) {
                 $v = _ws($v);
             }
         }
         $fields[$field_id]['icon'] = $fields[$field_id]['type'] == 'Email' || $fields[$field_id]['type'] == 'Phone' ? strtolower($fields[$field_id]['type']) : '';
     }
     return $fields;
 }
 public function execute()
 {
     // Layout caching is forbidden
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Expires: " . date("r"));
     $this->executeAction('sidebar', new contactsBackendSidebarAction());
     $fields = array();
     // normally this is done with waContactFields::getInfo() but we don't need most of the info
     // so we loop through fields manually.
     foreach (waContactFields::getAll('enabled') as $field_id => $f) {
         /**
          * @var $f waContactField
          */
         $fields[$field_id] = array();
         $fields[$field_id]['id'] = $field_id;
         $fields[$field_id]['name'] = $f->getName();
         $fields[$field_id]['fields'] = $f instanceof waContactCompositeField;
         if ($ext = $f->getParameter('ext')) {
             $fields[$field_id]['ext'] = $ext;
             foreach ($fields[$field_id]['ext'] as &$v) {
                 $v = _ws($v);
             }
         }
     }
     /**
      * Include plugins js and css
      * @event backend_assets
      * @return array[string]string $return[%plugin_id%]
      */
     $this->view->assign('backend_assets', wa()->event('backend_assets'));
     /**
      * Include plugins js templates
      * @event backend_tempaltes
      * @return array[string]string $return[%plugin_id%]
      */
     $this->view->assign('backend_templates', wa()->event('backend_templates'));
     $this->view->assign(array('admin' => wa()->getUser()->getRights('contacts', 'backend') > 1, 'global_admin' => wa()->getUser()->getRights('webasyst', 'backend') > 0, 'fields' => $fields, 'groups' => $this->getGroups(), 'paginator_type' => wa('contacts')->getConfig('contacts')->getOption('paginator_type'), 'lang' => substr(wa()->getLocale(), 0, 2)));
 }
 /**
  * Get data for contacts in this collection.
  * @param string|array $fields
  * @param int $offset
  * @param int $limit
  * @return array [contact_id][field] = field value in appropriate field format
  * @throws waException
  */
 public function getContacts($fields = "id", $offset = 0, $limit = 50)
 {
     $sql = "SELECT " . $this->getFields($fields) . " " . $this->getSQL();
     $sql .= $this->getGroupBy();
     $sql .= $this->getHaving();
     $sql .= $this->getOrderBy();
     $sql .= " LIMIT " . ($offset ? $offset . ',' : '') . (int) $limit;
     //header("X-SQL-". mt_rand() . ": ". str_replace("\n", " ", $sql));
     $data = $this->getModel()->query($sql)->fetchAll('id');
     $ids = array_keys($data);
     //
     // Load fields from other storages
     //
     if ($ids && $this->post_fields) {
         // $fill[table][field] = null
         // needed for all rows to always contain all apropriate keys
         // in case when we're asked to load all fields from that table
         $fill = array_fill_keys(array_keys($this->post_fields), array());
         foreach (waContactFields::getAll('enabled') as $fid => $field) {
             /**
              * @var waContactField $field
              */
             $fill[$field->getStorage(true)][$fid] = false;
         }
         foreach ($this->post_fields as $table => $fields) {
             if ($table == '_internal') {
                 foreach ($fields as $f) {
                     /**
                      * @var $f string
                      */
                     if ($f == 'photo_url' || substr($f, 0, 10) == 'photo_url_') {
                         if ($f == 'photo_url') {
                             $size = null;
                         } else {
                             $size = substr($f, 10);
                         }
                         $retina = isset($this->options['photo_url_2x']) ? $this->options['photo_url_2x'] : null;
                         foreach ($data as $id => &$v) {
                             $v[$f] = waContact::getPhotoUrl($id, $v['photo'], $size, $size, $v['is_company'] ? 'company' : 'person', $retina);
                         }
                         unset($v);
                     } else {
                         switch ($f) {
                             case '_online_status':
                                 $llm = new waLoginLogModel();
                                 $contact_ids_map = $llm->select('DISTINCT contact_id')->where('datetime_out IS NULL')->fetchAll('contact_id');
                                 $timeout = waUser::getOption('online_timeout');
                                 foreach ($data as &$v) {
                                     if (isset($v['last_datetime']) && $v['last_datetime'] && $v['last_datetime'] != '0000-00-00 00:00:00') {
                                         if (time() - strtotime($v['last_datetime']) < $timeout) {
                                             if (isset($contact_ids_map[$v['id']])) {
                                                 $v['_online_status'] = 'online';
                                             } else {
                                                 $v['_online_status'] = 'offline';
                                             }
                                         }
                                     }
                                     $v['_online_status'] = 'offline';
                                 }
                                 unset($v);
                                 break;
                             case '_access':
                                 $rm = new waContactRightsModel();
                                 $accessStatus = $rm->getAccessStatus($ids);
                                 foreach ($data as $id => &$v) {
                                     if (!isset($accessStatus[$id])) {
                                         $v['_access'] = '';
                                         continue;
                                     }
                                     $v['_access'] = $accessStatus[$id];
                                 }
                                 unset($v);
                                 break;
                             default:
                                 throw new waException('Unknown internal field: ' . $f);
                         }
                     }
                 }
                 continue;
             }
             $data_fields = $fields;
             foreach ($data_fields as $k => $field_id) {
                 $f = waContactFields::get($field_id);
                 if ($f && $f instanceof waContactCompositeField) {
                     unset($data_fields[$k]);
                     $data_fields = array_merge($data_fields, $f->getField());
                 }
             }
             $model = $this->getModel($table);
             $post_data = $model->getData($ids, $data_fields);
             foreach ($post_data as $contact_id => $contact_data) {
                 foreach ($contact_data as $field_id => $value) {
                     if (!($f = waContactFields::get($field_id))) {
                         continue;
                     }
                     if (!$f->isMulti()) {
                         $post_data[$contact_id][$field_id] = isset($value[0]['data']) ? $value[0]['data'] : (is_array($value[0]) ? $value[0]['value'] : $value[0]);
                     }
                 }
             }
             if ($fields) {
                 $fill[$table] = array_fill_keys($fields, '');
             } else {
                 if (!isset($fill[$table])) {
                     $fill[$table] = array();
                 }
             }
             foreach ($data as $contact_id => $v) {
                 if (isset($post_data[$contact_id])) {
                     $data[$contact_id] += $post_data[$contact_id];
                 }
                 $data[$contact_id] += $fill[$table];
             }
         }
     }
     return $data;
 }
    public function getHtmlOne($params = array(), $attrs = '')
    {
        //
        // HTML: list of radio buttons
        //
        $value = isset($params['value']) ? $params['value'] : '';
        $html = '';
        $radios_name = $this->getHTMLName($params);
        foreach ($this->getOptions() as $k => $v) {
            $html .= '<label><input type="radio"' . ($k == $value ? ' checked="checked"' : '') . ' name="' . $radios_name . '" value="' . htmlspecialchars($k) . '"> ' . htmlspecialchars($v) . '</label>';
        }
        //
        // JS: hide form fields depending on radio selection
        //
        $hide_data = array();
        $hide_by_default = array();
        $field_names = array();
        $p = $params;
        $all_fields = waContactFields::getAll('enabled');
        foreach (ifempty($this->options['hide'], array()) as $option_id => $field_ids) {
            $hide_data[$option_id] = array_fill_keys($field_ids, 1);
            $hide_by_default += $hide_data[$option_id];
            foreach ($field_ids as $fid) {
                if (empty($all_fields[$fid]) || $all_fields[$fid]->isRequired()) {
                    // Never hide required fields
                    unset($hide_by_default[$fid], $hide_data[$option_id][$fid]);
                    continue;
                }
                if (empty($field_names[$fid])) {
                    $p['id'] = $fid;
                    $field_names[$fid] = $this->getHTMLName($p);
                }
            }
        }
        $uniqid = uniqid('s');
        $hide_data['hide_by_default'] = $hide_by_default;
        $field_names = json_encode($field_names);
        $hide_data = json_encode($hide_data);
        $js = <<<EOF
<span id="{$uniqid}"></span>
<script>if (\$) { \$(function() { "use strict";
    var hide_data = {$hide_data};
    var radios_parent = \$('#{$uniqid}').parent();
    var field_names = {$field_names};
    if (!radios_parent || !radios_parent.length) {
        return;
    }

    var initially_selected = radios_parent.find(':radio[name="{$radios_name}"]:checked');
    var previous_selection = 'hide_by_default';

    radios_parent.on('change', ':radio[name="{$radios_name}"]', function() {

        var option_id = \$(this).val();

        // Show previously hidden
        if (hide_data[previous_selection]) {
            for (var field_id in hide_data[previous_selection]) {
                if (!hide_data[previous_selection].hasOwnProperty(field_id)) {
                    continue;
                }
                if (hide_data[option_id] && hide_data[option_id][field_id]) {
                    continue;
                }
                if (!field_names[field_id]) {
                    continue;
                }
                \$('[name^="'+field_names[field_id]+'"]:first').closest('.wa-field,.field').show();
            }
        }

        // Hide using new selection
        if (hide_data[option_id]) {
            for (var field_id in hide_data[option_id]) {
                if (!hide_data[option_id].hasOwnProperty(field_id)) {
                    continue;
                }
                if (hide_data[previous_selection] && hide_data[previous_selection][field_id]) {
                    continue;
                }
                if (!field_names[field_id]) {
                    continue;
                }
                var field_to_hide = \$('[name^="'+field_names[field_id]+'"]:first').closest('.wa-field,.field');
                if (!field_to_hide.is('.required,.wa-required')) {
                    field_to_hide.hide();
                }
            }
        }

        previous_selection = option_id;
    });

    if (initially_selected && initially_selected.length) {
        initially_selected.change();
    } else {
        var hide_by_default = hide_data.hide_by_default;
        for (var field_id in hide_by_default) {
            if (!hide_by_default.hasOwnProperty(field_id)) {
                continue;
            }
            if (!field_names[field_id]) {
                continue;
            }
            var field_to_hide = \$('[name^="'+field_names[field_id]+'"]:first').closest('.wa-field,.field');
            if (!field_to_hide.is('.required,.wa-required')) {
                field_to_hide.hide();
            }
        }
    }
}); };</script>
EOF;
        return $html . $js;
    }
 private function getContactfieldControl($name, $params = array())
 {
     $params['options'] = array();
     $params['options'][] = array('title' => '—', 'value' => '');
     $fields = waContactFields::getAll();
     foreach ($fields as $field) {
         if ($field instanceof waContactCompositeField) {
             $subfields = $field->getFields();
             foreach ($subfields as $subfield) {
                 $params['options'][] = array('group' => $field->getName(), 'title' => $subfield->getName(), 'value' => $field->getId() . '.' . $subfield->getId());
             }
         } else {
             $params['options'][] = array('title' => $field->getName(), 'value' => $field->getId());
         }
     }
     return $this->getSelectControl($name, $params);
 }
 /**
  * Merge given contacts into master contact, save, send merge event, then delete slaves.
  *
  * !!! Probably should move it into something like contactsHelper
  *
  * @param array $merge_ids list of contact ids
  * @param int $master_id contact id to merge others into
  * @return array
  */
 public static function merge($merge_ids, $master_id)
 {
     $merge_ids[] = $master_id;
     // List of contacts to merge
     $collection = new contactsCollection('id/' . implode(',', $merge_ids));
     $contacts_data = $collection->getContacts('*');
     // Master contact data
     if (!$master_id || !isset($contacts_data[$master_id])) {
         throw new waException('No contact to merge into.');
     }
     $master_data = $contacts_data[$master_id];
     unset($contacts_data[$master_id]);
     $master = new waContact($master_id);
     $result = array('total_requested' => count($contacts_data) + 1, 'total_merged' => 0, 'error' => '', 'users' => 0);
     if ($master_data['photo']) {
         $filename = wa()->getDataPath(waContact::getPhotoDir($master_data['id']) . "{$master_data['photo']}.original.jpg", true, 'contacts');
         if (!file_exists($filename)) {
             $master_data['photo'] = null;
         }
     }
     $data_fields = waContactFields::getAll('enabled');
     $check_duplicates = array();
     // field_id => true
     $update_photo = null;
     // if need to update photo here it is file paths
     // merge loop
     foreach ($contacts_data as $id => $info) {
         if ($info['is_user'] > 0) {
             $result['users']++;
             unset($contacts_data[$id]);
             continue;
         }
         foreach ($data_fields as $f => $field) {
             if (!empty($info[$f])) {
                 if ($field->isMulti()) {
                     $master->add($f, $info[$f]);
                     $check_duplicates[$f] = true;
                 } else {
                     // Field does not allow multiple values.
                     // Set value if no value yet.
                     if (empty($master_data[$f])) {
                         $master[$f] = $master_data[$f] = $info[$f];
                     }
                 }
             }
         }
         // photo
         if (!$master_data['photo'] && $info['photo'] && !$update_photo) {
             $filename_original = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.original.jpg", true, 'contacts');
             if (file_exists($filename_original)) {
                 $update_photo = array('original' => $filename_original);
                 $filename_crop = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.jpg", true, 'contacts');
                 if (file_exists($filename_crop)) {
                     $update_photo['crop'] = $filename_crop;
                 }
             }
         }
         // birthday parts
         if (!empty($data_fields['birthday'])) {
             foreach (array('birth_day', 'birth_month', 'birth_year') as $f) {
                 if (empty($master_data[$f]) && !empty($info[$f])) {
                     $master[$f] = $master_data[$f] = $info[$f];
                 }
             }
         }
     }
     // Remove duplicates
     foreach (array_keys($check_duplicates) as $f) {
         $values = $master[$f];
         if (!is_array($values) || count($values) <= 1) {
             continue;
         }
         $unique_values = array();
         // md5 => true
         foreach ($values as $k => $v) {
             if (is_array($v)) {
                 if (isset($v['value']) && is_string($v['value'])) {
                     $v = $v['value'];
                 } else {
                     unset($v['ext'], $v['status']);
                     ksort($v);
                     $v = serialize($v);
                 }
             }
             $hash = md5(mb_strtolower($v));
             if (!empty($unique_values[$hash])) {
                 unset($values[$k]);
                 continue;
             }
             $unique_values[$hash] = true;
         }
         $master[$f] = array_values($values);
     }
     // Save master contact
     $errors = $master->save(array(), 42);
     // 42 == do not validate anything at all
     if ($errors) {
         $errormsg = array();
         foreach ($errors as $field => $err) {
             if (!is_array($err)) {
                 $err = array($err);
             }
             foreach ($err as $str) {
                 $errormsg[] = $field . ': ' . $str;
             }
         }
         $result['error'] = implode("\n<br>", $errormsg);
         return $result;
     }
     // Merge categories
     $category_ids = array();
     $ccm = new waContactCategoriesModel();
     foreach ($ccm->getContactsCategories($merge_ids) as $cid => $cats) {
         $category_ids += array_flip($cats);
     }
     $category_ids = array_keys($category_ids);
     $ccm->add($master_id, $category_ids);
     // update photo
     if ($update_photo) {
         $rand = mt_rand();
         $path = wa()->getDataPath(waContact::getPhotoDir($master['id']), true, 'contacts', false);
         // delete old image
         if (file_exists($path)) {
             waFiles::delete($path);
         }
         waFiles::create($path);
         $filename = $path . "/" . $rand . ".original.jpg";
         waFiles::create($filename);
         waImage::factory($update_photo['original'])->save($filename, 90);
         if (!empty($update_photo['crop'])) {
             $filename = $path . "/" . $rand . ".jpg";
             waFiles::create($filename);
             waImage::factory($update_photo['crop'])->save($filename, 90);
         } else {
             waFiles::copy($filename, $path . "/" . $rand . ".jpg");
         }
         $master->save(array('photo' => $rand));
     }
     $result['total_merged'] = count($contacts_data) + 1;
     $contact_ids = array_keys($contacts_data);
     // wa_log
     $log_model = new waLogModel();
     $log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id));
     // wa_login_log
     $login_log_model = new waLoginLogModel();
     $login_log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id));
     // Merge event
     $params = array('contacts' => $contact_ids, 'id' => $master_data['id']);
     wa()->event(array('contacts', 'merge'), $params);
     // Delete all merged contacts
     $contact_model = new waContactModel();
     $contact_model->delete($contact_ids, false);
     // false == do not trigger event
     $history_model = new contactsHistoryModel();
     foreach ($contact_ids as $contact_id) {
         $history_model->deleteByField(array('type' => 'add', 'hash' => '/contact/' . $contact_id));
     }
     return $result;
 }
 /** Using $this->id get waContact and save it in $this->contact;
  * Load vars into $this->view specific to waContact. */
 protected function getContactInfo()
 {
     $system = wa();
     if ($this->id == $system->getUser()->getId()) {
         $this->contact = $system->getUser();
         $this->view->assign('own_profile', true);
     } else {
         $this->contact = new waContact($this->id);
         $this->view->assign('own_profile', false);
     }
     $exists = $this->contact->exists();
     if ($exists) {
         $this->view->assign('contact', $this->contact);
         // who created this contact and when
         $this->view->assign('contact_create_time', waDateTime::format('datetime', $this->contact['create_datetime'], $system->getUser()->getTimezone()));
         if ($this->contact['create_contact_id']) {
             try {
                 $author = new waContact($this->contact['create_contact_id']);
                 if ($author['name']) {
                     $this->view->assign('author', $author);
                 }
             } catch (Exception $e) {
                 // Contact not found. Ignore silently.
             }
         }
         $this->view->assign('top', $this->contact->getTopFields());
         // Main contact editor data
         $fieldValues = $this->contact->load('js', true);
         $m = new waContactModel();
         if (isset($fieldValues['company_contact_id'])) {
             if (!$m->getById($fieldValues['company_contact_id'])) {
                 $fieldValues['company_contact_id'] = 0;
                 $this->contact->save(array('company_contact_id' => 0));
             }
         }
         $contactFields = waContactFields::getInfo($this->contact['is_company'] ? 'company' : 'person', true);
         // Only show fields that are allowed in own profile
         if (!empty($this->params['limited_own_profile'])) {
             $allowed = array();
             foreach (waContactFields::getAll('person') as $f) {
                 if ($f->getParameter('allow_self_edit')) {
                     $allowed[$f->getId()] = true;
                 }
             }
             $fieldValues = array_intersect_key($fieldValues, $allowed);
             $contactFields = array_intersect_key($contactFields, $allowed);
         }
         contactsHelper::normalzieContactFieldValues($fieldValues, $contactFields);
         $this->view->assign('contactFields', $contactFields);
         $this->view->assign('contactFieldsOrder', array_keys($contactFields));
         $this->view->assign('fieldValues', $fieldValues);
         // Contact categories
         $cm = new waContactCategoriesModel();
         $this->view->assign('contact_categories', array_values($cm->getContactCategories($this->id)));
     } else {
         $this->view->assign('contact', array('id' => $this->id));
     }
     return $exists;
 }
 public function execute()
 {
     // $this->getConfig()->getCheckoutSettings()['contactinfo']
     $config = $this->params;
     if (empty($config)) {
         //$config_steps = $this->getConfig()->getCheckoutSettings();
         //$config = $config_steps['contactinfo']; // debug helper
         $config = array();
     }
     $fields_unsorted = waContactFields::getAll();
     // Allow to disable name field in form, despite that it is normally required.
     $fields_unsorted['name'] = clone $fields_unsorted['name'];
     $fields_unsorted['name']->setParameter('required', false);
     $fields_unsorted['address.billing'] = clone $fields_unsorted['address'];
     $fields_unsorted['address.billing']->setParameter('localized_names', _w('Billing address'));
     $fields_unsorted['address.shipping'] = clone $fields_unsorted['address'];
     $fields_unsorted['address.shipping']->setParameter('localized_names', _w('Shipping address'));
     // Load config parameters into cloned fields
     $fields = array();
     $config_fields = ifempty($config['fields'], array());
     foreach ($config_fields as $fld_id => $opts) {
         // Skip hidden fields (they are shown as 'disabled')
         if (!empty($opts['hidden'])) {
             continue;
         }
         // This allows to specify e.g. 'address.shipping' as field id in config.
         $real_fld_id = explode('.', $fld_id, 2);
         $real_fld_id = $real_fld_id[0];
         if (empty($fields_unsorted[$real_fld_id]) || !$fields_unsorted[$real_fld_id] instanceof waContactField || !is_array($opts)) {
             continue;
         }
         $fields[$fld_id] = clone $fields_unsorted[$real_fld_id];
         foreach ($opts as $k => $v) {
             if ($fields[$fld_id] instanceof waContactCompositeField && $k == 'fields') {
                 if (is_array($v)) {
                     $cloned_subfields = $v;
                     $unknown_subfields = array();
                     foreach ($cloned_subfields as $sf_id => $sf) {
                         $unknown_subfields[$sf_id] = true;
                     }
                     foreach ($fields[$fld_id]->getFields() as $sf) {
                         $sf = clone $sf;
                         $o = ifset($v[$sf->getId()]);
                         if (isset($unknown_subfields[$sf->getId()])) {
                             unset($unknown_subfields[$sf->getId()]);
                         }
                         if ($o && is_array($o) && empty($o['hidden'])) {
                             $sf->setParameters($o);
                             $cloned_subfields[$sf->getId()] = $sf;
                         } else {
                             if (isset($cloned_subfields[$sf->getId()])) {
                                 unset($cloned_subfields[$sf->getId()]);
                             }
                             $sf->setParameter('_disabled', true);
                             $cloned_subfields[] = $sf;
                         }
                     }
                     foreach ($unknown_subfields as $sf_id => $flag) {
                         unset($cloned_subfields[$sf_id]);
                     }
                     $fields[$fld_id]->setParameter('fields', $cloned_subfields);
                 }
             } else {
                 $fields[$fld_id]->setParameter($k, $v);
             }
         }
     }
     // Add to $fields everything that were not specified in config.
     foreach ($fields_unsorted as $fld_id => $f) {
         if (empty($fields[$fld_id])) {
             $fields[$fld_id] = clone $f;
             $fields[$fld_id]->setParameter('_disabled', true);
         }
     }
     // Address fields are shown separately
     $address = $fields['address'];
     $billing_address = $fields['address.billing'];
     $shipping_address = $fields['address.shipping'];
     unset($fields['address.billing'], $fields['address.shipping'], $fields['address']);
     $shipbill_address = array();
     $shipbill_address['ship'] = array('short_id' => 'ship', 'id' => 'address.shipping', 'name' => _w('Shipping address prompt'), 'f' => $shipping_address, 'subfields' => array(), 'show_custom_settings' => false);
     $shipbill_address['bill'] = array('short_id' => 'bill', 'id' => 'address.billing', 'name' => _w('Billing address prompt'), 'f' => $billing_address, 'subfields' => array(), 'show_custom_settings' => false);
     $address_subfields = $address->getFields();
     foreach ($address_subfields as $sf) {
         $sfa = array('id' => $sf->getId(), 'name' => $sf->getName(), 'enabled' => false, 'f' => $sf);
         $shipbill_address['ship']['subfields'][$sf->getId()] = $sfa;
         $shipbill_address['bill']['subfields'][$sf->getId()] = $sfa;
     }
     foreach ($shipping_address->getFields() as $sf) {
         if ($sf->getParameter('_disabled')) {
             $shipbill_address['ship']['show_custom_settings'] = true;
         } else {
             $shipbill_address['ship']['subfields'][$sf->getId()]['enabled'] = true;
         }
     }
     foreach ($billing_address->getFields() as $sf) {
         if ($sf->getParameter('_disabled')) {
             if (!empty($address_subfields[$sf->getId()]) && !$address_subfields[$sf->getId()]->getParameter('_disabled')) {
                 $shipbill_address['bill']['show_custom_settings'] = true;
             }
         } else {
             $shipbill_address['bill']['subfields'][$sf->getId()]['enabled'] = true;
         }
     }
     $this->view->assign('fields', $fields);
     $this->view->assign('address', $address);
     $this->view->assign('shipbill_address', $shipbill_address);
 }
 public function setOptions($config)
 {
     if (!waRequest::post()) {
         return $config;
     }
     $options = waRequest::post('options');
     if (!is_array($options)) {
         return $config;
     }
     $fields_unsorted = waContactFields::getAll();
     $config['fields'] = array();
     $cfvm = new waContactFieldValuesModel();
     foreach ($options as $fld_id => $opts) {
         if ($fld_id == '%FID%') {
             continue;
         }
         $fld_id_no_ext = explode('.', $fld_id, 2);
         $field_ext = empty($fld_id_no_ext[1]) ? '' : '.' . $fld_id_no_ext[1];
         $fld_id_no_ext = $fld_id_no_ext[0];
         $field = ifset($fields_unsorted[$fld_id_no_ext]);
         // Special treatment for subfields of shipping and billing address:
         // copy actual settings from address field.
         if ($field_ext && $fld_id_no_ext == 'address') {
             $existing_subfields = $field->getFields();
             // Sanity check
             if (!is_array($opts) || empty($options['address']) || !is_array($options['address']) || empty($options['address']['fields']) || !is_array($options['address']['fields'])) {
                 continue;
             }
             // Copy settings if subfield is turned on, or required, or is hidden
             $fields = array();
             foreach ($options['address']['fields'] as $sf_id => $sf_opts) {
                 if (!empty($sf_opts['required']) || !empty($sf_opts['_disabled']) && !empty($sf_opts['_default_value_enabled']) && empty($sf_opts['_deleted']) || !empty($opts['fields'][$sf_id])) {
                     if (!$field_ext || isset($existing_subfields[$sf_id])) {
                         $fields[$sf_id] = $sf_opts;
                     }
                 }
             }
             $opts['fields'] = $fields;
         }
         if ($field) {
             if (!empty($opts['_deleted'])) {
                 waContactFields::deleteField($field);
                 unset($fields_unsorted[$fld_id_no_ext]);
                 continue;
             }
             $new_field = false;
         } else {
             $field = self::createFromOpts($opts, $fields_unsorted);
             if (!$field || $field instanceof waContactCompositeField) {
                 continue;
             }
             // For conditional fields, update ID in database: replace temporary id with new one
             if ($field instanceof waContactConditionalField) {
                 $cfvm->changeField($fld_id_no_ext, $field->getId());
             }
             $fld_id = $field->getId() . $field_ext;
             $new_field = true;
         }
         list($local_opts, $sys_opts) = self::tidyOpts($field, $fld_id, $opts);
         if ($local_opts === null || $sys_opts === null) {
             continue;
         }
         // Write to system config.
         if (!$field_ext) {
             $field->setParameters($sys_opts);
             $fields_unsorted[$fld_id_no_ext] = $field;
             if ($new_field) {
                 waContactFields::createField($field);
                 waContactFields::enableField($field, 'person');
                 $fields_unsorted[$field->getId()] = $field;
             } else {
                 if ($sys_opts) {
                     waContactFields::updateField($field);
                     waContactFields::enableField($field, 'person');
                 }
             }
         }
         $config['fields'][$fld_id] = $local_opts;
     }
     // Delete garbage from wa_contact_field_values
     $cfvm->exec("DELETE FROM wa_contact_field_values WHERE field RLIKE '__[0-9]+\$'");
     return $config;
 }
 public function workupContacts(&$contacts)
 {
     if (!$contacts) {
         return array();
     }
     $contact_fields = array(array_keys(waContactFields::getAll('person', true)), array_keys(waContactFields::getAll('company', true)));
     foreach ($contacts as &$c) {
         $fields = $contact_fields[intval($c['is_company'])];
         $data = array('id' => $c['id']);
         foreach ($fields as $fld_id) {
             if (array_key_exists($fld_id, $c)) {
                 $data[$fld_id] = $c[$fld_id];
                 unset($c[$fld_id]);
             }
         }
         $c = array_merge($data, $c);
     }
     unset($c);
     // load that fields, that are top
     if ($this->getRequest()->request('top')) {
         foreach ($contacts as &$c) {
             $c['top'] = contactsHelper::getTop(new waContact($c['id']));
         }
         unset($c);
     }
 }
 public function execute()
 {
     $apps = wa()->getApps();
     $auth_apps = array();
     $domain = siteHelper::getDomain();
     $routes = wa()->getRouting()->getRoutes($domain);
     $auth_app_id = false;
     foreach ($routes as $route) {
         if (isset($route['app']) && isset($apps[$route['app']])) {
             $auth_apps[$route['app']] = true;
             $auth_app_id = $route['app'];
         }
     }
     $temp = array();
     foreach ($apps as $app_id => $app) {
         if (isset($app['frontend']) || isset($auth_apps[$app_id])) {
             $temp[$app_id] = array('id' => $app_id, 'icon' => $app['icon'], 'name' => $app['name']);
             if (isset($auth_apps[$app_id])) {
                 if (empty($app['auth'])) {
                     unset($auth_apps[$app_id]);
                 } else {
                     $auth_apps[$app_id] = $temp[$app_id];
                 }
             }
         }
     }
     foreach ($auth_apps as $app_id => &$a) {
         $a['login_url'] = wa()->getRouteUrl($app_id . '/login', array('domain' => $domain), true);
     }
     unset($a);
     $this->view->assign('auth_apps', $auth_apps);
     $auth_config = wa()->getAuthConfig(siteHelper::getDomain());
     $this->view->assign('auth_config', array('auth' => isset($auth_config['auth']) ? $auth_config['auth'] : false, 'app' => isset($auth_config['app']) ? $auth_config['app'] : $auth_app_id, 'signup_captcha' => isset($auth_config['signup_captcha']) ? $auth_config['signup_captcha'] : false, 'adapters' => isset($auth_config['adapters']) ? $auth_config['adapters'] : array()));
     $this->view->assign('auth_adapters', $this->getAuthAdapters());
     $this->view->assign('apps', $temp);
     $this->view->assign('domain_id', siteHelper::getDomainId());
     $domain = siteHelper::getDomain();
     $personal_sidebar = wa('site')->event('backend_personal');
     foreach ($personal_sidebar as &$items) {
         foreach ($items as &$item) {
             $item['url'] .= '&domain=' . urlencode($domain);
         }
     }
     $this->view->assign('domain', siteHelper::getDomain());
     $this->view->assign('domain_id', siteHelper::getDomainId());
     $this->view->assign('personal_sidebar', $personal_sidebar);
     // signup
     $fields = $enable_fields = array();
     $must_have_fields = array('email', 'password');
     $default_fields = array_merge(array('firstname', 'lastname', ''), $must_have_fields);
     $unset_fields = array('name');
     // include auth.php
     $domain_config_path = wa('site')->getConfig()->getPath('config', 'auth');
     if (file_exists($domain_config_path)) {
         $domain_config = (include $domain_config_path);
     } else {
         $domain_config = array();
     }
     // fields for this form (or default fields)
     $config_fields = isset($domain_config[$domain]['fields']) ? $domain_config[$domain]['fields'] : $default_fields;
     $separators = 0;
     foreach ($config_fields as $field_name => $field) {
         $fld_name = is_array($field) ? $field_name : $field;
         $fld_name = strlen($fld_name) ? $fld_name : $separators++;
         if (!$fld_name) {
             // todo: don't skip separator
             continue;
         }
         $enable_fields[$fld_name] = $field;
     }
     $available_fields = waContactFields::getAll('person', true) + array('password' => new waContactPasswordField('password', 'Password'));
     foreach ($available_fields as $field_name => $field) {
         $name = $field->getName();
         if ($name && !in_array($field_name, $unset_fields)) {
             $checked = array_key_exists($field_name, $enable_fields);
             $available_fields[$field_name] = array('id' => $field_name, 'name' => $name, 'checked' => $checked, 'disabled' => false);
             // only for 'must have' fields
             if (in_array($field_name, $must_have_fields)) {
                 $available_fields[$field_name]['disabled'] = true;
                 $available_fields[$field_name]['checked'] = true;
                 // if we don't have 'must have' fields - let's add'em
                 if (!array_key_exists($field_name, $enable_fields)) {
                     $enable_fields[$field_name] = $available_fields[$field_name];
                 }
             }
         } else {
             unset($available_fields[$field_name]);
         }
     }
     $enable_fields = array_merge_recursive($enable_fields, $available_fields);
     $this->view->assign('domain', $domain);
     $this->view->assign('enable_fields', $enable_fields);
     $this->view->assign('available_fields', $available_fields);
     $this->view->assign('fields', $fields);
     $this->view->assign('params', isset($domain_config[$domain]['params']) ? $domain_config[$domain]['params'] : array());
 }
 public function execute()
 {
     // only allowed to admin
     if ($this->getRights('backend') <= 1) {
         throw new waRightsException(_w('Access denied'));
     }
     $ids = waRequest::request('ids', array(), 'array_int');
     $collection = new contactsCollection('id/' . implode(',', $ids));
     $collection->orderBy('~data', 'DESC');
     $contacts = $collection->getContacts('*,photo_url_96', 0, 500);
     foreach ($contacts as &$c) {
         $c['name'] = waContactNameField::formatName($c);
     }
     unset($c);
     // Field names
     $fields = array();
     // field id => field name
     foreach (waContactFields::getAll('enabled') as $field_id => $field) {
         $fields[$field_id] = $field->getName();
         // Format data for template if needed
         foreach ($contacts as &$c) {
             if (empty($c[$field_id])) {
                 continue;
             }
             if (!is_array($c[$field_id]) || $this->is_assoc($c[$field_id])) {
                 $c[$field_id] = $field->format($c[$field_id], 'html');
             } else {
                 foreach ($c[$field_id] as &$v) {
                     $v = $field->format($v, 'html');
                 }
                 unset($v);
                 $c[$field_id] = implode(', ', $c[$field_id]);
             }
         }
         unset($c);
     }
     // skip some fields in the list
     $fields = array_diff_key($fields, array('title' => true, 'name' => true, 'photo' => true, 'firstname' => true, 'middlename' => true, 'lastname' => true, 'locale' => true, 'timezone' => true));
     // Initialize 'master_only' key
     foreach ($contacts as &$c) {
         $c['master_only'] = '';
     }
     unset($c);
     // Event to allow other applications to add their data if needed
     $params = array_keys($contacts);
     $links = wa()->event('links', $params);
     $apps = wa()->getApps();
     foreach ($links as $app_id => $app_links) {
         foreach ($app_links as $contact_id => $contact_links) {
             foreach ($contact_links as $l) {
                 // Show information about links
                 $field_name = $apps[$app_id]['name'] . '/' . $l['role'];
                 $fields[$field_name] = $field_name;
                 $contacts[$contact_id][$field_name] = _w("%d link", "%d links", $l['links_number']);
                 // Show warning if this contact cannot be merged into other contacts.
                 if (!empty($l['forbid_merge_reason'])) {
                     if (!empty($contacts[$contact_id]['master_only'])) {
                         $contacts[$contact_id]['master_only'] .= '<br>';
                     } else {
                         $contacts[$contact_id]['master_only'] = '';
                     }
                     $contacts[$contact_id]['master_only'] .= $l['forbid_merge_reason'];
                 }
             }
         }
     }
     // List of contacts that can be safely merged into other contacts
     $slave_ids = array();
     foreach ($contacts as &$c) {
         if ($c['is_user'] > 0) {
             $c['master_only'] = ($c['master_only'] ? $c['master_only'] . '<br>' : '') . _w('Users can not be merged into other contacts.');
         } else {
             if (empty($c['master_only'])) {
                 $slave_ids[] = $c['id'];
             }
         }
         $author = array('name' => '');
         if ($c['create_contact_id']) {
             $author_contact = new waContact($c['create_contact_id']);
             if ($author_contact->exists()) {
                 $author = $author_contact;
             }
         }
         $c['author'] = $author;
     }
     unset($c);
     $this->view->assign('slave_ids', $slave_ids);
     $this->view->assign('contacts', $contacts);
     $this->view->assign('fields', $fields);
 }
示例#18
0
<?php

// add social netform field
$field = waContactFields::get('socialnetwork', 'all');
if ($field->getType() === 'SocialNetwork') {
    $sort = 0;
    foreach (waContactFields::getAll('person') as $field_id => $fld) {
        if ($field_id == 'im') {
            break;
        }
        $sort += 1;
    }
    waContactFields::updateField($field);
    waContactFields::enableField($field, 'person', $sort);
}
// socail network field add domain parameter
$f = waContactFields::get('socialnetwork');
$f->setParameter('domain', array('facebook' => 'facebook.com', 'vkontakte' => 'vk.com', 'twitter' => 'twitter.com', 'linkedin' => null));
waContactFields::updateField($f);
// Update birthday field
$field = waContactFields::get('birthday');
if ($field && $field instanceof waContactDateField) {
    $params = $field->getParameters();
    $new_field = new waContactBirthdayField('birthday', 'Birthday', array('storage' => 'info', 'prefix' => 'birth'));
    $params = array_merge($params, $new_field->getParameters());
    $new_field->setParameters($params);
    waContactFields::updateField($new_field);
}
$field = waContactFields::get('birthday');
if ($field) {
    $params = $field->getParameters();
 public function execute()
 {
     $id = waRequest::request('id', null, waRequest::TYPE_INT);
     $scm = new shopCustomerModel();
     $customer = $scm->getById($id);
     try {
         $contact = new waContact($id);
         $contact->getName();
     } catch (waException $e) {
         // !!! What to do when shop_customer exists, but no wa_contact found?
         throw $e;
     }
     $ccsm = new waContactCategoriesModel();
     $contact_categories = $ccsm->getContactCategories($id);
     $contacts_url = wa()->getAppUrl('contacts');
     // Info above tabs
     $top = array();
     foreach (array('email', 'phone', 'im') as $f) {
         if ($v = $contact->get($f, 'top,html')) {
             $top[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
         }
     }
     // Get photo
     $photo = $contact->get('photo');
     $config = $this->getConfig();
     $use_gravatar = $config->getGeneralSettings('use_gravatar');
     $gravatar_default = $config->getGeneralSettings('gravatar_default');
     if (!$photo && $use_gravatar) {
         $photo = shopHelper::getGravatar($contact->get('email', 'default'), 96, $gravatar_default);
     } else {
         $photo = $contact->getPhoto(96);
     }
     $contact['photo'] = $photo;
     // Customer orders
     $im = new shopOrderItemsModel();
     $orders_collection = new shopOrdersCollection('search/contact_id=' . $id);
     $total_count = $orders_collection->count();
     $orders = $orders_collection->getOrders('*,items,params', 0, $total_count);
     shopHelper::workupOrders($orders);
     foreach ($orders as &$o) {
         $o['total_formatted'] = waCurrency::format('%{s}', $o['total'], $o['currency']);
         $o['shipping_name'] = ifset($o['params']['shipping_name'], '');
         $o['payment_name'] = ifset($o['params']['payment_name'], '');
         // !!! TODO: shipping and payment icons
     }
     // Customer reviews
     $prm = new shopProductReviewsModel();
     $reviews = $prm->getList('*,is_new,product', array('escape' => false, 'where' => array('contact_id' => $id), 'limit' => false));
     // Customer affiliate transactions history
     $atm = new shopAffiliateTransactionModel();
     $affiliate_history = $atm->getByContact($id);
     $this->view->assign('top', $top);
     $this->view->assign('orders', $orders);
     $this->view->assign('reviews', $reviews);
     $this->view->assign('contact', $contact);
     $this->view->assign('customer', $customer);
     $this->view->assign('contacts_url', $contacts_url);
     $this->view->assign('affiliate_history', $affiliate_history);
     $this->view->assign('contact_categories', $contact_categories);
     $this->view->assign('def_cur_tmpl', str_replace('0', '%s', waCurrency::format('%{s}', 0, wa()->getConfig()->getCurrency())));
     $this->view->assign('point_rate', str_replace(',', '.', (double) str_replace(',', '.', wa()->getSetting('affiliate_usage_rate'))));
     $fields = waContactFields::getAll('person');
     if (isset($fields['name'])) {
         unset($fields['name']);
     }
     $this->view->assign('fields', $fields);
     $this->view->assign('orders_default_view', $config->getOption('orders_default_view'));
     /*
      * @event backend_customer
      * @return array[string]array $return[%plugin_id%] array of html output
      * @return array[string][string]string $return[%plugin_id%]['info_section'] html output
      * @return array[string][string]string $return[%plugin_id%]['name_suffix'] html output
      * @return array[string][string]string $return[%plugin_id%]['header'] html output
      * @return array[string][string]string $return[%plugin_id%]['action_link'] html output
      */
     $this->view->assign('backend_customer', wa()->event('backend_customer', $customer));
 }
 public function clearDisabledFields()
 {
     if (!$this->id) {
         return;
     }
     $disabled_fields = waContactFields::getAll($this['is_company'] ? 'company_disabled' : 'person_disabled', true);
     $data = array();
     foreach ($disabled_fields as $field_id => $field) {
         $data[$field->getStorage()->getType()][$field_id] = $field->prepareSave(null);
     }
     foreach ($data as $storage => $storage_data) {
         waContactFields::getStorage($storage)->set($this, $storage_data);
     }
 }
 public function load($format = false, $all = false)
 {
     if (!$this->id) {
         return $this->data;
     } else {
         $cache = isset(self::$cache[$this->id]) ? self::$cache[$this->id] : array();
         $fields = waContactFields::getAll($this['is_company'] ? 'company' : 'person', $all);
         // Get field to load from Storages
         $load = array();
         foreach ($fields as $field) {
             /**
              * @var waContactField $field
              */
             if (!isset($cache[$field->getId()])) {
                 $load[$field->getStorage()->getType()] = true;
             }
         }
         // Load data from storages
         foreach ($load as $storage => $bool) {
             waContactFields::getStorage($storage)->get($this);
         }
         // format accordingly
         if ($format) {
             $result = array();
             foreach ($fields as $field) {
                 $result[$field->getId()] = $field->get($this, $format);
             }
         } else {
             $result = self::$cache[$this->id];
             foreach ($fields as $field) {
                 $result[$field->getId()] = $field->get($this);
             }
             foreach ($result as $field_id => $value) {
                 if (!isset($fields[$field_id]) && is_array($value)) {
                     if (isset($value[0]['value'])) {
                         $result[$field_id] = $value[0]['value'];
                     }
                 }
             }
             // remove some fields
             unset($result['password']);
         }
         return $result;
     }
 }
示例#22
0
 /**
  * @return waContactForm
  */
 protected function getForm()
 {
     // Read all contact fields and find all enabled for "my profile"
     $fields = array('photo' => new waContactHiddenField('photo', _ws('Photo'))) + waContactFields::getAll('person') + array('password' => new waContactPasswordField('password', _ws('Password'))) + array('password_confirm' => new waContactPasswordField('password_confirm', _ws('Confirm password')));
     $domain = wa()->getRouting()->getDomain();
     $domain_config_path = wa()->getConfig()->getConfigPath('domains/' . $domain . '.php', true, 'site');
     if (file_exists($domain_config_path)) {
         $domain_config = (include $domain_config_path);
     } else {
         $domain_config = array();
     }
     $enabled = array();
     foreach ($fields as $fld_id => $f) {
         if (!empty($domain_config['personal_fields'][$fld_id])) {
             $enabled[$fld_id] = $f;
             if ($fld_id === 'password') {
                 $enabled[$fld_id . '_confirm'] = $fields[$fld_id . '_confirm'];
             }
         }
     }
     // If nothing found, fall back to the default field list
     if (!$enabled) {
         foreach (array('firstname', 'middlename', 'lastname', 'email', 'phone', 'password') as $fld_id) {
             if (!empty($fields[$fld_id])) {
                 $enabled[$fld_id] = $fields[$fld_id];
             }
         }
     }
     return waContactForm::loadConfig($enabled, array('namespace' => 'profile'));
 }
示例#23
0
 public function getTopFields()
 {
     $top = array();
     static $fields = null;
     if ($fields === null) {
         $fields = array(waContactFields::getAll('person', true), waContactFields::getAll('company', true));
     }
     $country_model = new waCountryModel();
     $iso3letters_map = $country_model->select('DISTINCT iso3letter')->fetchAll('iso3letter', true);
     foreach ($fields[intval($this['is_company'])] as $f) {
         $info = $f->getInfo();
         if ($f->getParameter('top') && ($value = $this->get($info['id'], 'top,html'))) {
             if ($info['type'] == 'Address') {
                 $data = $this->get($info['id']);
                 $data_for_map = $this->get($info['id'], 'forMap');
                 $value = (array) $value;
                 foreach ($value as $k => &$v) {
                     if (isset($data[$k]['data']['country']) && isset($iso3letters_map[$data[$k]['data']['country']])) {
                         $v = '<img src="' . wa_url() . 'wa-content/img/country/' . strtolower($data[$k]['data']['country']) . '.gif" /> ' . $v;
                     }
                     $map_url = '';
                     if (is_string($data_for_map[$k])) {
                         $map_url = $data_for_map[$k];
                     } else {
                         if (!empty($data_for_map[$k]['coords'])) {
                             $map_url = $data_for_map[$k]['coords'];
                         } else {
                             if (!empty($data_for_map[$k]['with_street'])) {
                                 $map_url = $data_for_map[$k]['with_street'];
                             }
                         }
                     }
                     $v .= ' <a target="_blank" href="//maps.google.com/maps?q=' . urlencode($map_url) . '&z=15" class="small underline map-link">' . _w('map') . '</a>';
                     $v = '<div data-subfield-index=' . $k . '>' . $v . '</div>';
                 }
                 unset($v);
             }
             $delimiter = $info['type'] == 'Composite' || $info['type'] == 'Address' ? "<br>" : ", ";
             $top[] = array('id' => $info['id'], 'name' => $f->getName(), 'value' => is_array($value) ? implode($delimiter, $value) : $value, 'icon' => $info['type'] == 'Email' || $info['type'] == 'Phone' ? strtolower($info['type']) : '', 'pic' => '');
         }
     }
     return $top;
 }