<?php

class Addresses extends PhonalisaRecord
{

    public $file;
    public $id;
    public $ldapId;
    public $ldapInterface;
    public $contact_id;
    public $contact_tid;
    public $contact_addrbook_type;
    public $contact_owner;
    public $contact_private;
    public $cat_id;
    public $n_family;
    public $n_given;
    public $n_middle;
    public $n_prefix;
    public $n_suffix;
    public $n_fn;
    public $n_fileas;
    public $contact_bday;
    public $org_name;
    public $org_unit;
    public $contact_title;
    public $contact_role;
    public $contact_assistent;
    public $contact_room;
    public $adr_one_street;
    public $adr_one_street2;
    public $adr_one_locality;
    public $adr_one_region;
    public $adr_one_postalcode;
    public $adr_one_countryname;
    public $contact_label;
    public $adr_two_street;
    public $adr_two_street2;
    public $adr_two_locality;
    public $adr_two_region;
    public $adr_two_postalcode;
    public $adr_two_countryname;
    public $tel_work;
    public $tel_work_ic;
    public $tel_cell;
    public $tel_cell_ic;
    public $tel_fax;
    public $tel_fax_ic;
    public $tel_assistent;
    public $tel_assistent_ic;
    public $tel_car;
    public $tel_car_ic;
    public $tel_pager;
    public $tel_pager_ic;
    public $tel_home;
    public $tel_home_ic;
    public $tel_fax_home;
    public $tel_fax_home_ic;
    public $tel_cell_private;
    public $tel_cell_private_ic;
    public $tel_other;
    public $tel_other_ic;
    public $tel_prefer;
    public $tel_prefer_ic;
    public $contact_email;
    public $contact_email_home;
    public $contact_url;
    public $contact_url_home;
    public $contact_freebusy_uri;
    public $contact_calendar_uri;
    public $contact_note;
    public $contact_tz;
    public $contact_geo;
    public $contact_pubkey;
    public $contact_created;
    public $contact_creator;
    public $contact_modified;
    public $contact_modifier;
    public $contact_jpegphoto;
    public $account_id;
    public $contact_uid;
    public $social_network1;
    public $social_network2;
    public $social_network_user1;
    public $social_network_user2;
    public $contact_type;
    public $facebook_profile_url;
    public $twitter_profile_url;
    public $google_profile_url;
    public $linkedin_profile_url;
    public $xing_profile_url;
    public $day;
    public $month;
    public $year;
    public $avatarSizes = array(40, 80, 460);
    public $googleId;
    public $xingId;
    public $changed;
    public $source;
    public $ringtone;

    public function behaviors()
    {
        return array(
            'AttributesBackupBehavior' => 'ext.AttributesBackupBehavior',
        );
    }

    public static function myAttributes()
    {
        return array(
            'contact_type' => 'contact_type',
            'id' => 'id',
            'ldapId' => 'ldapId',
            'ldapInterface' => 'ldapInterface',
            'googleId' => 'googleId',
            'xingId' => 'xingId',
            'contact_tid' => 'contact_tid',
            'contact_addrbook_type' => 'contact_addrbook_type',
            'contact_owner' => 'contact_owner',
            'contact_private' => 'contact_private',
            'cat_id' => 'cat_id',
            'n_family' => 'n_family',
            'n_given' => 'n_given',
            'n_middle' => 'n_middle',
            'n_prefix' => 'n_prefix',
            'n_suffix' => 'n_suffix',
            'n_fn' => 'n_fn',
            'n_fileas' => 'n_fileas',
            'contact_bday' => 'contact_bday',
            'org_name' => 'org_name',
            'org_unit' => 'org_unit',
            'contact_title' => 'contact_title',
            'contact_role' => 'contact_role',
            'contact_assistent' => 'contact_assistent',
            'contact_room' => 'contact_room',
            'adr_one_street' => 'adr_one_street',
            'adr_one_street2' => 'adr_one_street2',
            'adr_one_locality' => 'adr_one_locality',
            'adr_one_region' => 'adr_one_region',
            'adr_one_postalcode' => 'adr_one_postalcode',
            'adr_one_countryname' => 'adr_one_countryname',
            'contact_label' => 'contact_label',
            'adr_two_street' => 'adr_two_street',
            'adr_two_street2' => 'adr_two_street2',
            'adr_two_locality' => 'adr_two_locality',
            'adr_two_region' => 'adr_two_region',
            'adr_two_postalcode' => 'adr_two_postalcode',
            'adr_two_countryname' => 'adr_two_countryname',
            'tel_work' => 'tel_work',
            'tel_work_ic' => 'tel_work_ic',
            'tel_cell' => 'tel_cell',
            'tel_cell_ic' => 'tel_cell_ic',
            'tel_fax' => 'tel_fax',
            'tel_fax_ic' => 'tel_fax_ic',
            'tel_assistent' => 'tel_assistent',
            'tel_assistent_ic' => 'tel_assistent_ic',
            'tel_car' => 'tel_car',
            'tel_car_ic' => 'tel_car_ic',
            'tel_pager' => 'tel_pager',
            'tel_pager_ic' => 'tel_pager_ic',
            'tel_home' => 'tel_home',
            'tel_home_ic' => 'tel_home_ic',
            'tel_fax_home' => 'tel_fax_home',
            'tel_fax_home_ic' => 'tel_fax_home_ic',
            'tel_cell_private' => 'tel_cell_private',
            'tel_cell_private_ic' => 'tel_cell_private_ic',
            'tel_other' => 'tel_other',
            'tel_other_ic' => 'tel_other_ic',
            'tel_prefer' => 'tel_prefer',
            'tel_prefer_ic' => 'tel_prefer_ic',
            'contact_email' => 'contact_email',
            'contact_email_home' => 'contact_email_home',
            'contact_url' => 'contact_url',
            'contact_url_home' => 'contact_url_home',
            'contact_freebusy_uri' => 'contact_freebusy_uri',
            'contact_calendar_uri' => 'contact_calendar_uri',
            'contact_note' => 'contact_note',
            'contact_tz' => 'contact_tz',
            'contact_geo' => 'contact_geo',
            'contact_pubkey' => 'contact_pubkey',
            'contact_created' => 'contact_created',
            'contact_creator' => 'contact_creator',
            'contact_modified' => 'contact_modified',
            'contact_modifier' => 'contact_modifier',
            'contact_jpegphoto' => 'contact_jpegphoto',
            'account_id' => 'account_id',
            'contact_uid' => 'contact_uid',
            'social_network1' => 'social_network1',
            'social_network2' => 'social_network2',
            'social_network_user1' => 'social_network_user1',
            'social_network_user2' => 'social_network_user2',
            'facebook_profile_url' => 'facebook_profile_url',
            'twitter_profile_url' => 'twitter_profile_url',
            'google_profile_url' => 'google_profile_url',
            'linkedin_profile_url' => 'linkedin_profile_url',
            'xing_profile_url' => 'xing_profile_url',
            'changed' => 'changed',
            'source' => 'source',
            'ringtone' => 'ringtone'
        );
    }

    public static function csvRelevantAttributes()
    {
        return array(
            //Header
            'n_prefix' => array('length' => 64),
            'n_given' => array('length' => 64),
            'n_middle' => array('length' => 64),
            'n_family' => array('length' => 64),
            'org_name' => array('length' => 128),
            // Company imformations
            'tel_work' => array('length' => 40),
            'tel_cell' => array('length' => 40),
            'tel_fax' => array('length' => 40),
            'contact_email' => array('length' => 64),
            'contact_type' => array('length' => 64,
                'relation' => array(
                    'model' => 'ContactType',
                    'value' => 'name'
                )
            ),
            //private Informations
            'tel_home' => array('length' => 40),
            'tel_cell_private' => array('length' => 40),
            'tel_fax_home' => array('length' => 40),
            'contact_email_home' => array('length' => 64),
            'contact_url_home' => array('length' => 128),
            //Company location
            'adr_one_street' => array('length' => 64),
            'adr_one_postalcode' => array('length' => 64),
            'adr_one_locality' => array('length' => 64),
            'adr_one_countryname' => array('length' => 64),
            //Privat location
            'adr_two_street' => array('length' => 64),
            'adr_two_postalcode' => array('length' => 64),
            'adr_two_locality' => array('length' => 64),
            'adr_two_countryname' => array('length' => 64),
            //Contact Company info
            'org_unit' => array('length' => 64),
            'contact_role' => array('length' => 64),
            'contact_room' => array('length' => 64),
            'tel_assistent' => array('length' => 40),
            'contact_url' => array('length' => 128),
            'contact_freebusy_uri' => array('length' => 128),
            'contact_pubkey' => array('safe' => 'true'),
            'contact_label' => array('safe' => 'true'),
            'contact_assistent' => array('length' => 64),
            'contact_note' => array('safe' => 'true'), //FIXME ... encode new line and delimiter chars ... 
            //Contact social network informations
            'facebook_profile_url' => array('length' => 255),
            'twitter_profile_url' => array('length' => 255),
            'google_profile_url' => array('length' => 255),
            'xing_profile_url' => array('length' => 255),
            'linkedin_profile_url' => array('length' => 255),
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Addresses the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'addresses';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.

        return array(
            array('contact_owner, contact_tid', 'required'),
            array('ldapId, ldapInterface', 'required', 'on' => 'LdapImport'),
            array('contact_private, contact_created, contact_creator, contact_modified, contact_modifier,
			     account_id', 'numerical', 'integerOnly' => true),
            array('contact_addrbook_type ', 'length', 'max' => 1),
            array('contact_email,contact_email_home ', 'email'),
            #array('contact_email,contact_email_home', 'isMail', 'on'=>'create, update'),
            // array('contact_bday','checkBirthday'),
            array('contact_bday', 'safe'),
            //array('contact_bday','length','max'=>10),
            array('cat_id, n_fileas, contact_uid, social_network1, social_network_user1, social_network2, social_network_user2, facebook_profile_url, twitter_profile_url, google_profile_url, linkedin_profile_url, xing_profile_url', 'length', 'max' => 255),
            array('n_family, n_given, n_middle, n_prefix, n_suffix,
			     org_unit, contact_title, contact_role, contact_assistent,
			     contact_room, adr_one_street, adr_one_street2, adr_one_locality, adr_one_region,
			     adr_one_postalcode, adr_one_countryname, adr_two_street, adr_two_street2, adr_two_locality,
			     adr_two_region, adr_two_postalcode, adr_two_countryname', 'length', 'max' => 64),
            array('n_fn, org_name, contact_email, contact_email_home, contact_url,
                ldapId,contact_url_home, contact_freebusy_uri, contact_calendar_uri,contact_type', 'length', 'max' => 128),
            //array('contact_bday', 'length', 'max'=>12),
            array('tel_work, tel_work_ic, tel_cell, tel_cell_ic, tel_fax,
			     tel_fax_ic, tel_assistent, tel_assistent_ic, tel_car, tel_car_ic,
			     tel_pager, tel_pager_ic, tel_home, tel_home_ic, tel_fax_home,
			     tel_fax_home_ic, tel_cell_private, tel_cell_private_ic, tel_other, tel_other_ic',
                'length', 'max' => 40),
            array('tel_prefer, tel_prefer_ic, contact_geo', 'length', 'max' => 32),
            array('contact_tz', 'length', 'max' => 8),
            array('contact_label, contact_note, contact_pubkey, contact_jpegphoto, ringtone', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('contact_id, contact_tid, contact_addrbook_type, contact_owner, contact_private,
			     cat_id, n_family, n_given, n_middle, n_prefix, n_suffix,
			     n_fn, n_fileas, contact_bday, org_name, org_unit,
			     contact_title, contact_role, contact_assistent, contact_room, adr_one_street,
			     adr_one_street2, adr_one_locality, adr_one_region, adr_one_postalcode, adr_one_countryname,
			     contact_label, adr_two_street, adr_two_street2, adr_two_locality, adr_two_region,
			     adr_two_postalcode, adr_two_countryname, tel_work, tel_work_ic, tel_cell,
			     tel_cell_ic, tel_fax, tel_fax_ic, tel_assistent, tel_assistent_ic,
			     tel_car, tel_car_ic, tel_pager, tel_pager_ic, tel_home,
			     tel_home_ic, tel_fax_home, tel_fax_home_ic, tel_cell_private, tel_cell_private_ic,
			     tel_other, tel_other_ic, tel_prefer, tel_prefer_ic, contact_email,
			     contact_email_home, contact_url, contact_url_home, contact_freebusy_uri, contact_calendar_uri,
			     contact_note, contact_tz, contact_geo, contact_pubkey, contact_created,
			     contact_creator, contact_modified, contact_modifier, contact_jpegphoto, account_id,
			     contact_uid', 'safe', 'on' => 'search'),
            array(
                'source, changed', 'safe',
            ),
            array('contact_jpegphoto', 'file', 'types' => 'jpeg, jpg, gif, png', 'maxSize' => 1024 * 1024 * 10,
                'tooLarge' => 'The file is larger than 10 MB. Please upload a smaler file.',
                'allowEmpty' => true),
        );
    }
    /*
      public function isMail($attribute, $params) {

      $models = User::model()->findAllByAttributes(array($attribute=>$this->$attribute));

      if (preg_match('/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$/', $attribute)) {
      $this->addError($attribute, __('Your entry already exists. Please choose another.'));
      return false;
      }else{

      return true;
      }

      }
     */

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    public function phoneNumbers()
    {

        $numbers = array();

        if ($this->tel_work != '') {
            //$numbers["Company Phone \n <"tel_work">"] = $this->tel_work;
            $numbers["tel_work"] = $this->tel_work_ic;
        }
        if ($this->tel_cell != '') {
            //$numbers["Mobile Phone \n <".$this->tel_cell.">"] = $this->tel_cell;
            $numbers["tel_cell"] = $this->tel_cell_ic;
        }
        if ($this->tel_home != '') {
            //$numbers["Privat Phone \n <".$this->tel_home.">"] = $this->tel_home;
            $numbers["tel_home"] = $this->tel_home_ic;
        }
        if ($this->tel_cell_private != '') {
            //$numbers["Privat Mobile \n <".$this->tel_cell_private.">"] = $this->tel_cell_private;
            $numbers["tel_cell_private"] = $this->tel_cell_private_ic;
        }
        if ($this->tel_assistent != '') {
            //$numbers["Phone Assistent \n <".$this->tel_assistent.">"] = $this->tel_assistent;
            $numbers["tel_assistent"] = $this->tel_assistent_ic;
        }

        return $numbers;
    }

    public function phoneContactNames()
    {
        $name = '';
        if ($this->org_name) {
            $name.= $this->org_name . ", ";
        }
        if ($this->n_prefix) {
            $name.= $this->n_prefix . " ";
        }
        if ($this->n_family) {
            $name.= $this->n_family . ", ";
        }
        if ($this->n_given) {
            $name.= $this->n_given . " ";
        }
        if ($this->n_middle) {
            $name.= $this->n_middle;
        }
        return $name;
    }

    public function phoneContactPhotos($data)
    {

        $host = $_SERVER['HTTP_HOST'];
        $requestURI = $_SERVER['REQUEST_URI'];

        list ($protocol) = preg_split("/\//", $_SERVER['SERVER_PROTOCOL']);
        $protocol = strtolower($protocol);

        $url = $protocol . "://" . $host;

        $photo = $data->getPhotoUrl(40);

        return $url . $photo;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('ADDRESSESS_MODEL_ID'),
//             'contact_id'            => __('Contact'),
            'contact_tid' => __('ADDRESSESS_MODEL_CONTACT_TID'),
            'contact_addrbook_type' => __('ADDRESSESS_MODEL_CONTACT_ADDRBOOK_TYPE'),
            'contact_owner' => __('ADDRESSESS_MODEL_CONTACT_OWNER'),
            'contact_private' => __('ADDRESSESS_MODEL_CONTACT_PRIVATE'),
            'cat_id' => __('ADDRESSESS_MODEL_CAT_ID'),
            'n_family' => __('ADDRESSESS_MODEL_N_FAMILY'),
            'n_given' => __('ADDRESSESS_MODEL_N_GIVEN'),
            'n_middle' => __('ADDRESSESS_MODEL_N_MIDDLE'),
            'n_prefix' => __('ADDRESSESS_MODEL_N_PREFIX'),
            'n_suffix' => __('ADDRESSESS_MODEL_N_SUFFIX'),
            'n_fn' => __('ADDRESSESS_MODEL_N_FN'),
            'n_fileas' => __('ADDRESSESS_MODEL_N_FILEAS'),
            'contact_bday' => __('ADDRESSESS_MODEL_CONTACT_BDAY'),
            'org_name' => __('ADDRESSESS_MODEL_ORG_NAME'),
            'org_unit' => __('ADDRESSESS_MODEL_ORG_UNIT'),
            'contact_title' => __('ADDRESSESS_MODEL_CONTACT_TITLE'),
            'contact_role' => __('ADDRESSESS_MODEL_CONTACT_ROLE'),
            'contact_assistent' => __('ADDRESSESS_MODEL_CONTACT_ASSISTENT'),
            'contact_room' => __('ADDRESSESS_MODEL_CONTACT_ROOM'),
            'adr_one_street' => __('ADDRESSESS_MODEL_ADR_ONE_STREET'),
            'adr_one_street2' => __('ADDRESSESS_MODEL_ADR_ONESTREET2'),
            'adr_one_locality' => __('ADDRESSESS_MODEL_ADR_ONE_LOCALITY'),
            'adr_one_region' => __('ADDRESSESS_MODEL_ADR_ONE_REGION'),
            'adr_one_postalcode' => __('ADDRESSESS_MODEL_ADR_ONE_POSTALCODE'),
            'adr_one_countryname' => __('ADDRESSESS_MODEL_ADR_ONE_COUNTRYNAME'),
            'contact_label' => __('ADDRESSESS_MODEL_CONTACT_LABEL'),
            'adr_two_street' => __('ADDRESSESS_MODEL_ADR_TWO_STREET'),
            'adr_two_street2' => __('ADDRESSESS_MODEL_TWO_STREET2'),
            'adr_two_locality' => __('ADDRESSESS_MODEL_ADR_TWO_LOCALITY'),
            'adr_two_region' => __('ADDRESSESS_MODEL_ADR_TWO_REGION'),
            'adr_two_postalcode' => __('ADDRESSESS_MODEL_ADR_TWO_POSTALCODE'),
            'adr_two_countryname' => __('ADDRESSESS_MODEL_ADR_TWO_COUNTRYNAME'),
            'tel_work' => __('ADDRESSESS_MODEL_TEL_WORK'),
            'tel_work_ic' => __('ADDRESSESS_MODEL_TEL_WORK_IC'),
            'tel_cell' => __('ADDRESSESS_MODEL_TEL_CELL'),
            'tel_cell_ic' => __('ADDRESSESS_MODEL_TEL_CELL_IC'),
            'tel_fax' => __('ADDRESSESS_MODEL_TEL_FAX'),
            'tel_fax_ic' => __('ADDRESSESS_MODEL_TEL_FAX_IC'),
            'tel_assistent' => __('ADDRESSESS_MODEL_TEL_ASSISTENT'),
            'tel_assistent_ic' => __('ADDRESSESS_MODEL_TEL_ASSISTENT_IC'),
            'tel_car' => __('ADDRESSESS_MODEL_TEL_CAR'),
            'tel_car_ic' => __('ADDRESSESS_MODEL_TEL_CAR_IC'),
            'tel_pager' => __('ADDRESSESS_MODEL_TEL_PAGER'),
            'tel_pager_ic' => __('ADDRESSESS_MODEL_TEL_PAGER_IC'),
            'tel_home' => __('ADDRESSESS_MODEL_TEL_HOME'),
            'tel_home_ic' => __('ADDRESSESS_MODEL_TEL_HOME_IC'),
            'tel_fax_home' => __('ADDRESSESS_MODEL_TEL_FAX_HOME'),
            'tel_fax_home_ic' => __('ADDRESSESS_MODEL_TEL_FAX_HOME_IC'),
            'tel_cell_private' => __('ADDRESSESS_MODEL_TEL_CELL_PRIVATE'),
            'tel_cell_private_ic' => __('ADDRESSESS_MODEL_TEL_CELL_PRIVATE_IC'),
            'tel_other' => __('ADDRESSESS_MODEL_TEL_OTHER'),
            'tel_other_ic' => __('ADDRESSESS_MODEL_TEL_OTHER_IC'),
            'tel_prefer' => __('ADDRESSESS_MODEL_TEL_PRFER'),
            'tel_prefer_ic' => __('ADDRESSESS_MODEL_TEL_PRFER_IC'),
            'contact_email' => __('ADDRESSESS_MODEL_CONTACT_EMAIL'),
            'contact_email_home' => __('ADDRESSESS_MODEL_CONTACT_EMAIL_HOME'),
            'contact_url' => __('ADDRESSESS_MODEL_CONTACT_URL'),
            'contact_url_home' => __('ADDRESSESS_MODEL_CONTACT_URL_HOME'),
            'contact_freebusy_uri' => __('ADDRESSESS_MODEL_CONTACT_FREEBUSY_URI'),
            'contact_calendar_uri' => __('ADDRESSESS_MODEL_CONTACT_CALENDAR_URI'),
            'contact_note' => __('ADDRESSESS_MODEL_CONTACT_NOTE'),
            'contact_tz' => __('ADDRESSESS_MODEL_CONTACT_TZ'),
            'contact_geo' => __('ADDRESSESS_MODEL_CONTACT_GEO'),
            'contact_pubkey' => __('ADDRESSESS_MODEL_CONTACT_PUBKEY'),
            'contact_created' => __('ADDRESSESS_MODEL_CONTACT_CREATED'),
            'contact_creator' => __('ADDRESSESS_MODEL_CONTACT_CREATOR'),
            'contact_modified' => __('ADDRESSESS_MODEL_CONTACT_MODIFIED'),
            'contact_modifier' => __('ADDRESSESS_MODEL_CONTACT_MODIFIER'),
            'contact_jpegphoto' => __('ADDRESSESS_MODEL_CONTACT_JPEGPHOTO'),
            'account_id' => __('ADDRESSESS_MODEL_ACCOUNT_ID'),
            'contact_uid' => __('ADDRESSESS_MODEL_CONTACT_UID'),
            'social_network1' => __('ADDRESSESS_MODEL_SOCIAL_NETWORK1'),
            'social_network2' => __('ADDRESSESS_MODEL_SOCIAL_NETWORK2'),
            'social_network_user1' => __('ADDRESSESS_MODEL_SOCIAL_NETWORK_USER1'),
            'social_network_user2' => __('ADDRESSESS_MODEL_SOCIAL_NETWORK_USER2'),
            'contact_type' => __('ADDRESSESS_MODEL_CONTACT_TYPE'),
            'day' => __('ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_DAY'),
            'month' => __('ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_MONTH'),
            'year' => __('ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_YEAR'),
            'source' => __('ADDRESSESS_MODEL_SOURCE'),
            'ldapId' => __('ADMIN_LDAP_INTERFACE_LDAP_ID'),
            'ldapInterface' => __('ADDRESSESS_MODEL_LDAP_INTERFACE')
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CPhonalisaDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    private function createPermutedSearchQuery()
    {
        $query = '';

        foreach ($_GET['Addresses'] as $field => $value) {
            if ($value != '') {
                $query .= $field . '=' . implode('*|', permute($value));
                $query .= '* AND ';
            }
        }
        return $query;
    }

    public function search($bookId, $order = 'n_family')
    {


        //dump($filter);

        /*
          if ($filter != null) {
          return new CPhonalisaDataProvider($this, $filter);
          }
         */



        $book = Addressbook::model()->findByPk($bookId);

        if ($book == null)
            throw new CHttpException(404, 'Addressbook not found.');

        $query = '';
        $query .= 'contact_tid=' . $bookId;

        // get only owned addresses
        if ($book->type == AddressbookType::personal)
            $query .= ' AND contact_owner=' . Yii::app()->user->sudoUser;

        /*
          // Add more options if searching
          if(isset($_GET['Addresses']['search'])){
          //foreach($this->myAttributes() as $attribute){
          //    $condition .= ' AND '.$attribute.'='.$_GET['Addresses']['search'].'* OR';
          //}

          $query.= ' AND n_family='.$_GET['Addresses']['search'].'*';
          #$condition = rtrim($condition, ' OR');
          }
         */

        // Multi sarchfield search
        if (isset($_GET['Addresses'])) {
            $criteria = new CDbCriteria;
            $filter = $this->getFilter($criteria, !isset($_REQUEST['sort']) ? $order : $_REQUEST['sort']);

            $filter['criteria']->condition = $this->createPermutedSearchQuery() . $query;

            if ($filter != null) {

                return new CPhonalisaDataProvider($this, $filter);
            }
        }



        $options = array(
            'criteria' => array(
                'condition' => $query,
                'order' => !isset($_REQUEST['sort']) ? $order : null,
            ),
            'pagination' => array(
                'pageSize' => 17,
            ),
            'sort' => array(
                'defaultOrder' => $order,
            )
        );

        return new CPhonalisaDataProvider('Addresses', $options);
    }

    public function renderName(PhonalisaRecord $data, $row)
    {

        $namePattern = getFormatedNameToUser($data, 'addressbook');
        return $namePattern;
    }

    public function renderAddresses(PhonalisaRecord $data, $row)
    {
        $name = '';
        $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_LOCALITY');
        $name.='<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_LOCALITY" title="' . $translation . '">';

        if ($data->adr_one_street) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_STREET');
            $name.='<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_STREET" title="' . $translation . '">';
            $name.= CHtml::encode($data->adr_one_street);
            $name.= "</div>";
        }
        if ($data->adr_one_street2) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_STREET2');
            $name.='<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_STREET2" title="' . $translation . '">';
            $name.= CHtml::encode($data->adr_one_street2);
            $name.= "</div>";
        }
        if ($data->adr_one_postalcode) {
            $name.= CHtml::encode($data->adr_one_postalcode) . ' ';
        }
        if ($data->adr_one_locality) {
            $name.= CHtml::encode($data->adr_one_locality) . "<br>";
        }
        $name.= '</div>';

        return $name;
    }

    public function renderWebCompany(PhonalisaRecord $data, $row)
    {

        $web = '';
        if ($data->contact_email) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_MAIL');
            $encodedEmail = CHtml::encode($data->contact_email);
            $web.= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_MAIL" title="' . $translation . '"><i class="icon-envelope"> </i>' . CHtml::link($encodedEmail, 'mailto:' . $encodedEmail) . '</div>';
        }
        if ($data->contact_email_home) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_PRIVATE_MAIL');
            $encodedEmailHome = CHtml::encode($data->contact_email_home);
            $web.= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_PRIVATE_MAIL" title="' . $translation . '"><i class="icon-envelope"> </i>' . CHtml::link($encodedEmailHome, 'mailto:' . $encodedEmailHome) . '</div>';
        }

        return $web;
    }

    public function renderWebPrivate(PhonalisaRecord $data, $row)
    {

        $web = '';
        if ($data->contact_email_home) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_PRIVATE_MAIL');
            $web.= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_PRIVATE_MAIL" title="' . $translation . '"><i class="icon-envelope"> </i>' . CHtml::link($data->contact_email_home, 'mailto:' . CHtml::encode($data->contact_email_home)) . '</div>';
        }
        if ($data->contact_url_home) {

            $url = CHtml::encode($data->contact_url_home);

            if (strpos(substr($url, 0, 10), "//") === FALSE) {
                $url = "http://" . $url;
            }
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_PRIVATE_URL');
            $web.= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_PRIVATE_URL" title="' . $translation . '"><i class="icon-globe"> </i>' . CHtml::link($data->contact_url_home, $url, array("target" => "_blank")) . '</div>';
        }
        return $web;
    }

    public function getPhotoUrl($size = 460)
    {
        if ($this->contact_jpegphoto != '1') {
            return bu() . '/img/backgrounds/noAvatar.png';
        }
        $url = Yii::app()->createUrl('addressbookAddresses/default/photoshow', array('modelId' => $this->id, 'size' => $size, 'changed' => $this->changed));
        return $url;
    }

    public function renderPhoto(PhonalisaRecord $data, $row)
    {
        //dump($data->attributes);
        $photo = '';

        //$attribure = $data->avatarSizes;
        //$attribure = $attribure[0];
        if ($data->contact_jpegphoto == '1') {
            $photo = CHtml::image(
                            $data->getPhotoUrl(80), '', array('style' => 'height:64px;width:64px')
            );
        }
        return $photo;
    }

    public function renderTelWork(PhonalisaRecord $data, $row)
    {
        $phone = '';

        if ($data->tel_work) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_TEL_WORK');
            $phone .= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_TEL_WORK" class="callable" data-phone-number="' . $data->tel_work_ic . '" title="' . $translation . '">';
            $phone .= '<i class="icon-phone" >&nbsp;</i>';
            $phone .= CHtml::encode($data->tel_work) . '</div>';
        }
        if ($data->tel_fax) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_FAX');
            $phone .= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_COMPANY_FAX" title="' . $translation . '">';
            $phone .= '<i class="icon-print" >&nbsp;</i>';
            $phone .= CHtml::encode($data->tel_fax) . '</div>';
        }
        return $phone;
    }

    public function renderTelPrivate(PhonalisaRecord $data, $row)
    {
        $phone = '';

        if ($data->tel_home) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_PHONE_HOME');
            $phone .= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_PHONE_HOME" class="callable" data-phone-number="' . $data->tel_home_ic . '" title="' . $translation . '">';
            $phone .= '<i class="icon-phone" >&nbsp;</i>';
            $phone .= CHtml::encode($data->tel_home) . '</div>';
        }
        if ($data->tel_cell_private) {
            $translation = __('ADDRESSBOOK_ADDRESSES_MOUSEROVER_PHONE_PRIVAT');
            $phone .= '<div data-translation-id="ADDRESSBOOK_ADDRESSES_MOUSEROVER_PHONE_PRIVAT" class="callable" data-phone-number="' . $data->tel_cell_private_ic . '" title="' . $translation . '">';
            $phone .= '<i class="icon-signal" >&nbsp;</i>';
            $phone .= CHtml::encode($data->tel_cell_private) . '</div>';
        }

        return $phone;
    }

    public function renderBDayForm()
    {
        $currentDate = array('', '', '');
        if (isset($this->contact_bday) && $this->contact_bday != '') {
            $currentDate = explode('-', CHtml::encode($this->contact_bday));
        }

        $year = CHtml::activeTextField($this, 'year', array(
                    'style' => 'width:35px;',
                    'value' => $currentDate[0],
                    "maxlength" => "4",
                    'placeholder' => __('ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_YEAR'),
                    'data-translation-id' => 'ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_YEAR',
        ));
        $month = CHtml::activeTextField($this, 'month', array(
                    'style' => 'width:20px',
                    'value' => $currentDate[1],
                    "maxlength" => "2",
                    'placeholder' => __('ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_MONTH'),
                    'data-translation-id' => 'ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_MONTH'
        ));
        $day = CHtml::activeTextField($this, 'day', array(
                    'style' => 'width:20px',
                    "maxlength" => "2",
                    'value' => $currentDate[2],
                    'placeholder' => __('ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_DAY'),
                    'data-translation-id' => 'ADDRESSESS_MODEL_CONTACT_BDAY_PATTERN_DAY'
        ));

        $bDayTextFields = '';
        switch (cfg('USER_DATE_FORMAT')) {
            case 'm/d/Y':
                $bDayTextFields = $month . ' / ';
                $bDayTextFields.= $day . ' / ';
                $bDayTextFields.= $year;
                break;
            case 'd.m.Y':
                $bDayTextFields = $day . '.';
                $bDayTextFields.= $month . '.';
                $bDayTextFields.= $year;
                break;
            case 'Y-m-d':
                $bDayTextFields = $year . '-';
                $bDayTextFields.= $month . '-';
                $bDayTextFields.= $day;
                break;
        }
        return $bDayTextFields;
    }

    public function renderBday(PhonalisaRecord $data, $row)
    {
        return CHtml::encode($data->contact_bday);
    }

    //         public function freeSearch($criteria,$pattern) {
    //
    //             $initial=$_POST['pattern'];
    //             print_r($initial);
    // //            FIXME add compare attributes for quick search function
    //             $criteria->compare('n_family', $initial . '%', true, 'OR', false);
    //             $criteria->compare('n_given', $initial . '%', true, 'OR', false);
    //             $criteria->compare('org_name', $initial . '%', true, 'OR', false);
    //
    //             return $criteria;
    //
    //         }

    public function renderDataCell($data, $row, $column)
    {

        $imortedValues = $column->grid->viewData;
        return $imortedValues['userData'][$row][$column->name];
    }
    #####FIXME ! social network just for testing! not final ####

    public function SocialNetwork1()
    {

        return CHtml::dropDownList('Addresses[social_network1]', $this->social_network1, array(__('ADDRESSES_MODEL_SOCIAL_NETWORK_SELECT') => array(
                        '' => '',
                        'facebook' => __('Facebook'),
                        'google' => __('Google+'),
                        'xing' => __('XING'),
                        'twitter' => __('Twitter'),
        )));
    }

    public function SocialNetwork2()
    {

        return CHtml::dropDownList('Addresses[social_network2]', $this->social_network2, array(__('ADDRESSES_MODEL_SOCIAL_NETWORK_SELECT') => array(
                        '' => '',
                        'facebook' => __('Facebook'),
                        'google' => __('Google+'),
                        'xing' => __('XING'),
                        'twitter' => __('Twitter'),
        )));
    }
    #####social network stuff ends here! #####

    public function getDataFromCSV($csv)
    {
        $arrayDataProviderAddresses = array();

        $address = new Addresses();
        $address->id = $address->contact_id;
        foreach ($csv as $dataSet) {
            $arrayDataProviderAddresses[] = $address;
        }

        $dataProvider = new CArrayDataProvider($arrayDataProviderAddresses, array(
            'id' => 'key',
            'sort' => array(
                'attributes' => array(
                ),
            ),
        ));

        return $dataProvider;
    }
    /*
      public function checkBirthday($attribute,$params) {

      if ($this->$attribute == '' ) {
      return true;
      }

      switch (cfg('USER_DATE_FORMAT')){
      case 'yyyy-MM-dd':
      $date = explode ('-', $this->$attribute);
      $d = 2;
      $m = 1;
      $y = 0;
      break;
      case 'dd.MM.yyyy':
      $date = explode ('.', $this->$attribute);
      $d = 0;
      $m = 1;
      $y = 2;
      break;
      case 'MM/dd/yyyy':
      $date = explode ('/', $this->$attribute);
      $d = 1;
      $m = 0;
      $y = 2;
      break;
      }
      if(isset($date[$m])) {
      $this->month = $date[$m];
      }
      if(isset($date[$d])) {
      $this->day   =$date[$d];
      }
      if(isset($date[$y])) {
      $this->year  = $date[$y];
      }
      if (!checkdate((int)$this->month,(int)$this->day , (int)$this->year )) {
      $this->addError($attribute, __('ADDRESSESS_MODEL_CONTACT_BDAY_ERROR_MESSAGE'));
      return false;
      }
      if ((int)$this->day < 10) {
      $this->day = "0".(int)$this->day;
      }
      if ((int)$this->month < 10) {
      $this->month = "0".(int)$this->month;
      }
      $this->$attribute = $this->year.'-'.$this->month.'-'.$this->day;

      return true;
      } */

    /*
      public function beforeValidate() {
      $this->contact_owner = Yii::app()->user->sudoUser;
      return parent::beforeValidate();
      }
     */

    public function beforeDelete()
    {

        $deletedItem = new DeletedItem();
        $deletedItem->model_id = $this->id;
        $deletedItem->model_name = get_Class($this);
        $deletedItem->deleted = time();

        if ($deletedItem->save()) {
            return parent::beforeDelete();
        }
        return false;
    }

    public function afterDelete()
    {
        $contactType = new ContactType;
        $contactType->deleteContactType($this->contact_type);
        $this->deleteVCardData();

        return parent::afterDelete();
    }

    public function deleteVCardData()
    {
        $vCardData = iCloudData::model()->findByAttributes(array('fileId' => $this->id));

        if (!empty($vCardData)) {
            $vCardData->delete();
        }
    }

    private function canonizeNumbers()
    {

        //these are the telephone-numeric fields
        $fields = array();

        $fields[] = "tel_work";
        $fields[] = "tel_cell";
        $fields[] = "tel_fax";
        $fields[] = "tel_assistent";
        $fields[] = "tel_car";
        $fields[] = "tel_pager";
        $fields[] = "tel_home";
        $fields[] = "tel_fax_home";
        $fields[] = "tel_cell_private";
        $fields[] = "tel_other";

        foreach ($fields as $field) {
            $field_ic = $field . "_ic";
            if ($this->$field != "") {
                $this->$field_ic = NumberCanonizer::canonize($this->$field);
            } else {
                $this->$field_ic = "";
            }
        }
    }

    public function getCanonizedNumber($number)
    { //  number == 0049123437548
        if ($number == null || $number == "") {
            return "";
        }

        $DP_INTL_PREFIX = cfg('DP_INTL_PREFIX');
        // check if number starts with DP_INTL_PREFIX 
        if ($DP_INTL_PREFIX != "" && substr($number, 0, strlen($DP_INTL_PREFIX)) == $DP_INTL_PREFIX) { // if yes, cut DP_INTL_PREFIX
            $number = "0" . substr($number, strlen($DP_INTL_PREFIX));
        }

        return cfg('DP_AUTO_DIALOUT_PREFIX') . $number;
    }

    public function beforeSave()
    {
        if (!$this->source) {
            $this->source = AddressSourceType::USER;
        }

        $currentAdressbook = Addressbook::model()->findByPk($this->contact_tid);
        if ($currentAdressbook->type != AddressbookType::personal) {
            $this->ringtone = '';
        }

        if (!isset($this->id)) {
            $this->contact_created = PhonalisaDate::newServerTimestamp();
        }

        //update canonized numbers needed for reverse search
        $this->canonizeNumbers();

        if ($this->contact_owner != 'intern' && empty($this->contact_owner)) { //FIXME
            $this->contact_owner = Yii::app()->user->sudoUser;
        }

        $this->changed = time();

        return parent::beforeSave();
    }

    public function downloadContactImage()
    {
        //$urlParts = parse_url($this->image);
        $tempPath = Yii::app()->runtimePath . '/' . $this->id . basename($this->contact_jpegphoto);

        $ch = curl_init($this->contact_jpegphoto);
        $fp = fopen($tempPath, 'wb');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        if (cfg('HTTP_PROXY_IP_ADDRESS') != '') {
            curl_setopt($ch, CURLOPT_PROXY, cfg('HTTP_PROXY_IP_ADDRESS') . ":" . cfg('HTTP_PROXY_PORT'));
        }

        if (!curl_exec($ch)) {
            curl_close($ch);
            fclose($fp);
            unlink($tempPath);
            return false;
        }

        curl_close($ch);
        fclose($fp);


        if ($this->isImage($tempPath)) {
            $this->contact_jpegphoto = '1';
            $this->save();
            $this->saveImage($tempPath);
        } else {
            unlink($tempPath);
        }
    }

    public function isImage($path)
    {
        $a = getimagesize($path);
        $image_type = $a[2];

        if (in_array($image_type, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP))) {
            return true;
        }
        return false;
    }

    public function saveImage($tempSrcPath)
    {
        $resizeHelper = new ImageResize($tempSrcPath);
        foreach ($this->avatarSizes as $size) {
            $tempPath = Yii::app()->runtimePath . "/" . $this->id . '_' . $size . ".jpg";

            $resizeHelper->resizeImage((int) $size, (int) $size, 'crop');
            $resizeHelper->saveImage($tempPath, 80);

            $this->saveFileToFieldByPath("image_" . $size, $tempPath);
            unlink($tempPath);
        }
        unlink($tempSrcPath);
    }

    public function afterSave()
    {
        $remoteImageFound = stripos($this->contact_jpegphoto, "http") === 0;
        if ($remoteImageFound) {
            $this->downloadContactImage();
        }

        if (!empty($_FILES['Addresses']['tmp_name']['contact_jpegphoto'])) {
            $file = CUploadedFile::getInstance($this, 'contact_jpegphoto');

            if ($file->tempName != '') {
                $tempOriginalPath = Yii::app()->runtimePath . '/' . $this->id . $file->name;
                $file->saveAs($tempOriginalPath);


                $this->saveImage($tempOriginalPath);
            }
        }

        if (isset($this->oldAttributes['contact_type'])) {
            $contactType = new ContactType;
            $contactType->deleteContactType($this->oldAttributes['contact_type']);
        }

        if (($this->scenario != 'Import') && $this->addressChanged()) {
            $this->updateICloudContactLists();
        }

        return parent::afterSave();
    }

    private function addressChanged()
    {
        $iCloudRelevantAttributes = iCloudContactsList::getICloudRelevantAttributes();

        if (empty($this->oldAttributes)) {
            return true;
        } elseif (!empty($this->oldAttributes['contact_bday']) && !empty($this->attributes['contact_bday'])) {
            $oldBirthday = PhonalisaDate::userDate(($this->oldAttributes['contact_bday']));
            $newBrithday = PhonalisaDate::userDate(($this->attributes['contact_bday']));
            if (strcmp($oldBirthday, $newBrithday) != 0) {
                return true;
            }
        }

        foreach ($iCloudRelevantAttributes as $value) {
            if (($this->attributes[$value] != $this->oldAttributes[$value])) {
                return true;
            }
        }

        if (!empty($_FILES['Addresses']['tmp_name']['contact_jpegphoto'])) {
            return true;
        }

        return false;
    }

    private function updateICloudContactLists()
    {
        $iCloudContactsLists = iCloudContactsList::model()->findAllByAttributes(array('plDirectoryId' => $this->contact_tid));
        if (!empty($iCloudContactsLists)) {
            foreach ($iCloudContactsLists as $iCloudContactsList) {
                $iCloudContactsList->updateICloudContactsList('uploadList', $this->id);
            }
        }
    }

    public function createCopy($newAttrubutes = array())
    {
        $copy = new Addresses;
        $copy->attributes = $this->attributes;
        $copy->contact_jpegphoto = $this->contact_jpegphoto;

        foreach ($newAttrubutes as $attribute => $value) {
            $copy->$attribute = $value;
        }

        $copy->save();

        foreach ($this->avatarSizes as $size) {

            $length = 0;
            $data = "";

            $this->getBinaryField("image_" . $size, $data, $length);
            $copy->saveBinaryField("image_" . $size, $data, $length);
        }

        return $copy;
    }

    public function getFormatedName()
    {

        $namePattern = getFormatedNameToUser($this, 'addressbook');
        return $namePattern;
    }

    public function getVCardString()
    {
        $card = 'BEGIN:VCARD\nVERSION:4.0\n';

        // FIXME: encode model values        
        $card .= 'FN:' . $this->getFormatedName() . '\n'; //

        $card .= 'END:VCARD';
        return $card;
    }

    public function getCsvValues()
    {

        $valueList = array();
        foreach (Addresses::csvRelevantAttributes() as $attribute => $params) {
            if (isset($params["relation"])) {
                $relatedModel = new $params["relation"]["model"];
                $relatedModel = $relatedModel->findByPk($this->$attribute);
                $valueList[] = $relatedModel->{$params["relation"]["value"]};
            } else {
                $valueList[] = $this->$attribute;
            }
        }
    }

    public static function getTelAttributes()
    {
        $model = new Addresses();
        $attributeNames = $model->getTelAttributeKeys();

        $translatedAttributenames = array();
        foreach ($attributeNames as $attributeName) {
            $translatedAttributenames[$attributeName] = $model->getAttributeLabel($attributeName);
        }
        return $translatedAttributenames;
    }

    public static function isNumberAttribute($attributeName)
    {
        $attributeNames = Addresses::getTelAttributeKeys();
        return in_array($attributeName, $attributeNames);
    }

    public static function getTelAttributeKeys()
    {
        return array(
            'tel_work',
            'tel_cell',
            'tel_fax',
            'tel_assistent',
            'tel_home',
            'tel_fax_home',
            'tel_cell_private'
        );
    }

    public static function isCanonizedNumberAttribute($attributeName)
    {
        $attributeNames = Addresses::getCanonizedAttributeKeys();
        return in_array($attributeName, $attributeNames);
    }

    public static function getCanonizedAttributeKeys()
    {
        $attributeNames = Addresses::getTelAttributeKeys();
        $canonizedAttributeNames = array();
        foreach ($attributeNames as $attributeName) {
            $canonizedAttributeNames[] = $attributeName."_ic";
        }
        return $canonizedAttributeNames;
    }

    public function isICloudImported()
    {
        $result = false;
        if ($this->source === AddressSourceType::ICLOUD || iCloudData::model()->findByAttributes(array('fileId' => $this->id))) {
            $result = true;
        }
        return $result;
    }
}
