<?php

class DefaultController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column1';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function hasWritePermission()
    {
        // prevent to check access on photoshow
        if ($this->action->id == 'photoshow' || $this->action->id == 'lastContact') {
            return false;
        }

        $user = $this->getCurrentUser();
        $bookId = $this->getBookId("write", false);

        if ($user->hasPermission($bookId, 'write')) {
            return 'true';
        }
        return 'false';
    }

    public function hasCsvImportPermission()
    {
        // prevent to check access on photoshow
        if ($this->action->id == 'photoshow') {
            return false;
        }

        $user = $this->getCurrentUser();
        $bookId = $this->getBookId();

        if ($user->hasPermission($bookId, 'csvImport')) {
            return 'true';
        }
        return 'false';
    }

    public function getCurrentUser($allowSudoer = true)
    {
        if ($allowSudoer == true) {
            return app()->user->sudoUserInstance;
        }
        return app()->user->realUserInstance;
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('photoShow', 'canonizeNumber', 'manageAddress'),
                'users' => array('*'),
            ),
            array('allow', // check for read Permissions
                'actions' => array(
                    "processAjaxAction",
                    "ajaxDelete",
                    'index',
                    'ajaxGetContactTypeValues',
                    'csvExport',
                    'downloadCsv',
                    'xingImport',
                    'getJsonAddress',
                    'addressList',
                    'view',
                    'getJsonAddressCanonizedNumber',
                    'lastContact',
                    'ajaxCreateDeleteMessage'
                ), //FIXME !
                'users' => array('@'),
            //'expression'=>AccessManager::checkSessionPermission($this->module->id),
            ),
            array('allow', // check for write permissions
                'actions' => array('clearTmp', 'delete'),
                'expression' => $this->hasWritePermission(),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionGetJsonAddressCanonizedNumber()
    {
        $addr = Addresses::model()->findByPk($_REQUEST['addressId']);
        
        if (!Addresses::isCanonizedNumberAttribute($_REQUEST['attributeName'])) {
            throw new CHttpException(403, "Forbidden");
        }
        
        $number = $addr->getCanonizedNumber($addr->{$_REQUEST['attributeName']});
        echo json_encode(array('number' => $number));
    }

    public function actionAjaxGetContactTypeValues()
    {
        echo json_encode(ContactType::getDefinedContactTypes());
    }

    public function addContactType(&$model)
    {
        $defaults = ContactType::getDefinedContactTypes();


        foreach ($defaults as $default) {

            if ($model->contact_type === (string) $default->id) {
                return;
            }
        }


        $contactType = new ContactType();
        $contactType->name = $model->contact_type;
        if (!$contactType->save()) {
            throw new CHttpException(500, 'could not create ContactType Object');
        }
        $model->contact_type = $contactType->id;
    }

    public function actionSaveInputData($model)
    {
        if ($this->userHasNoWritePermissions()) {
            Log::w("Try to save Address without write permission");
            throw new CHttpException(403, "Forbidden");
        }

        unset($_POST['Addresses']["source"]);
        $model->attributes = $_POST['Addresses'];
        $model->contact_owner = Yii::app()->user->sudoUser;

        if (isset($model->contact_bday) && strlen($model->contact_bday) != 0) {
            $pattern = PhonalisaDate::userDatePattern();
            $model->contact_bday = PhonalisaDate::newServerDate($model->contact_bday, $pattern);
        }


        if (!empty($_FILES['Addresses']['tmp_name']['contact_jpegphoto'])) {
            $model->contact_jpegphoto = '1';
        } else {
            if (isset($_POST['deleteImg'])) {
                $model->contact_jpegphoto = '0';
                //foreach($model->avatarSizes as $size){
                // FIXME: remove binaryFile !!!
                //$attribute = 'image_'.$size;
                //}
            }
        }

        //ContactType Stuff :

        $this->addContactType($model, $_POST['Addresses']['contact_type']);

        if ($model->save()) {
            $this->initiateSyncForEachContactList($model->contact_tid);
            return true;
        } else {
            Log::e(json_encode($model->errors));
            return false;
        }
    }

    private function userHasNoWritePermissions()
    {
        $currentAddressBook = isset($_REQUEST["id"]) ? Addressbook::model()->findByPk($_REQUEST["id"]) : $this->getCurrentBook("write", false);
        if (!$currentAddressBook) {
            return false;
        }
        $currentUser = $this->getCurrentUser();
        $permissionModel = new Permissions();
        $permissions = $permissionModel->getPermissionsArray(
                array(
            "itemId" => $currentAddressBook->id,
            "groupId" => $currentUser->group,
            "type" => "write"
                ), true);
        if (!empty($permissions)) {
            return false;
        }
        return true;
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = $this->loadModel($id);
            $model->delete();
            $this->initiateSyncForEachContactList($model->contact_tid);
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    private function initiateSyncForEachContactList($addressBookID)
    {
        $iCloudContactsLists = iCloudContactsList::model()->findAllByAttributes(array('plDirectoryId' => $addressBookID));
        if (!empty($iCloudContactsLists)) {
            foreach ($iCloudContactsLists as $iCloudContactsList) {
                if (isset($iCloudContactsList)) {
                    $iCloudContactsList->startICloudSync();
                }
            }
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex($id = null)
    {
        $user = app()->user->sudoUserInstance;
        if ($user && $id == null) {
            $firstAddressBook = $user->getAddressBooks();

            if (count($firstAddressBook)) {
                // sort by title caseinsensitive
                uasort($firstAddressBook, function ($a, $b) {
                    return strnatcmp(strtolower($a->title), strtolower($b->title));
                });

                foreach ($firstAddressBook as $book) {
                    $id = $book->id;
                    break;
                }
            } else {
                throw new CHttpException('403', "Forbidden4");
            }
        }

        $bookId = $this->getBookId();
        $model = new Addresses('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Addresses'])) {
            $model->attributes = $_GET['Addresses'];
        }

        $addressBookModel = Addressbook::model()->findByPk($id);
        if ($addressBookModel == null) {
            throw new Exception('Addressbook not found');
        }

        $writePermissions = $user->hasPermission($bookId, 'write');

        if (isset($_GET['ajax']) && $_GET['ajax'] == 'addresses-grid') {

            $this->renderPartial('addressList', array(
                //'model'=>$model,
                'writePermissions' => $writePermissions,
                'dataProvider' => $model->search($id),
                'model' => $model,
                'addressBookId' => $id,
                'addressBookModel' => $addressBookModel,
                'bookId' => $bookId,
            ));
            Yii::app()->end();
        }

        $this->render('index', array(
            //'model'=>$model,
            'writePermissions' => $writePermissions,
            'dataProvider' => $model->search($id),
            'model' => $model,
            'addressBookModel' => $addressBookModel,
            'bookId' => $bookId,
        ));
    }

    public function getFirstModelFromDataprovider($dataProvider)
    {

        if (isset($_GET['addressId'])) {
            $model = Addresses::model()->findByPk($_GET['addressId']);
            if ($model !== null) {
                $this->formatModelBDayToUserFormat($model);
                return $model;
            }
        }

        $model = new Addresses();
        $firstModel = $dataProvider->data;
        $firstModel = !empty($dataProvider->data) ? $firstModel[0] : null;
        $model = isset($firstModel) && $firstModel != null ? $firstModel : $model;
        $this->formatModelBDayToUserFormat($model);
        return $model;
    }

    private function formatModelBDayToUserFormat(&$model)
    {
        if (isset($model->contact_bday) && strlen($model->contact_bday) != 0) {
            $pattern = PhonalisaDate::userDatePattern();
            $model->contact_bday = PhonalisaDate::convertServerDateTo($pattern, $model->contact_bday);
        }
    }

    /**
     * Manages all models.
     */
    public function getCurrentBook($permissionType = "read")
    {
        $id = $this->getBookId($permissionType);
        $addrbooks = $this->getCurrentUser()->getAddressBooks();
        if (array_key_exists($id, $addrbooks)) {
            return $addrbooks[$id];
        }
        return null;
    }

    public function getSelectedRows($limit = 100, $offset = 0)
    {
        if (isset($_POST['selectedRows'])) {
            foreach ($_POST['selectedRows'] as $id) {
                $models[] = Addresses::model()->findByPk($id);
            }
            return $models;
        }
        return false;
    }

    public function getBookId($permissionsType = "read", $throwErrors = true)
    {
        $user = $this->getCurrentUser();
        if (!$user) {
            app()->user->logout();
            app()->user->loginRequired();
        }
        $addressBooks = $user->getAddressbooks();
        //Sorting for menu
        $addressBooksSorted = array();
        foreach ($addressBooks as $id => $addressBook) {
            $addressBooksSorted[strtolower($addressBook->title)] = $addressBook;
        }
        ksort($addressBooksSorted, SORT_NATURAL);


        $bookId = false;

        if (isset($_REQUEST['id']) && !isset($_REQUEST['bookId'])) {

            $bookId = $_REQUEST['id'];
            if (!$user->hasPermission($bookId, $permissionsType)) {
                if ($throwErrors) {
                    throw new CHttpException(403, 'Forbidden1');
                } else {
                    return false;
                }
            } else {
                return $bookId;
            }
        }

        if (isset($_REQUEST['bookId'])) {
            $bookId = $_REQUEST['bookId'];
            if (!$user->hasPermission($bookId, $permissionsType)) {
                if ($throwErrors) {
                    throw new CHttpException(403, 'Forbidden2');
                } else {
                    return false;
                }
            } else {
                return $bookId;
            }
        }

        foreach ($addressBooksSorted as $book) {
            if ($user->hasPermission($book->id, $permissionsType)) {
                return $book->id;
            }
        }

        return $bookId;
    }

    // // // // //    PHOTO UPLOADE !
    public function actionPhotoshow($id = "", $size = 80)
    {
        session_cache_limiter('none');
        header('Cache-control: max-age=' . (60 * 60 * 24 * 365));
        header('Pragma: public');
        header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365));

        $headers = getallheaders();
        if (isset($headers['If-Modified-Since'])) {
            if (strtotime($headers['If-Modified-Since']) < time() - 600) {
                header('HTTP/1.1 304 Not Modified');
                exit;
            }
        }

        if ($id == "") {
            $id = $_GET['modelId'];
        }

        if (isset($_GET['size']) && $_GET['size'] != "") {
            $size = $_GET['size'];
        }


        $model = $this->loadModel($id);

        $data = "";
        $length = 0;
        if ($model != null && $model->getBinaryField('image_' . $size, $data, $length)) {
            $this->renderPartial('_photoImage', array("data" => $data));
        }
        //$this->renderPartial('_photoImage', array("model" => $model));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Addresses::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }

        if (cfg('USER_DATE_FORMAT') != 'yyyy-mm-dd') {

            $date = explode('-', $model->contact_bday);
            $d = 2;
            $m = 1;
            $y = 0;

            if (cfg('USER_DATE_FORMAT') == 'dd.mm.yyyy') {
                if (isset($date[$d]) && isset($date[$m]) && isset($date[$y])) {
                    $model->contact_bday = $date[$d] . '.' . $date[$m] . '.' . $date[$y];
                }
            }
            if (cfg('USER_DATE_FORMAT') == 'mm/dd/yyyy') {
                if (isset($date[$d]) && isset($date[$m]) && isset($date[$y])) {
                    $model->contact_bday = $date[$m] . '/' . $date[$d] . '/' . $date[$y];
                }
            }
        }

        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'addressbookaddresses-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function getAddressbooksToMove($type = "move")
    {

        $addressbooks = $this->getCurrentUser()->getAddressbooks("write");

        $titles = array();

        foreach ($addressbooks as $addrbook) {
            if ($type == 'move' && $addrbook->type != AddressbookType::intern) {
                if ($addrbook->id != $this->getBookId()) {
                    $titles[$type . "_" . $addrbook->id] = $addrbook->title;
                }
            } elseif ($type == 'copy' && $addrbook->type != AddressbookType::intern) {
                if ($addrbook->id != $this->getBookId()) {
                    $titles[$type . "_" . $addrbook->id] = $addrbook->title;
                }
            }
        }

        return $titles;
    }

    public function getAddressbooksOptions($addressBookModel)
    {
        $bookOptions = array();
        foreach ($this->getAddressbooksToMove('copy') as $bookId => $bookTitle) {
            $bookOptions[$bookId] = array(
                'value' => $bookId,
                'label' => $bookTitle,
                'data-confirm' => __('COPY_SELECTION_TO')
                . ' "' . $bookTitle . '" '
                . __('ADRESSBOOK_ADDRESSES_ACTION_END_TEXT')
            );
        }

        $bookOptions['delete'] = array(
            'value' => 'delete',
            'label' => __('DELETE_SELECTED_ADDRESSES'),
            'data-confirm' => $this->createConfirmMessage($addressBookModel, __('DELETE_SELECTED_ADDRESSES_CONFIRM')),
            'data-translation-id' => 'DELETE_SELECTED_ADDRESSES',
            'data-translation-target' => 'ADDRESSES_GROUP_ACTIONS',
        );

        $bookOptions['copy'] = array(
            'value' => 'copy',
            'label' => __('COPY_SELECTED_ADDRESSES'),
            'data-confirm' => __('COPY_SELECTED_ADDRESSES_CONFIRM'),
            'data-translation-id' => 'COPY_SELECTED_ADDRESSES',
            'data-translation-target' => 'ADDRESSES_GROUP_ACTIONS',
        );

        $bookOptions['CSV-Export'] = array(
            'value' => 'csvExport',
            'label' => __('CSV_EXPORT_SELECTED_ADDRESSES'),
            'data-confirm' => __('CSV_EXPORT_SELECTED_ADDRESSES_CONFIRM'),
            'data-translation-id' => 'CSV_EXPORT_SELECTED_ADDRESSES',
            'data-translation-target' => 'ADDRESSES_GROUP_ACTIONS',
        );
        foreach ($this->getAddressbooksToMove() as $bookId => $bookTitle) {
            $bookOptions[$bookId] = array('value' => $bookId,
                'label' => $bookTitle,
                'data-confirm' => $this->createConfirmMessage($addressBookModel, __('MOVE_SELECTION_TO')
                        . ' "' . $bookTitle . '" '
                        . __('ADRESSBOOK_ADDRESSES_ACTION_END_TEXT'))
            );
        }

        return $bookOptions;
    }

    public function actionAjaxCreateDeleteMessage()
    {
        $addressBookModel = Addressbook::model()->findByPk($_REQUEST['addressBookId']);
        $message = $this->createConfirmMessage($addressBookModel, $_REQUEST['message']);
        echo $message;
        Yii::app()->end();
    }
    
    private function createConfirmMessage($addressBookModel, $message)
    {
        $attributes = array(
            'addressBookId' => $addressBookModel->id,
            'provider' => 'iCloud'
        );
        if ((int) $addressBookModel->type === AddressbookType::personal) {
            $attributes['owner'] = $this->getCurrentUser()->id;
        }
        $connectedAccounts = ThirdPartyCredential::model()->countAllByAttributes($attributes);
        if ($connectedAccounts > 0) {
            $message = "<div id='connected-account-warning'class='alert alert-danger'>"
                    . __('ADRESSBOOK_ADDRESSES_MODEL_WARNING_ICLOUD_CONNECTED')
                    . $message
                    . "</div>";
        }

        return $message;
    }

    public function getGroupActionListData()
    {

        if ($this->getCurrentBook()->type == AddressbookType::intern) {
            $options = array(__('ADDRESSES_GROUP_ACTIONS_EXPORT_TITLE') => array(
                    'CSV-Export' => 'CSV-Export',
                    __('ADDRESSES_GROUP_ACTIONS_COPY_TO_TITLE') => $this->getAddressbooksToMove('copy'),
                ),
            );
            return $options;
        }
        if (count($this->getAddressbooksToMove()) >= 1) {
            $options = array(
                __('ADDRESSES_GROUP_ACTIONS_DELETE_OR_COPY_TITLE') => array(
                    'delete' => __('DELETE_SELECTED_ADDRESSES'),
                    'copy' => __('COPY_SELECTED_ADDRESSES')
                ),
                __('ADDRESSES_GROUP_ACTIONS_EXPORT_TITLE') => array(
                    'CSV-Export' => __('ADDRESSES_GROUP_ACTIONS_EXPORT_TITLE'),
                ),
                __('ADDRESSES_GROUP_ACTIONS_COPY_TO_TITLE') => $this->getAddressbooksToMove('copy'),
                __('ADDRESSES_GROUP_ACTIONS_MOVE_TO_TITLE') => $this->getAddressbooksToMove(),
            );
        } else {

            $options = array(
                __('ADDRESSES_GROUP_ACTIONS_DELETE_OR_COPY_TITLE') => array(
                    'delete' => __('DELETE_SELECTED_ADDRESSES'),
                    'copy' => __('COPY_SELECTED_ADDRESSES')
                ),
                __('ADDRESSES_GROUP_ACTIONS_EXPORT_TITLE') => array(
                    'CSV-Export' => __('ADDRESSES_GROUP_ACTIONS_EXPORT_TITLE'),
                ),
            );
        }
        return $options;
    }

    public function multiActions($models)
    {

        $startTime = time();
        switch ($_POST['function']) {
            case 'delete':
                $this->multiDelete($models, $startTime);
                break;
            case 'copy':
                if (!isset($_POST['id'])) {
                    // exeption
                }

                $this->multiCopyModel($models, $startTime, $_REQUEST['id']);
                break;
            case array_key_exists($_POST['function'], $this->getCurrentUser()->getAddressbooks()):
                $this->moveAddressbook($models, $_POST['function'], $startTime);
                break;
            case strpos($_POST['function'], 'move'):
                $tid = str_replace('move', '', $_POST['function']);
                $this->moveToAddressbook($models, $tid, $startTime);
                break;
        }

        if (!isset($_GET['ajax'])) {
            //$bookId = $this->getBookId();
            //$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('default/admin/id/'.$bookId));
        }
    }

    public function moveToAddressbook($models, $tid, $startTime)
    {
        $addrbooks = $this->getCurrentUser()->getAddressBooks();
        foreach ($models as $model) {
            if ($model->contact_created <= $startTime || $model->contact_created == '') {
                $model->contact_tid = $tid;
                if ($addrbooks[$tid]->type == AddressbookType::personal) {
                    $model->contact_owner = $this->getCurrentUser();
                }
                $model->save();
            }
        }
        $this->initiateSyncForEachContactList($tid);
    }

    public function moveAddressbook($models, $target, $startTime)
    {
        $addrbooks = $this->getCurrentUser()->getAddressBooks();

        foreach ($models as $model) {
            if ($model->contact_created <= $startTime) {


                $newAttributes = array();
                $newAttributes['contact_jpegphoto'] = $model->contact_jpegphoto;
                $newAttributes['contact_tid'] = $target;

                if ($addrbooks[$target]->type == AddressbookType::personal) {

                    $newAttributes['contact_owner'] = $this->getCurrentUser()->id;
                }

                $model->createCopy($newAttributes);
            }
        }
        $this->initiateSyncForEachContactList($target);
    }

    public function multiDelete($models, $startTime)
    {

        foreach ($models as $model) {
            if ($model != null) {
                if ($model->contact_created <= $startTime) {
                    $model->delete();
                }
            }
        }
    }

    public function multiCopyModel($models, $startTime, $target)
    {
        $addrbooks = $this->getCurrentUser()->getAddressBooks();

        if (!isset($target)) {
            $target = $this->id; // WTF ??? $this->id === controller id
        }


        foreach ($models as $model) {
            if ($model->contact_created <= $startTime) {

                $newAttributes = array();
                $newAttributes['contact_jpegphoto'] = $model->contact_jpegphoto;

                if ($addrbooks[$target]->type == AddressbookType::personal) {
                    $newAttributes['contact_owner'] = $this->getCurrentUser()->id;
                }

                $model->createCopy($newAttributes);
            }
        }
    }

    public function actionCsvExport($models, $startTime, $limit = 100, $offset = 0)
    {
        $tmpPath = tempPath('csv'); //Yii::app()->basePath."/TmpTest/";
        $filname = Yii::app()->user->sudoUser . "csvTmp" . $startTime . ".csv";
        $data = $this->getCsvData($models);

        //FIXME set this in config ?
        $cut = ";";

        if ($offset == 0) {
            if (count($models)) {
                $header = $this->getAddressesCsvHeader($models[0]);
            } else {
                $header = $this->getAddressesCsvHeader(new Addresses());
            }
            $handle = fopen($tmpPath . $filname, "w");

            fputcsv($handle, $header, $cut);
            fclose($handle);
            $handle = fopen($tmpPath . $filname, "a");
            foreach ($data as $fields) {

                fputcsv($handle, $fields, $cut);
            }
            fclose($handle);
        } else {
            $handle = fopen($tmpPath . $filname, "a");
            foreach ($data as $fields) {
                fputcsv($handle, $fields, $cut);
            }
            fclose($handle);
        }
    }

    public function getAddressesCsvHeader($model, $cut = ";")
    {
        $header = array();
        $csvRelevantAttributes = Addresses::csvRelevantAttributes();
        foreach ($model->attributes as $attribute => $value) {
            if (!array_key_exists($attribute, $csvRelevantAttributes)) {
                continue;
            }
            $header[] = $attribute;
        }
        return $header;
    }

    public function importCustomValue(&$value, $exportOptions)
    {

        if (isset($exportOptions['model'])) {
            $model = $exportOptions['model']::model()->findByPk($value);
            if ($model && isset($exportOptions['value'])) {
                $value = $model->{$exportOptions['value']};
            }
        }
    }

    public function getCsvData($models, $cut = ";")
    {

        $data = array();
        $csvRelevantAttributes = Addresses::csvRelevantAttributes();
        foreach ($models as $model) {
            $subdata = array();
            foreach ($model->attributes as $attribute => $value) {
                if (!array_key_exists($attribute, $csvRelevantAttributes)) {
                    continue;
                } elseif (isset($csvRelevantAttributes[$attribute]['relation'])) {
                    $this->importCustomValue($value, $csvRelevantAttributes[$attribute]['relation']);
                }
                $value = str_replace(";", '', $value); // HOTFIX !
                $value = str_replace("\n", '\n', $value);
                $value = str_replace("\r\n", '\r\n', $value);
                $value = str_replace("\"", '\'', $value);

                $datavalue = $value;
                $subdata[] = $datavalue;
            }
            $data[] = $subdata;
        }

        return $data;
    }

    public function actionDownloadCsv($startTime = "")
    {

        if (isset($_GET["startTime"])) {
            $startTime = $_GET["startTime"];
        }

        $tmpPath = tempPath('csv'); //Yii::app()->basePath."/TmpTest/";
        // CSV hotfix
        $filname = Yii::app()->user->sudoUser . "csvTmp" . ($startTime + 0) . ".csv"; // +20 ??
        $this->renderPartial(
                'csvExport', array(
            'startTime' => $startTime,
            'filname' => $filname,
            'tmpPath' => $tmpPath
                )
        );
    }

    public function checkIfAddressBookIsPrivate()
    {
        $result = false;
        $book = Addressbook::model()->findByPk($this->getBookId());
        if ($book->type == AddressbookType::personal) {
            $result = true;
        }
        return $result;
    }

    public function actionClearTmp()
    {
        $tmpPath = tempPath('csv'); //Yii::app()->getRuntimePath()."/csv/";//Yii::app()->basePath."/TmpTest/";
        $filname = Yii::app()->user->sudoUser . "csvTmp" . $_GET['startTime'] . ".csv";
        unlink($tmpPath . $filname);
        //$this->actionAdmin();
        $this->redirect(array('admin', 'id' => $_GET['id']));
    }

    public function renderBDayPicker($model, $form)
    {
        $this->renderPartial('bDayPicker', array('model' => $model, 'form' => $form));
    }

    public function actionGetJsonAddress($addressId, $bookId)
    {
        $model = Addresses::model()->findByPk($addressId);
        if (!$model->isICloudImported() && isset($model->contact_bday)) {
            $model->contact_bday = PhonalisaDate::userDate($model->contact_bday);
        }
        if ($model == null) {
            $book = Addressbook::model()->findByPk($bookId);

            if ($book->type == AddressbookType::personal) {
                $model = Addresses::model()->find(
                        array(
                    'contact_tid' => $bookId,
                    'contact_owner' => app()->user->sudoUser
                        ), 'n_given', 1 //limit
                );
            } else {
                $model = Addresses::model()->find(array('contact_tid' => $bookId), 'n_given', 1);
            }
            if (!empty($model)) {
                $model = $model[0];
            } else {
                $model = new Addresses();
                $model->contact_owner = Yii::app()->user->sudoUser;
                $model->contact_tid = $bookId;
                // 		throw new Exception('Address not found');
            }
        }

        header('Content-Type: application/json');
        echo CJSON::encode($model->getAttributes());
    }

    public function actionManageAddress()
    {
        $model = new Addresses();
        $model->contact_owner = Yii::app()->user->sudoUser;
        $this->performAjaxValidation($model);

        if (isset($_POST['Addresses'])) {
            if (isset($_POST['Addresses']['id']) && $_POST['Addresses']['id'] != '') {
                $model = $this->loadModel($_POST['Addresses']['id']);
            }


            $this->actionSaveInputData($model);

            $this->formatModelBDayToUserFormat($model);
//            if ($this->actionSaveInputData($model) === true) {
            header('Content-Type: application/json');
            echo CJSON::encode($model->getAttributes());
//            } else {
//                header('Content-Type: application/json');
//                echo CJSON::encode($model->getAttributes());
//            }
        }
    }

    public function actionCanonizeNumber()
    {
        if (!isset($_REQUEST['number'])) {
            Yii::app()->end();
        }

        $number = $_REQUEST['number'];

        $newNumber = NumberCanonizer::canonize($number);
        header('Content-Type: application/json');
        echo CJSON::encode($newNumber);
        Yii::app()->end();
    }

    public function getAddressBookList()
    {
        $userBooks = app()->user->sudoUserInstance->getAddressbooks();

        $list = array();

        foreach ($userBooks as $book) {
            $menuItem = array(
                'label' => $book->title,
                'url' => url('addressbookAddresses/default/index', array('id' => $book->id)),
            );
            $list[$book->id] = $menuItem;
        }
        // Sort all addressbooks alphabetically
        uasort($list, function ($a, $b) {
            return strnatcmp(strtolower($a['label']), strtolower($b['label']));
        });

        return $list;
    }

    public function lastContactDataProvider($contactId)
    {
        if (!isset($_REQUEST['ajax'])) {
            return new CArrayDataProvider(array(), array(
                'sort' => array(
                    'attributes' => array('typ', 'timestamp', 'note'),
                ),
            ));
        }

        $user = app()->user->sudoUserInstance;

        $condition = 'caller_addressbook_id=' . $contactId;
        $condition .= ' AND owner_id=' . $user->id;

        foreach ($user->getUserGroupIds() as $groupId) {
            $condition .= '|' . $groupId;
        }

        $options = array(
            'criteria' => array(
                'condition' => $condition,
                'order' => 'timestamp DESC',
            )
        );

        $dataProvider = new CPhonalisaDataProvider('UCItem', $options);

        //HotFix FIXME : fix for getting Item Count to make Pagination work ...
        $condition = '';
        foreach ($user->getUserGroupIds() as $groupId) {
            $condition .= '|' . $groupId;
        }
        $dataProvider->totalItemCount = count(
                UCItem::model()->find(
                        array(
                    'caller_addressbook_id' => $contactId,
                    'owner_id' => $user->id . $condition,
                        ), 'timestamp DESC'
                )
        );
        // HotFix end;

        return $dataProvider;
    }

    public function actionLastContact($id)
    {
        $this->renderPartial('lastContact', array(
            'dataProvider' => $this->lastContactDataProvider($id),
        ));
        //die($id);
    }

    public function renderHistoryTypeCell($data, $row)
    {
        return $this->renderPartial('historyTypeCell', array('model' => $data), true, false);
    }

    public function renderHistorySummaryCell($data, $row)
    {
        return $this->renderPartial('historySummaryCell', array('model' => $data), true, false);
    }

    public function getRingtoneData($userId)
    {
        $stdRingtones = array(
            '' => __('DEFAULT_ADRESSBOOK_RINGTONE'),
            'ringtone-1' => __('BELLCORE') . ' 1',
            'ringtone-2' => __('BELLCORE') . ' 2',
            'ringtone-3' => __('BELLCORE') . ' 3',
            'ringtone-4' => __('BELLCORE') . ' 4',
            'ringtone-5' => __('BELLCORE') . ' 5',
            'ringtone-6' => __('BELLCORE') . ' 6',
            'ringtone-7' => __('BELLCORE') . ' 7',
            'ringtone-8' => __('BELLCORE') . ' 8',
            'ringtone-9' => __('BELLCORE') . ' 9',
            'ringtone-10' => __('BELLCORE') . ' 10',
            'mute' => __('BELLCORE_MUTE'),
        );

        $ringtoneData = Ringtone::model()->findAllByAttributes(
                array('userId' => $userId)
        );
        $userRingtones = CHtml::listData($ringtoneData, 'id', 'fileName');

        $availableRingTones = array(__('CHOOSE_BELLCHOR') => array_merge($stdRingtones, $userRingtones));

        return $availableRingTones;
    }

    public function getAddressBookListMobile($model)
    {
        $items = $this->getAddressBookList();
        $html = '';
        foreach ($items as $id => $item) {
            $url = url('addressbookAddresses/default/addressList', array('id' => $id));
            $html.="<li><a rel='external' href='$url'>";
            $html.=$item['label'];
            $html.="<span class='ui-li-count'>" . $model->search($id)->totalItemCount . "</span>";
            $html.="</a></li>";
        }
        return $html;
    }

    public function actionAddressList()
    {
        $items = array();
        if ($_REQUEST['id']) {
            if (Yii::app()->detectMobileBrowser->showMobile) {
                return $this->renderInfiniteAddressesScroll($_REQUEST['id']);
            }
            $dataProvider = Addresses::model()->search($_REQUEST['id']);
            if ($dataProvider) {
                $items = $dataProvider->data;
            }
        }
        $this->render('addressList', array('items' => $items));
    }

    public function renderInfiniteAddressesScroll($addressBookID)
    {
        $model = new Addresses();
        $total = Addresses::model()->countAllByAttributes(array('contact_tid' => $addressBookID));
        $pages = new CPagination($total);
        $pages->pageSize = 20;

        $condition['contact_tid'] = $addressBookID;
        $items = Addresses::model()->find($condition, 'n_family', $pages->limit, $pages->offset);
        $this->render('addressList', array(
            'items' => $items,
            'pages' => $pages,
            'model' => $model
        ));
    }

    public function getAddressListMobile($items)
    {
        $html = '';
        foreach ($items as $item) {
            $imageURL = $item->getPhotoUrl(80);
            $contactName = "$item->n_prefix $item->n_family, $item->n_given";
            $company = $item->org_name;
            $url = url('addressbookAddresses/default/view', array('id' => $item->id));
            $html.="<li class='ucItem ui-li-has-thumb'><a class='ui-btn ui-btn-icon-right ui-icon-carat-r' href='$url'>";
            $html.="<img src='$imageURL'>";
            $html.="<h2>$contactName</h2>";
            $html.="<p class='addressKey'>$company</p>";
            $html.="</a></li>";
        }
        return $html;
    }

    public function actionView()
    {
        $model = array();
        $imageURL = '';
        $company = '';
        $contactName = '';

        if (isset($_REQUEST['id'])) {
            $model = Addresses::model()->findByPk($_REQUEST['id']);
            $imageURL = $model->getPhotoUrl(80);
            $contactName = "$model->n_prefix $model->n_family, $model->n_given";
            $company = $model->org_name;
        }

        $this->render('view', array(
            'model' => $model,
            'imageURL' => $imageURL,
            'company' => $company,
            'contactName' => $contactName
        ));
    }
}

if (!function_exists('getallheaders')) {

    function getallheaders()
    {
        $headers = '';
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}
