Exemple #1
0
 public function testAfterDelete()
 {
     $user = User::model()->findByPk('2');
     if (X2_TEST_DEBUG_LEVEL > 1) {
         /**/
         print 'id of user to delete: ';
         /**/
         print $user->id;
     }
     // test calendar permissions deletion
     $this->assertNotEquals(0, sizeof(X2CalendarPermissions::model()->findAllByAttributes(array('user_id' => $user->id))));
     $this->assertNotEquals(0, sizeof(X2CalendarPermissions::model()->findAllByAttributes(array('other_user_id' => $user->id))));
     // assert that group to user records exist for this user
     $this->assertTrue(sizeof(GroupToUser::model()->findAllByAttributes(array('userId' => $user->id))) > 0);
     $this->assertTrue($user->delete());
     X2_TEST_DEBUG_LEVEL > 1 && (print 'looking for groupToUser records with userId = ' . $user->id);
     GroupToUser::model()->refresh();
     // assert that group to user records were deleted
     $this->assertTrue(sizeof(GroupToUser::model()->findAllByAttributes(array('userId' => $user->id))) === 0);
     // test profile deletion
     $this->assertTrue(sizeof(Profile::model()->findAllByAttributes(array('username' => $user->username))) === 0);
     // test social deletion
     $this->assertTrue(sizeof(Social::model()->findAllByAttributes(array('user' => $user->username))) === 0);
     $this->assertTrue(sizeof(Social::model()->findAllByAttributes(array('associationId' => $user->id))) === 0);
     // test event deletion
     $this->assertTrue(sizeof(Events::model()->findAll("user=:username OR (type='feed' AND associationId=" . $user->id . ")", array(':username' => $user->username))) === 0);
     // test calendar permissions deletion
     $this->assertEquals(0, sizeof(X2CalendarPermissions::model()->findAllByAttributes(array('user_id' => $user->id))));
     $this->assertEquals(0, sizeof(X2CalendarPermissions::model()->findAllByAttributes(array('other_user_id' => $user->id))));
 }
 /**
  * Displays a particular model.
  * @param integer $id the ID of the model to be displayed
  */
 public function actionView($id)
 {
     $category = explode('_', $id);
     $category = $this->loadModel($category[0]);
     $events = array();
     $dates = Dates::model()->findAllByAttributes(array('status_date' => 1), array('order' => 't.date_date ASC'));
     foreach ($dates as $key => $date) {
         $eventsDate = Events::model()->findAllByAttributes(array('dates_id_date' => $date->id_date, 'status_event' => 1, 'great_event' => 1, 'event_categories_id_category' => $category->id_category), array('order' => 't.hour_event ASC'));
         $events = array_merge($events, $eventsDate);
     }
     if (isset($_GET['event'])) {
         $event = Events::model()->findByAttributes(array('status_event' => 1, 'great_event' => 1, 'event_categories_id_category' => $category->id_category, 'id_event' => $_GET['event']));
         if ($event == null) {
             throw new CHttpException(404, 'The requested page does not exist.');
         }
     } else {
         if (isset($events[0])) {
             $event = $events[0];
             $this->pageTitle = 'Eventos ' . $category->name_category . ' - ' . $this->pageTitle;
             $this->pageDescription = 'Los esperamos sin falta en nuestros eventos religiosos, teatro, danza, noches de música, cabalgata, carrozas y comparsas, deportes extremos y actividades para toda la familia.';
             $this->tagImage = '/images/events/' . $event->image_event;
         } else {
             $event = null;
         }
     }
     $this->render('view', array('category' => $category, 'events' => $events, 'event' => $event));
 }
 public function afterDelete()
 {
     parent::afterDelete();
     if ($this->countByAttributes(['event_id' => $this->event_id]) == 0) {
         Events::model()->deleteByPk($this->event_id);
     }
 }
 /**
  * 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 = Events::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
Exemple #5
0
function getCalendarByRange($id)
{
    try {
        $event = Events::model()->findByPk($id);
    } catch (Exception $e) {
    }
    return $event;
}
 public function actionIndex()
 {
     if (Yii::app()->request->isAjaxRequest) {
         header('Content-Type: application/json');
         echo CJSON::encode(array('success' => true, 'msg' => ProjectMessages::model()->findByPk(Events::model()->findByPk(Yii::app()->request->getParam('id'))->event_id)->message));
         Yii::app()->end();
     }
     $events = Events::model()->findAll(array('condition' => '', 'order' => 'timestamp DESC'));
     $this->render('index', array('events' => $events));
 }
Exemple #7
0
 public function actionGetEventByUser()
 {
     $request = Yii::app()->request;
     try {
         $user_id = StringHelper::filterString($request->getQuery('user_id'));
         $limit = StringHelper::filterString($request->getQuery('limit'));
         $offset = StringHelper::filterString($request->getQuery('offset'));
         $data = Events::model()->getEventByUser($user_id, $limit, $offset);
         ResponseHelper::JsonReturnSuccess($data, 'Success');
     } catch (Exception $ex) {
         var_dump($ex->getMessage());
     }
 }
 public function actionEventos()
 {
     $this->pageTitle = 'Eventos - ' . $this->pageTitle;
     $this->pageDescription = 'Los esperamos sin falta en nuestros eventos religiosos, teatro, danza, noches de música, cabalgata, carrozas y comparsas, deportes extremos y actividades para toda la familia.';
     $this->tagImage = '/images/facebook-eventos.png';
     $categories = array();
     $categoriesDb = EventCategories::model()->findAllByAttributes(array('status_category' => 1));
     foreach ($categoriesDb as $key => $category) {
         $events = Events::model()->findAllByAttributes(array('status_event' => 1, 'great_event' => 1, 'event_categories_id_category' => $category->id_category), array('order' => 't.id_event ASC', 'limit' => 3));
         if ($events != null) {
             $categories[] = array('events' => $events, 'category' => $category);
         }
     }
     $this->render('eventos', array('categories' => $categories));
 }
 public function actionDelete()
 {
     $id = Yii::app()->request->getParam('id');
     if (Yii::app()->request->isAjaxRequest) {
         header('Content-Type: application/json');
         if (Events::model()->deleteByPk($id)) {
             echo CJSON::encode(array('success' => true));
         } else {
             echo CJSON::encode(array('error' => true));
         }
         Yii::app()->end();
     }
     $events = Events::model()->findAll(array('condition' => '', 'order' => 'timestamp DESC'));
     $this->render('index', array('events' => $events));
 }
 /**
  * Displays a particular model.
  * @param integer $id the ID of the model to be displayed
  */
 public function actionEvent($id)
 {
     if (Yii::app()->request->isAjaxRequest) {
         $event = Events::model()->findByAttributes(array('id_event' => $id, 'status_event' => 1));
         if ($event != null) {
             $days = array('Monday' => 'Lunes', 'Tuesday' => 'Martes', 'Wednesday' => 'Miercoles', 'Thursday' => 'Jueves', 'Friday' => 'Viernes', 'Saturday' => 'Sabado', 'Sunday' => 'Domingo');
             $hour = new DateTime($event->hour_event);
             $date = new DateTime($event->datesIdDate->date_date);
             $event->hour_event = $hour->format('g:i A');
             $event->datesIdDate->date_date = $days[$date->format('l')] . ' ' . intval($date->format('d'));
             echo CJSON::encode(array("title" => MyMethods::myStrtoupper($event->title_event), "image" => Yii::app()->request->baseUrl . '/images/events/' . $event->image_event, "place" => MyMethods::myStrtoupper($event->placesIdPlace->name_place), "hour" => $event->datesIdDate->date_date . ' - ' . $event->hour_event, "description" => $event->description_event));
         } else {
             throw new CHttpException(404, 'The requested page does not exist.');
         }
     } else {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
 }
 public function run($args)
 {
     $companies = Company::model()->findAll('frozen=:p', array(':p' => '0'));
     foreach ($companies as $company) {
         Company::setActive($company);
         Yii::app()->language = Company::getLanguage();
         User::model()->refreshMetaData();
         AuthAssignment::model()->refreshMetaData();
         ProfileField::model()->refreshMetaData();
         Profile::model()->refreshMetaData();
         Zakaz::model()->refreshMetaData();
         ZakazParts::model()->refreshMetaData();
         Events::model()->refreshMetaData();
         Templates::model()->refreshMetaData();
         Emails::model()->refreshMetaData();
         self::executor();
         self::manager();
         self::send_deffered_emails();
     }
 }
Exemple #12
0
 public function getEventByUser($user_id, $limit, $offset)
 {
     $criteria = new CDbCriteria();
     $criteria->condition = "created_by = {$user_id}";
     $criteria->limit = $limit;
     $criteria->offset = $offset;
     $result = Events::model()->findAll($criteria);
     $returnArr = array();
     foreach ($result as $item) {
         $itemArr['name'] = $item->name;
         $itemArr['images'] = $item->images;
         $itemArr['description'] = $item->description;
         $itemArr['status'] = $item->status;
         $itemArr['date'] = $item->date;
         $itemArr['address'] = $item->address;
         $itemArr['type'] = $item->type;
         $returnArr[] = $itemArr;
     }
     return $returnArr;
 }
Exemple #13
0
function removeCalendar($id)
{
    $ret = array();
    try {
        $event = Events::model()->findByPk($id);
        $event->delete();
        if ($event->save() == false) {
            $ret['IsSuccess'] = false;
            $ret['Msg'] = $event->error();
        } else {
            $ret['IsSuccess'] = true;
            $ret['Msg'] = 'Succefully';
        }
    } catch (Exception $e) {
        $ret['IsSuccess'] = false;
        $ret['Msg'] = $e->getMessage();
    }
    return $ret;
}
 /**
  *  Вывод и добавление сообщений
  */
 public function actionIndex($orderId)
 {
     $isGuest = Yii::app()->user->isGuest;
     Yii::app()->session['project_id'] = $orderId;
     if (Yii::app()->request->isAjaxRequest) {
         if (Yii::app()->request->getPost('ProjectMessages')) {
             $id = (int) $_POST['ProjectMessages']['id'];
             if ($id > 0) {
                 $model = ProjectMessages::model()->findByPk($id);
             } else {
                 $model = new ProjectMessages();
                 $model->sender = Yii::app()->user->id;
                 $model->moderated = 0;
                 $model->order = $orderId;
             }
             $post = $_POST['ProjectMessages']['message'];
             $post = str_replace("\r\n", '<br>', $post);
             $post = str_replace("\n", '<br>', $post);
             $_POST['ProjectMessages']['message'] = $post;
             $model->attributes = Yii::app()->request->getPost('ProjectMessages');
             $model->date = date('Y-m-d H:i:s');
             switch ($model->recipient) {
                 case 'manager':
                     $model->recipient = 1;
                     break;
                 case 'customer':
                     if (User::model()->isCustomer()) {
                         $model->recipient = Zakaz::model()->resetScope()->findByPk($orderId)->attributes['executor'];
                         $type_id = Emails::TYPE_20;
                     } else {
                         if (User::model()->isAuthor()) {
                             $model->recipient = Zakaz::model()->findByPk($orderId)->attributes['user_id'];
                             $type_id = Emails::TYPE_16;
                         }
                     }
                     $user = User::model()->findByPk($model->recipient);
                     $profile = Profile::model()->findAll("`user_id`='{$model->recipient}'");
                     $email = new Emails();
                     $rec = Templates::model()->findAll("`type_id`='{$type_id}'");
                     $title = $rec[0]->title;
                     $body = $rec[0]->text;
                     $email->name = $user->full_name;
                     if (strlen($email->name) < 2) {
                         $email->name = $user->username;
                     }
                     $email->num_order = $orderId;
                     $email->message = $post;
                     $email->page_order = 'http://' . $_SERVER['SERVER_NAME'] . '/project/chat?orderId=' . $orderId;
                     $email->sendTo($user->email, $body, $type_id);
                     break;
             }
             //print_r($model);
             //echo '<br>$model->save()='.$model->save();
             EventHelper::addMessage($orderId, $model->message);
         }
         $this->renderPartial('chat', array('orderId' => $orderId, 'isGuest' => $isGuest));
         Yii::app()->end();
     }
     $order = Zakaz::model()->resetScope()->findByPk($orderId);
     $parts = ZakazParts::model()->findAll(array('condition' => "`proj_id`='{$orderId}'"));
     if ($isGuest) {
         Yii::app()->theme = 'client';
         // если гость прошёл по ссылке на неcуществующий
         // проект, отправляем его на регистрацию
         $url = 'http://' . $_SERVER['SERVER_NAME'] . '/';
         if (!$order) {
             $this->redirect($url);
         }
         $moderate_types = EventHelper::get_moderate_types_string();
         $events = Events::model()->findAll(array('condition' => "`event_id`='{$orderId}' AND `type` in ({$moderate_types})", 'order' => 'timestamp DESC'), array(':event_id' => $orderId));
         $moderated = count($events) == 0;
         // если гость прошёл по ссылке на непромодерированный
         // проект, отправляем его на регистрацию
         if (!$moderated) {
             $this->redirect(Yii::app()->createUrl('user/login'));
         }
         //			Catalog::model()->tableName();
         //$EmptyChat = UserModule::t('EmptyChat');
         $this->render('index', array('orderId' => $orderId, 'order' => $order, 'executor' => Zakaz::getExecutor($orderId), 'moderated' => $moderated, 'isGuest' => $isGuest, 'parts' => $parts));
         Yii::app()->end();
     }
     $moderate_types = EventHelper::get_moderate_types_string();
     $events = Events::model()->findAll(array('condition' => "`event_id`='{$orderId}' AND `type` in ({$moderate_types})", 'order' => 'timestamp DESC'), array(':event_id' => $orderId));
     $moderated = count($events) == 0;
     $this->render('index', array('orderId' => $orderId, 'order' => $order, 'executor' => Zakaz::getExecutor($orderId), 'moderated' => $moderated, 'isGuest' => $isGuest, 'parts' => $parts));
 }
 /**
  * Одобрение или нет заказа
  * @param $answer
  * @author Emericanec
  */
 public function actionModerationAnswer($id, $event_id, $answer)
 {
     $model = Zakaz::model()->resetScope()->findByPk($id);
     $event = Events::model()->findByPk($event_id);
     if (!$model->is_active && $event) {
         if ($answer == 1) {
             $model->is_active = 1;
             if ($model->save()) {
                 $event->delete();
                 // Заказчику проект принят
                 $type_id = Emails::TYPE_12;
                 $email = new Emails();
                 $order = Zakaz::model()->findByPk($id);
                 $user = User::model()->findByPk($order->user_id);
                 $email->from_id = 1;
                 $email->to_id = $user->id;
                 $rec = Templates::model()->findAll("`type_id`='{$type_id}'");
                 $campaign = Campaign::search_by_domain($_SERVER['SERVER_NAME']);
                 $email->campaign = $campaign->name;
                 $email->name = $user->full_name;
                 $email->num_order = $id;
                 $email->page_order = 'http://' . $_SERVER['SERVER_NAME'] . '/project/chat?orderId=' . $id;
                 //$email->login= $user->username;
                 //$email->password= $soucePassword;
                 $email->sendTo($user->email, $rec[0]->title, $rec[0]->text, $type_id);
                 $this->redirect(Yii::app()->createUrl('project/zakaz/update', array('id' => $model->id)));
             }
         } else {
             // если нет то просто удаляем
             $model->delete();
             $event->delete();
             $this->redirect(Yii::app()->createUrl('project/event'));
         }
     } else {
         $event->delete();
         throw new CHttpException("Заказ не найден или его уже отмодерировали");
     }
 }
Exemple #16
0
 /**
  * Attempts to ensure that isVisibleTo and getAccessCriteria check the same permissions
  */
 public function testPermissionsCheckEquivalence()
 {
     TestingAuxLib::loadX2NonWebUser();
     TestingAuxLib::suLogin('testuser2');
     $allEvents = Events::model()->findAll();
     $that = $this;
     $checkEquivalence = function ($events) use($allEvents, $that) {
         $ids = array_map(function ($event) {
             return $event->id;
         }, $events);
         $that->assertTrue(count($events) > 1);
         foreach ($events as $event) {
             $that->assertTrue($event->isVisibleTo(Yii::app()->params->profile->user));
         }
         $found = false;
         foreach ($allEvents as $event) {
             if (!in_array($event->id, $ids)) {
                 $found = true;
                 $that->assertFalse($event->isVisibleTo(Yii::app()->params->profile->user));
             }
         }
         $that->assertTrue($found);
     };
     Yii::app()->settings->historyPrivacy = null;
     $accessCriteria = Events::model()->getAccessCriteria();
     $events = Events::model()->findAll($accessCriteria);
     $checkEquivalence($events);
     Yii::app()->settings->historyPrivacy = 'group';
     $accessCriteria = Events::model()->getAccessCriteria();
     $events = Events::model()->findAll($accessCriteria);
     $checkEquivalence($events);
     Yii::app()->settings->historyPrivacy = 'user';
     $accessCriteria = Events::model()->getAccessCriteria();
     $events = Events::model()->findAll($accessCriteria);
     $checkEquivalence($events);
 }
Exemple #17
0
 /**
  * Deletes an action
  * @param integer $id The id of the action
  */
 public function actionDelete($id)
 {
     $model = $this->loadModel($id);
     if (Yii::app()->request->isPostRequest) {
         // $this->cleanUpTags($model);	// now in TagBehavior
         $event = new Events();
         $event->type = 'record_deleted';
         $event->associationType = $this->modelClass;
         $event->associationId = $model->id;
         $event->text = $model->name;
         $event->visibility = $model->visibility;
         $event->user = Yii::app()->user->getName();
         $event->save();
         Events::model()->deleteAllByAttributes(array('associationType' => 'Actions', 'associationId' => $id, 'type' => 'action_reminder'));
         $model->syncGoogleCalendar('delete');
         /* if(!is_numeric($model->assignedTo)) { // assigned to user
            $profile = Profile::model()->findByAttributes(array('username'=>$model->assignedTo));
            if(isset($profile))
            $profile->deleteGoogleCalendarEvent($model); // update action in Google Calendar if user has a Google Calendar
            } else { // Assigned to group
            $groups = Yii::app()->db->createCommand()->select('userId')->from('x2_group_to_user')->where("groupId={$model->assignedTo}")->queryAll();
            foreach($groups as $group) {
            $profile = Profile::model()->findByPk($group['userId']);
            if(isset($profile))
            $profile->deleteGoogleCalendarEvent($model);
            } */
         $model->delete();
     } else {
         throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
     }
     // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
     if (!isset($_GET['ajax']) && !Yii::app()->request->isAjaxRequest) {
         $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
     } else {
         if (!isset($_POST['gvSelection'])) {
             echo 'success';
         }
     }
 }
 private function getSliceData($date_start, $date_end)
 {
     $looms = array();
     $ls = Loominfo::model()->findAll();
     for ($i = 0; $i < count($ls); $i++) {
         $l = $ls[$i];
         $looms[$l->frepeaterid][$l->flcardid] = array('name' => $l->floomname, 'fid' => $l->fid);
     }
     $c = new CDbCriteria();
     $c->select = 'frepeatid, flcardid, SUM(fwbrknum) as swb, SUM(fsbrknum) as ssb, SUM(fobrknum) as sob, SUM(frpmnum) as srp, SUM(ftbrknum) as stb';
     $c->condition = "ftimestamp>:date_start and ftimestamp<:date_end";
     $c->group = 'frepeatid, flcardid';
     $c->params = array(':date_start' => $date_start, ':date_end' => $date_end);
     $results = Hourdata::model()->findAll($c);
     // $sql = "select frepeatid, flcardid, SUM(fwbrknum) as swb, SUM(fsbrknum) as ssb, SUM(fobrknum) as sob, SUM(frpmnum) as srp, SUM(ftbrknum) as stb
     //         from {{hourdata}}
     //         group by frepeatid, flcardid";
     //where ftimestamp>:date_start and ftimestamp<:date_end
     //echo $sql;
     //$cmd = $db->createCommand($sql);
     //$cmd->bindValue(':date_start', $date_start);
     //$cmd->bindValue(':date_end', $date_end);
     // $results = array();
     // $results = $cmd->queryAll();
     $sums = array();
     $n = count($results);
     for ($i = 0; $i < $n; $i++) {
         $r = $results[$i];
         $card_id = $r['flcardid'];
         $repeat_id = $r['frepeatid'];
         if (!isset($sums[$repeat_id])) {
             $sums[$repeat_id] = array();
         }
         $sums[$repeat_id][$card_id] = array('swb' => $r['swb'], 'ssb' => $r['ssb'], 'sob' => $r['sob'], 'srp' => $r['srp'], 'stb' => $r['stb']);
     }
     //print_r($sums);
     $criteria = new CDbCriteria();
     $criteria->condition = "ftimestamp>:date_start and ftimestamp<:date_end and fstatus=1";
     $criteria->group = "ftimestamp";
     $criteria->order = "frepeatid,flcardid,ftimestamp";
     $criteria->params = array(':date_start' => $date_start, ':date_end' => $date_end);
     $results = Events::model()->findAll($criteria);
     //
     $time_slice = array();
     $card_info = array();
     $run_begin_time = 0;
     $run_end_time = 0;
     $last_event = -1;
     $begin_timestamp = 0;
     //$last_r = array();
     foreach ($results as $result) {
         $card_id = $result['flcardid'];
         $repeat_id = $result['frepeatid'];
         if (!isset($time_slice[$card_id])) {
             $name = "[{$repeat_id}][{$card_id}]";
             //$looms[$repeat_id][$card_id];
             if (isset($looms[$repeat_id][$card_id])) {
                 $name = $looms[$repeat_id][$card_id]['name'];
                 $loom_id = $looms[$repeat_id][$card_id]['fid'];
             }
             $time_slice[$card_id] = array('loomid' => $loom_id, 'name' => $name, 'max_ts' => 0, 'min_ts' => 0, 'max_fwbrknum' => 0, 'min_fwbrknum' => $result['fwbrknum'], 'max_ftbrknum' => 0, 'min_ftbrknum' => $result['ftbrknum'], 'max_fsbrknum' => 0, 'min_fsbrknum' => $result['fsbrknum'], 'max_fobrknum' => 0, 'min_fobrknum' => $result['fobrknum']);
             $card_info =& $time_slice[$card_id];
             $last_event = -1;
             $begin_timestamp = 0;
             if (isset($sums[$repeat_id][$card_id])) {
                 $card_info['wbrknum'] = $sums[$repeat_id][$card_id]['swb'];
                 //$slice['max_fwbrknum'] - $slice['min_fwbrknum'];
                 $card_info['sbrknum'] = $sums[$repeat_id][$card_id]['ssb'];
                 //$slice['max_fsbrknum'] - $slice['min_fsbrknum'];
                 $card_info['tbrknum'] = $sums[$repeat_id][$card_id]['stb'];
                 //$slice['max_ftbrknum'] - $slice['min_ftbrknum'];
                 $card_info['obrknum'] = $sums[$repeat_id][$card_id]['sob'];
                 //$slice['max_fobrknum'] - $slice['min_fobrknum'];
                 $card_info['srpnum'] = $sums[$repeat_id][$card_id]['srp'];
                 //$slice['max_fobrknum'] - $slice['min_fobrknum'];
             } else {
                 $card_info['wbrknum'] = 0;
                 $card_info['sbrknum'] = 0;
                 $card_info['tbrknum'] = 0;
                 $card_info['obrknum'] = 0;
                 $card_info['srpnum'] = 0;
             }
             // if ($last_r) {
             //     $l_card_id = $last_r['flcardid'];
             //     $time_slice[$l_card_id]['max_fwbrknum']= $last_r['fwbrknum'];
             //     $time_slice[$l_card_id]['max_ftbrknum']= $last_r['ftbrknum'];
             //     $time_slice[$l_card_id]['max_fsbrknum']= $last_r['fsbrknum'];
             //     $time_slice[$l_card_id]['max_fobrknum']= $last_r['fobrknum'];
             // }
         }
         $event_id = $result['feventid'];
         //$event_fields = array(8=>'wbrknum', 2=>'sbrknum', 1=>'tbrknum', 4=>'obrknum');
         if (!isset($card_info[$event_id])) {
             $card_info[$event_id] = array('time_len' => 0, 'num' => 0);
         }
         $card_info[$event_id]['num']++;
         //
         $card_info['max_ts'] = max($card_info['max_ts'], $result['ftimestamp']);
         if ($card_info['min_ts'] == 0) {
             $card_info['min_ts'] = $result['ftimestamp'];
         } else {
             $card_info['min_ts'] = min($card_info['min_ts'], $result['ftimestamp']);
         }
         //
         if ($last_event != $event_id) {
             if ($last_event != -1) {
                 $card_info[$last_event]['time_len'] += $result['ftimestamp'] - $begin_timestamp;
             }
             $begin_timestamp = $result['ftimestamp'];
             $last_event = $event_id;
         }
         //$last_r = $result;
     }
     return $time_slice;
 }
 /**
  *  Вывод и добавление сообщений
  */
 public function actionIndex($orderId, $role = null)
 {
     $isCorrector = $role == 'Corrector' ? 1 : 0;
     $isGuest = Yii::app()->user->isGuest;
     if ($isGuest) {
         $url = 'http://' . $_SERVER['SERVER_NAME'] . '/user/login';
         $this->redirect($url);
     }
     Yii::app()->session['project_id'] = $orderId;
     $order = Zakaz::model()->resetScope()->findByPk($orderId);
     if (Yii::app()->request->isAjaxRequest) {
         if (Yii::app()->request->getPost('ProjectMessages')) {
             $id = (int) $_POST['ProjectMessages']['id'];
             if ($id > 0) {
                 // редактирование сообщения
                 $model = ProjectMessages::model()->findByPk($id);
             } else {
                 // новое сообщение
                 $model = new ProjectMessages();
                 $model->sender = Yii::app()->user->id;
                 $model->moderated = 0;
                 $model->order = $orderId;
             }
             $post = $_POST['ProjectMessages']['message'];
             $post = str_replace("\r\n", '<br>', $post);
             $post = str_replace("\n", '<br>', $post);
             $_POST['ProjectMessages']['message'] = $post;
             $model->attributes = Yii::app()->request->getPost('ProjectMessages');
             $model->date = date('Y-m-d H:i:s');
             switch ($model->recipient) {
                 case 'author_to_manager':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Author');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Admin');
                     $model->recipient = 1;
                     break;
                 case 'customer_to_manager':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Customer');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Admin');
                     $model->recipient = 1;
                     break;
                 case 'corrector_to_manager':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Corrector');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Admin');
                     $model->recipient = 1;
                     break;
                 case 'author_to_customer':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Author');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Customer');
                     $model->recipient = Zakaz::model()->findByPk($orderId)->attributes['user_id'];
                     break;
                 case 'corrector_to_customer':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Corrector');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Customer');
                     $model->recipient = Zakaz::model()->findByPk($orderId)->attributes['user_id'];
                     break;
                 case 'customer_to_author':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Customer');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Author');
                     $model->recipient = Zakaz::model()->resetScope()->findByPk($orderId)->attributes['executor'];
                     break;
                 case 'corrector_to_author':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Corrector');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Author');
                     $model->recipient = Zakaz::model()->resetScope()->findByPk($orderId)->attributes['executor'];
                     break;
                 case 'author_to_corrector':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Author');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Corrector');
                     $model->recipient = -2;
                     break;
                 case 'customer_to_corrector':
                     $model->sender_role = ProjectMessages::model()->getRoleId('Customer');
                     $model->recipient_role = ProjectMessages::model()->getRoleId('Corrector');
                     $model->recipient = -2;
                     break;
             }
             $model->save();
             EventHelper::addMessage($orderId, $model->message);
         }
         $this->renderPartial('chat', array('order' => $order, 'orderId' => $orderId, 'isGuest' => $isGuest));
         Yii::app()->end();
     }
     if (User::model()->isAuthor() && (!User::model()->isCorrector() || !$order->technicalspec) && !User::model()->isExecutor($orderId)) {
         $this->redirect(Yii::app()->createUrl('/project/chat/view', array('orderId' => $orderId)));
     }
     if (User::model()->isCustomer() && $order->user_id != Yii::app()->user->id) {
         $this->redirect('/');
     }
     $parts = ZakazParts::model()->findAll(array('condition' => "`proj_id`='{$orderId}'"));
     if (User::model()->isExecutor($order->id)) {
         $order->executor_event = null;
     }
     if (User::model()->isCustomer()) {
         $order->customer_event = null;
     }
     $order->save(false);
     $moderate_types = EventHelper::get_moderate_types_string();
     $events = Events::model()->findAll(array('condition' => "`event_id`='{$orderId}' AND `type` in ({$moderate_types})", 'order' => 'timestamp DESC'), array(':event_id' => $orderId));
     $PaymentImages = PaymentImage::model()->findAll(array('condition' => "`project_id`='{$orderId}'"));
     $moderated = count($events) == 0;
     $this->render('index', array('orderId' => $orderId, 'order' => $order, 'executor' => Zakaz::getExecutor($orderId), 'moderated' => $moderated, 'parts' => $parts, 'PaymentImages' => $PaymentImages, 'isCorrector' => $isCorrector));
 }
Exemple #20
0
	font-size:12px;
	
	
}
.ui-corner-all a{text-indent:-999px !important; background:url(images/evnt_close.png) no-repeat !important;
	width:21px; height:21px;}



</style>



<div id="dialog" class="window">
<?php 
$event = Events::model()->findByAttributes(array('id' => $event_id));
$event_type = EventsType::model()->findByPk($event->type);
?>
	<div class="event_viewbx">
        <div class="e_closebttn"></div>
        <div class="e_pop_top">
        		
        		 <div class="e_pop_top_color">
                 	<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 				width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve">
					<path fill-rule="evenodd" clip-rule="evenodd" fill="<?php 
echo $event_type->colour_code;
?>
" d="M1,0h23C14.162,10.08,11.671,12.419,0,24V1C0,0.447,0.448,0,1,0z"
					/>
					</svg>
Exemple #21
0
 /**
  * Megjeleníti a megadott esemény részletes adatait.
  * @param int $id Az esemény azonosítója
  */
 public function actionDetails($id)
 {
     $EventModel = Events::model()->findByPk((int) $id);
     $SubjectModel = Subject::model()->findByPk($EventModel->subject_id);
     if ($EventModel == null || $SubjectModel == null) {
         throw new CHttpException(404, "A kért elem nem található");
     }
     $this->render('details', array('EventModel' => $EventModel, 'SubjectModel' => $SubjectModel));
 }
Exemple #22
0
 public function actionAddComment()
 {
     if (isset($_POST['id']) && isset($_POST['text']) && $_POST['text'] != '') {
         $id = $_POST['id'];
         $comment = $_POST['text'];
         $postModel = Events::model()->findByPk($id);
         if ($postModel === null) {
             throw new CHttpException(404, Yii::t('app', 'The requested post does not exist.'));
         }
         $commentModel = new Events();
         $commentModel->text = $comment;
         $commentModel->user = Yii::app()->user->name;
         $commentModel->type = 'comment';
         $commentModel->associationId = $postModel->id;
         $commentModel->associationType = 'Events';
         $commentModel->timestamp = time();
         if ($commentModel->save()) {
             $commentCount = X2Model::model('Events')->countByAttributes(array('type' => 'comment', 'associationType' => 'Events', 'associationId' => $postModel->id));
             $postModel->lastUpdated = time();
             $postModel->save();
             $profileUser = Yii::app()->db->createCommand()->select('username')->from('x2_users')->where('id=:id', array(':id' => $postModel->associationId))->queryScalar();
             // notify the owner of the feed containing the post you commented on (unless that person is you)
             if ($postModel->associationId != Yii::app()->user->getId()) {
                 $postNotif = new Notification();
                 $postNotif->type = 'social_comment';
                 $postNotif->createdBy = $commentModel->user;
                 $postNotif->modelType = 'Profile';
                 $postNotif->modelId = $postModel->associationId;
                 // look up the username of the owner of the feed
                 $postNotif->user = $profileUser;
                 $postNotif->createDate = time();
                 $postNotif->save();
             }
             // now notify the person whose post you commented on (unless they're the same person as the first notification)
             if ($profileUser != $postModel->user && $postModel->user != Yii::app()->user->name) {
                 $commentNotif = new Notification();
                 $commentNotif->type = 'social_comment';
                 $commentNotif->createdBy = $commentModel->user;
                 $commentNotif->modelType = 'Profile';
                 $commentNotif->modelId = $postModel->associationId;
                 $commentNotif->user = $postModel->user;
                 $commentNotif->createDate = time();
                 $commentNotif->save();
             }
         }
         echo $commentCount;
     } else {
         echo "";
     }
 }
Exemple #23
0
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * X2Engine" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by X2Engine".
 *****************************************************************************************/
?>
<div class="view top-level">
	<div class="deleteButton">
		<?php 
$parent = Events::model()->findByPk($data->associationId);
if ($data->user == Yii::app()->user->getName() || $parent->associationId == Yii::app()->user->getId() || Yii::app()->params->isAdmin) {
    echo CHtml::link('', array('/profile/deletePost', 'id' => $data->id, 'profileId' => $profileId), array('class' => 'fa fa-close'));
}
//,array('class'=>'x2-button')
?>
	</div>
	<?php 
echo User::getUserLinks($data->user);
echo ' ';
echo X2Html::tag('span', array('class' => 'comment-age x2-hint', 'id' => "-{$data->timestamp}", 'title' => Formatter::formatFeedTimestamp($data->timestamp)), Formatter::formatFeedTimestamp($data->timestamp));
?>
 
	<br/>
	<?php 
echo $data->text;
 public function actionChStatus($id, $status)
 {
     $model = UpdateProfile::model()->findByPk($id);
     if ($status == 'appove') {
         $model->status = 1;
         $attribute = $model->attribute;
         $profile = Profile::model()->findbyPk($model->user);
         $profile->{$attribute} = $model->to_data;
         if ($profile->save(false)) {
             $model->save();
         }
         if (YII_DEBUG) {
             CVarDumper::dump($profile->errors);
         }
     }
     if ($status == 'reject') {
         $model->status = 0;
         $model->save();
     }
     $countRecord = UpdateProfile::model()->countByAttributes(array('user' => $model->user, 'status' => null));
     //если записей для редактирования нет, то удаляем сообщения из списка сообщений
     if ($countRecord <= 0) {
         // сменим всем событиям статус на выполненый у данного пользователя
         Yii::import('application.modules.project.components.EventHelper');
         $eventList = Events::model()->findAllByAttributes(array('type' => EventHelper::TYPE_UPDATE_PROFILE, 'event_id' => $model->user));
         foreach ($eventList as $event) {
             $event->delete();
         }
     }
     // ответ
     if (Yii::app()->request->isAjaxRequest) {
         Yii::app()->end();
     }
     Yii::app()->redirect(Yii::app()->request->urlReferrer);
 }
Exemple #25
0
    public static function generateFeedEmail($filters, $userId, $range, $limit, $eventId, $deleteKey)
    {
        $image = Yii::app()->getAbsoluteBaseUrl(true) . '/images/x2engine.png';
        $msg = "<div id='wrap' style='width:6.5in;height:9in;margin-top:auto;margin-left:auto;margin-bottom:auto;margin-right:auto;'><html><body><center>";
        $msg .= '<table border="0" cellpadding="0" cellspacing="0" height="100%" id="top-activity" style="background: white; font-family: \'Helvetica Neue\', \'Helvetica\', Helvetica, Arial, sans-serif; font-weight: normal; font-style: normal; font-size: 14px; line-height: 1; color: #222222; position: relative; -webkit-font-smoothing: antialiased;background-color:#FAFAFA;height:25% !important; margin:0; padding:0; width:100% !important;" width="100%">' . "<tbody><tr><td align=\"center\" style=\"padding-top:20px;\" valign=\"top\">" . '<table border="0" cellpadding="0" cellspacing="0" id="templateContainer" style="border: 1px solid #DDDDDD;background-color:#FFFFFF;" width="600"><tbody>';
        $msg .= '<tr>
                    <td align="center" valign="top"><!-- // Begin Template Header \\ -->
			<table border="0" cellpadding="0" cellspacing="0" id="templateHeader" width="600">
                            <tbody>
				<tr>
                                    <td class="headerContent" style="color:#202020;font-weight:bold;line-height:100%;padding:0;text-align:center;vertical-align:middle;font-family: inherit;font-weight: normal;font-size: 14px;margin-bottom: 17px"><img id="headerImage campaign-icon" src="' . $image . '" style="border:0; height:auto; line-height:100%; outline:none; text-decoration:none;max-width:600px;" /></td>
                                </tr>
                                <tr>
                                    <td style="color:#202020;font-weight:bold;padding:5px;text-align:center;vertical-align:middle;font-family: inherit;font-weight: normal;font-size: 14px;"><h2>' . Yii::t('profile', 'Activity Feed Report') . '</h2></td>
                                </tr>
                            </tbody>
			</table>
                    <hr width="60%"></td><!-- // End Template Header \\ -->
		</tr>';
        $msg .= '<tr><td align="center" valign="top"><!-- // Begin Template Body \\ -->' . '<table border="0" cellpadding="0" cellspacing="0" id="templateBody" width="600"><tbody><tr>' . '<td valign="top"><!-- // Begin Module: Standard Content \\ -->' . '<table border="0" cellpadding="20" cellspacing="0" width="100%"><tbody>';
        $params = array();
        $userRecord = X2Model::model('Profile')->findByPk($userId);
        $params[':username'] = $userRecord->username;
        $parsedFilters = Events::parseFilters($filters, $params);
        $visibilityCondition = $parsedFilters['conditions']['visibility'];
        $accessCriteria = Events::model()->getAccessCriteria();
        $userCondition = $parsedFilters['conditions']['users'];
        $typeCondition = $parsedFilters['conditions']['types'];
        $subtypeCondition = $parsedFilters['conditions']['subtypes'];
        $condition = "type!='comment' AND (type!='action_reminder' " . "OR user=:username) AND " . "(type!='notif' OR user=:username)" . $visibilityCondition . $userCondition . $typeCondition . $subtypeCondition . ' AND (' . $accessCriteria->condition . ')';
        switch ($range) {
            case 'daily':
                $timeRange = 24 * 60 * 60;
                break;
            case 'weekly':
                $timeRange = 7 * 24 * 60 * 60;
                break;
            case 'monthly':
                $timeRange = 30 * 24 * 60 * 60;
                break;
            default:
                $timeRange = 24 * 60 * 60;
                break;
        }
        $condition .= " AND timestamp BETWEEN " . (time() - $timeRange) . " AND " . time();
        $topTypes = Yii::app()->db->createCommand()->select('type, COUNT(type)')->from('x2_events')->where($condition, array_merge($params, $accessCriteria->params))->group('type')->order('COUNT(type) DESC')->limit(5)->queryAll();
        $topUsers = Yii::app()->db->createCommand()->select('user, COUNT(user)')->from('x2_events')->where($condition, array_merge($params, $accessCriteria->params))->group('user')->order('COUNT(user) DESC')->limit(5)->queryAll();
        $msg .= "<tr><td style='text-align:center;'>";
        $msg .= "<div>" . Yii::t('profile', "Here's your {range} update on what's been going on in X2Engine!", array('{range}' => Yii::t('profile', $range))) . "</div><br>" . "<div>Time Range: <em>" . Formatter::formatDateTime(time() - $timeRange) . "</em> to <em>" . Formatter::formatDateTime(time()) . "</em></div>";
        $msg .= "</tr></td>";
        $msg .= "<tr><td><table width='100%'><tbody>";
        $msg .= "<tr><th>" . Yii::t('profile', "Top Activity") . "</th><th>" . Yii::t('profile', "Top Users") . "</th></tr>";
        for ($i = 0; $i < 5; $i++) {
            $msg .= "<tr><td style='text-align:center;'>";
            if (isset($topTypes[$i])) {
                $type = Events::parseType($topTypes[$i]['type']);
                $count = $topTypes[$i]['COUNT(type)'];
                $msg .= $count . " " . $type;
            }
            $msg .= "</td><td style='text-align:center;'>";
            if (isset($topUsers[$i]) && $topUsers[$i]['COUNT(user)'] > 0) {
                $username = User::getUserLinks($topUsers[$i]['user'], false, true);
                $count = $topUsers[$i]['COUNT(user)'];
                $msg .= $count . " " . Yii::t('profile', "events from") . " " . $username . ".";
            }
            $msg .= "</td></tr>";
        }
        $msg .= "</tbody></table></td></tr>";
        $msg .= "<tr><td style='text-align:center'><hr width='60%'>";
        $msg .= "<tr><td style='text-align:center;'>" . Yii::t('profile', "Here's the {limit} most recent items on the Activity Feed.", array('{limit}' => $limit)) . "</td></tr>";
        $msg .= "</td></tr>";
        $msg .= "<tr><td style='text-align:center'><hr width='60%'><table><tbody>";
        $events = new CActiveDataProvider('Events', array('criteria' => array('condition' => $condition, 'order' => 'timestamp DESC', 'params' => array_merge($params, $accessCriteria->params)), 'pagination' => array('pageSize' => $limit)));
        foreach ($events->getData() as $event) {
            $msg .= "<tr>";
            $avatar = Yii::app()->db->createCommand()->select('avatar')->from('x2_profile')->where('username=:user', array(':user' => $event->user))->queryScalar();
            if (!empty($avatar) && file_exists($avatar)) {
                $avatar = Yii::app()->getAbsoluteBaseUrl() . '/' . $avatar;
            } else {
                $avatar = Yii::app()->getAbsoluteBaseUrl(true) . '/uploads/default.png';
            }
            $typeFile = $event->type;
            if (in_array($event->type, array('email_sent', 'email_opened'))) {
                if (in_array($event->subtype, array('quote', 'invoice'))) {
                    $typeFile .= "_{$event->subtype}";
                }
            }
            if ($event->type == 'record_create') {
                switch ($event->subtype) {
                    case 'call':
                        $typeFile = 'voip_call';
                        break;
                    case 'time':
                        $typeFile = 'log_time';
                        break;
                }
            }
            $imgFile = $avatar;
            if (file_exists(Yii::app()->theme->getBasePath() . '/images/eventIcons/' . $typeFile . '.png')) {
                $imgFile = Yii::app()->getAbsoluteBaseUrl() . '/themes/' . Yii::app()->theme->getName() . '/images/eventIcons/' . $typeFile . '.png';
            }
            $img = CHtml::image($imgFile, '', array('style' => 'width:45px;height:45px;float:left;margin-right:5px;'));
            $msg .= "<td>" . $img . "</td>";
            $msg .= "<td style='text-align:left'><span class='event-text'>" . $event->getText(array('requireAbsoluteUrl' => true), array('style' => 'text-decoration:none;')) . "</span></td>";
            $msg .= "</tr>";
        }
        $msg .= "</tbody></table></td></tr>";
        $msg .= "<tr><td style='text-align:center'><hr width='60%'><table><tbody>";
        $msg .= Yii::t('profile', "To stop receiving this report, ") . CHtml::link(Yii::t('profile', 'click here'), Yii::app()->getAbsoluteBaseUrl() . '/index.php/profile/deleteActivityReport?id=' . $eventId . '&deleteKey=' . $deleteKey);
        $msg .= "</tbody></table></td></tr>";
        $msg .= '</tbody></table></td></tr></tbody></table></td></tr>';
        $msg .= "<tbody></table></td></tr></tbody></table></center></body></html></div>";
        return $msg;
    }
Exemple #26
0
        $criteria->params[':placeholder'] = $rolename;
        $criteria->params[':default'] = '0';
    }
} else {
    if ($rolename != 'Admin') {
        $criteria->condition = 'placeholder = :default or placeholder=:placeholder';
        $criteria->params[':placeholder'] = $rolename;
        $criteria->params[':default'] = '0';
    }
}
$total = Events::model()->count($criteria);
$pages = new CPagination($total);
$pages->setPageSize(Yii::app()->params['listPerPage']);
$pages->applyLimit($criteria);
// the trick is here!
$events = Events::model()->findAll($criteria);
$page_size = Yii::app()->params['listPerPage'];
/**
 * If no events 
 */
if (!$events) {
    ?>
                                            <div style="padding:10px 0px 30px 20px">
                                                <div class="yellow_bx" style="background-image:none;width:90%;padding-bottom:45px;">
                                                    <div class="y_bx_head" style="width:95%;">
                                                    	<?php 
    echo Yii::t('dashboard', 'No Upcoming Events');
    ?>
                                                    </div>                    
                                                </div>
                                            </div>
Exemple #27
0
 public function testGetAccessCriteria()
 {
     TestingAuxLib::loadX2NonWebUser();
     TestingAuxLib::suLogin('admin');
     // admin privileges private profile
     $accessCriteria = Events::model()->getAccessCriteria();
     $this->assertEquals('TRUE', $accessCriteria->condition);
     $this->assertEquals(array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll($accessCriteria)), array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll()));
     // admin privileges public profile
     $accessCriteria = Events::model()->getAccessCriteria(Profile::model()->findByAttributes(array('username' => 'testuser')));
     $this->assertEquals(array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll($accessCriteria)), array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll('user="******"')));
     // non-admin public profile
     TestingAuxLib::suLogin('testuser2');
     Yii::app()->settings->historyPrivacy = null;
     $accessCriteria = Events::model()->getAccessCriteria(Profile::model()->findByAttributes(array('username' => 'testuser')));
     $this->assertEquals(array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll($accessCriteria)), array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll('user="******" and visibility')));
     // non-admin private profile
     TestingAuxLib::suLogin('testuser2');
     Yii::app()->settings->historyPrivacy = null;
     $accessCriteria = Events::model()->getAccessCriteria();
     $this->assertEquals(array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll($accessCriteria)), array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll('user="******" or visibility')));
     // non-admin private profile, user history
     TestingAuxLib::suLogin('testuser2');
     Yii::app()->settings->historyPrivacy = 'user';
     $accessCriteria = Events::model()->getAccessCriteria();
     $this->assertEquals(array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll($accessCriteria)), array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll('user="******"')));
     // non-admin private profile, group history
     // assumes that testuser2 and testuser3 are groupmates
     Yii::app()->settings->historyPrivacy = 'group';
     $accessCriteria = Events::model()->getAccessCriteria();
     $this->assertEquals(array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll($accessCriteria)), array_map(function ($event) {
         return $event->id;
     }, Events::model()->findAll('user="******" or user="******"')));
     Yii::app()->settings->historyPrivacy = null;
     TestingAuxLib::restoreX2WebUser();
 }
 public function actionDelete()
 {
     if (Yii::app()->request->isAjaxRequest) {
         if (!Yii::app()->user->hasState('calUserId')) {
             Yii::app()->end();
         }
         //$user_id = $_POST['ui'];
         $user_id = Yii::app()->user->getState('calUserId');
         $title = $_POST['title'];
         $criteria = new CDbCriteria();
         $criteria->condition = 'user_id=:user_id';
         $criteria->params = array(':user_id' => $user_id);
         $criteria->addSearchCondition('title', $title);
         $eventsDelete = Events::model()->find($criteria);
         $eventsDelete->delete();
         echo 0;
         Yii::app()->end();
     }
 }
 /**
  * Одобрение или нет заказа
  * @param $answer
  * @author Emericanec
  */
 public function actionModerationAnswer($id, $event_id, $answer)
 {
     $model = Zakaz::model()->resetScope()->findByPk($id);
     $event = Events::model()->findByPk($event_id);
     if (!$model->is_active && $event) {
         if ($answer == 1) {
             $model->is_active = 1;
             if ($model->save()) {
                 $event->delete();
                 $this->redirect(Yii::app()->createUrl('project/zakaz/update', array('id' => $model->id)));
             }
         } else {
             // если нет то просто удаляем
             $model->delete();
             $event->delete();
             $this->redirect(Yii::app()->createUrl('project/event'));
         }
     } else {
         $event->delete();
         throw new CHttpException("Заказ не найден или его уже отмодерировали");
     }
 }
 /**
  *  Вывод и добавление сообщений
  */
 public function actionIndex($orderId)
 {
     $isGuest = Yii::app()->user->guestName;
     if ($isGuest) {
         Yii::app()->theme = 'client';
         $order = Zakaz::model()->resetScope()->findByPk($orderId);
         // если гость прошёл по ссылке на неcуществующий
         // проект, отправляем его на регистрацию
         $url = 'http://' . $_SERVER['SERVER_NAME'] . '/';
         if (!$order) {
             $this->redirect($url);
         }
         $moderate_types = EventHelper::get_moderate_types_string();
         $events = Events::model()->findAll(array('condition' => "`event_id`='{$orderId}' AND `type` in ({$moderate_types})", 'order' => 'timestamp DESC'), array(':event_id' => $orderId));
         $moderated = count($events) == 0;
         // если гость прошёл по ссылке на непромодерированный
         // проект, отправляем его на регистрацию
         if (!$moderated) {
             $this->redirect(Yii::app()->createUrl('user/login'));
         }
         //			Catalog::model()->tableName();
         $this->render('index', array('orderId' => $orderId, 'order' => $order, 'executor' => Zakaz::getExecutor($orderId), 'moderated' => $moderated, 'isGuest' => $isGuest, 'parts' => ZakazParts::model()->findAll(array('condition' => "`proj_id`='{$orderId}'"))));
         Yii::app()->end();
     }
     Yii::app()->session['project_id'] = $orderId;
     if (Yii::app()->request->isAjaxRequest) {
         if (Yii::app()->request->getPost('ProjectMessages')) {
             $model = new ProjectMessages();
             $model->sender = Yii::app()->user->id;
             $model->moderated = 0;
             $model->order = $orderId;
             $post = $_POST['ProjectMessages']['message'];
             $post = str_replace("\r\n", '<br>', $post);
             $post = str_replace("\n", '<br>', $post);
             $_POST['ProjectMessages']['message'] = $post;
             $model->attributes = Yii::app()->request->getPost('ProjectMessages');
             $model->date = date('Y-m-d H:i:s');
             switch ($model->recipient) {
                 case 'manager':
                     $model->recipient = 1;
                     break;
                 case 'customer':
                     if (User::model()->isCustomer()) {
                         $model->recipient = Zakaz::model()->resetScope()->findByPk($orderId)->attributes['executor'];
                     }
                     if (User::model()->isAuthor()) {
                         $model->recipient = Zakaz::model()->findByPk($orderId)->attributes['user_id'];
                     }
                     break;
             }
             $model->save();
             EventHelper::addMessage($orderId, $model->message);
         }
         $this->renderPartial('chat', array('orderId' => $orderId, 'isGuest' => $isGuest));
         Yii::app()->end();
     }
     $moderate_types = EventHelper::get_moderate_types_string();
     $events = Events::model()->findAll(array('condition' => "`event_id`='{$orderId}' AND `type` in ({$moderate_types})", 'order' => 'timestamp DESC'), array(':event_id' => $orderId));
     $moderated = count($events) == 0;
     $this->render('index', array('orderId' => $orderId, 'order' => $order, 'executor' => Zakaz::getExecutor($orderId), 'moderated' => $moderated, 'isGuest' => $isGuest));
 }