Beispiel #1
0
 public function run()
 {
     $session = Yii::app()->session;
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     $cookies = Yii::app()->request->cookies;
     // If referrer is not our controller delete search parameters from session.
     if (strpos(Yii::app()->request->urlReferrer, '/quote/list') === false) {
         unset($session['search']);
     }
     if (!empty($_POST['search']) && is_array($_POST['search'])) {
         $search = $_POST['search'];
         $session['search'] = $search;
     } else {
         if (!empty($session['search'])) {
             $search = $session['search'];
         } else {
             $search = array('text' => '', 'authorId' => 0, 'approved' => 'all');
         }
     }
     $criteria = new CDbCriteria();
     $criteria->condition = '(textRu LIKE :text OR textEn LIKE :text) ' . ($search['authorId'] ? 'AND authorId = :authorId ' : '') . ($search['approved'] == 'approved' ? 'AND approvedTime ' : '') . ($search['approved'] == 'unApproved' ? 'AND (approvedTime IS NULL OR approvedTime = 0) ' : '');
     $criteria->params = array(':text' => "%{$search['text']}%") + ($search['authorId'] ? array(':authorId' => $search['authorId']) : array());
     $criteria->order = 'Quote.id DESC';
     $pages = new CPagination(Quote::model()->count($criteria));
     $config->applyTo($pages);
     $pages->applyLimit($criteria);
     $quotes = Quote::model()->with('tags', 'author')->findAll($criteria);
     $showSearchForm = !empty($cookies['showSearchForm']) && $cookies['showSearchForm']->value ? true : false;
     $criteria = new CDbCriteria();
     $criteria->order = 'name';
     $authors = Author::model()->findAll($criteria);
     $this->controller->render('list', array('quotes' => $quotes, 'pages' => $pages, 'authors' => $authors, 'search' => $search, 'showSearchForm' => $showSearchForm));
 }
Beispiel #2
0
 public function run()
 {
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     $form = new SearchForm();
     // If referrer is not our action delete search parameters from session.
     if (strpos(Yii::app()->request->urlReferrer, '/site/search') === false) {
         Yii::app()->session->remove('siteSearch');
     } else {
         if (!empty(Yii::app()->session['SearchForm'])) {
             $siteSearch = Yii::app()->session['SearchForm'];
             $form->text = $siteSearch['text'];
             $form->authorId = $siteSearch['authorId'];
         }
     }
     if (!empty($_POST['SearchForm']) && is_array($_POST['SearchForm'])) {
         $form->attributes = $_POST['SearchForm'];
         Yii::app()->session['SearchForm'] = array('text' => $form->text, 'authorId' => $form->authorId);
     }
     $criteria = new CDbCriteria();
     $criteria->order = 'approvedTime DESC';
     $criteria->condition = 'approvedTime AND (textRu LIKE :text OR textEn LIKE :text) ' . ($form->authorId ? 'AND (authorId LIKE :authorId)' : '');
     $criteria->params = array(':text' => "%{$form->text}%") + ($form->authorId ? array(':authorId' => $form->authorId) : array());
     $pages = new CPagination(Quote::model()->count($criteria));
     $config->applyTo($pages);
     $pages->applyLimit($criteria);
     $quotes = Quote::model()->with('tags')->findAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->order = 'name';
     $authors = Author::model()->findAll($criteria);
     $this->controller->render('search', array('quotes' => $quotes, 'pages' => $pages, 'form' => $form, 'authors' => $authors));
 }
Beispiel #3
0
 public function run()
 {
     $criteria = new CDbCriteria();
     $criteria->condition = 'approvedTime';
     $quote = Quote::model()->findByPk($_GET['id'], $criteria);
     if ($quote === null) {
         throw new CHttpException(404, 'Quote not found');
     }
     $this->controller->render('quote', array('quote' => $quote));
 }
Beispiel #4
0
 public function run()
 {
     $id = !empty($_GET['id']) ? $_GET['id'] : 0;
     $quote = Quote::model()->findByPk($id);
     if ($quote === null) {
         throw new CHttpException(404, 'Quote not found');
     }
     $quote->delete();
     Yii::app()->user->setFlash('generalMessage', 'Quote was deleted successfully.');
     $this->controller->redirect(array('list'));
 }
Beispiel #5
0
 public function run()
 {
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     $criteria = new CDbCriteria();
     $criteria->order = 'approvedTime DESC';
     $criteria->condition = 'approvedTime';
     $pages = new CPagination(Quote::model()->count($criteria));
     $config->applyTo($pages);
     $pages->applyLimit($criteria);
     $quotes = Quote::model()->with('tags', 'author')->findAll($criteria);
     $this->controller->render('list', array('quotes' => $quotes, 'pages' => $pages));
 }
Beispiel #6
0
 private function getStatistics()
 {
     $staistics = array();
     if ($this->controller->id == 'quote') {
         // Quotes total count.
         $staistics['totalCount'] = Quote::model()->count();
         // Get number of unapproved quotes.
         $criteria = new CDbCriteria();
         $criteria->condition = 'NOT approvedTime';
         $staistics['unapprovedCount'] = Quote::model()->count($criteria);
     } elseif ($this->controller->id == 'tag') {
         $staistics['totalCount'] = Tag::model()->count();
         $tags = Tag::model()->with('quotesCount')->findAll();
         // Delete tags with empty quotesCount (With PHP > 5.3 e can use closure here).
         // TODO: Rewrite this code for PHP 5.3 when it will be avaliable.
         function tagsFilter($tag)
         {
             return (bool) $tag->quotesCount;
         }
         $tags = array_filter($tags, 'tagsFilter');
         // Sort tags by their weights (quotesCount).
         function tagsSort($a, $b)
         {
             if ($a->quotesCount == $b->quotesCount) {
                 return 0;
             }
             return $a->quotesCount > $b->quotesCount ? -1 : 1;
         }
         usort($tags, 'tagsSort');
         $staistics['popularTags'] = array_slice($tags, 0, 10);
     } elseif ($this->controller->id == 'author') {
         $staistics['totalCount'] = Author::model()->count();
         $authors = Author::model()->with('quotesCount')->findAll();
         // Delete authors with empty quotesCount (With PHP > 5.3 e can use closure here).
         // TODO: Rewrite this code for PHP 5.3 when it will be avaliable.
         function authorsFilter($author)
         {
             return (bool) $author->quotesCount;
         }
         $authors = array_filter($authors, 'authorsFilter');
         // Sort tags by their weights (quotesCount).
         function authorsSort($a, $b)
         {
             if ($a->quotesCount == $b->quotesCount) {
                 return 0;
             }
             return $a->quotesCount > $b->quotesCount ? -1 : 1;
         }
         usort($authors, 'authorsSort');
         $staistics['popularAuthors'] = array_slice($authors, 0, 10);
     }
     return $staistics;
 }
 /**
  * Запускаем отрисовку виджета
  *
  * @return void
  */
 public function run()
 {
     // Авторизован ли пользователь
     if (Yii::app()->user->isAuthenticated() === false) {
         return;
     }
     if (($user = Yii::app()->user->getProfile()) === null) {
         return;
     }
     if (empty($this->programId)) {
         return;
     }
     $quote = Quote::model()->user($user->id)->program($this->programId)->find(array('order' => 't.id DESC'));
     $totalCount = Quote::model()->user($user->id)->program($this->programId)->count();
     $this->render($this->view, array('quote' => $quote, 'totalCount' => $totalCount));
 }
Beispiel #8
0
 public function run()
 {
     $connection = Yii::app()->db;
     $command = $connection->createCommand('SELECT id FROM Quote ORDER BY id DESC LIMIT 1');
     $reader = $command->query();
     $row = $reader->read();
     $maxId = $row['id'];
     mt_srand();
     $id = mt_rand(0, $maxId);
     $criteria = new CDbCriteria();
     $criteria->condition = 'approvedTime AND id >= :id';
     $criteria->params = array(':id' => $id);
     $criteria->limit = 1;
     $quote = Quote::model()->find($criteria);
     $this->controller->render('random', array('quote' => $quote));
 }
Beispiel #9
0
 public function run()
 {
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     $author = Author::model()->findByPk($_GET['authorId']);
     if ($author === null) {
         throw new CHttpException(404, 'Author not found');
     }
     $criteria = new CDbCriteria();
     $criteria->condition = 'authorId = :authorId';
     $criteria->params = array(':authorId' => $author->id);
     $pages = new CPagination(Quote::model()->count($criteria));
     $config->applyTo($pages);
     $pages->applyLimit($criteria);
     $quotes = Quote::model()->findAll($criteria);
     $this->controller->render('author', array('author' => $author, 'quotes' => $quotes, 'pages' => $pages));
 }
 public function run()
 {
     Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->getBaseUrl() . '/css/gridview/jquery.yiigridview.js');
     $relationships = Relationships::model()->findAllByAttributes(array('firstType' => 'quotes', 'secondType' => 'contacts', 'secondId' => $this->contactId));
     echo '<div id="quotes-form">';
     echo '<div id="wide-quote-form" class="wide form" style="overflow: visible;">';
     echo '<span style="font-weight:bold; font-size: 1.5em;">' . Yii::t('quotes', "Quotes") . '</span>';
     echo '<br /><br />';
     // get a list of products for adding to quotes
     $products = Product::model()->findAll(array('select' => 'id, name'));
     $productNames = array(0 => '');
     foreach ($products as $product) {
         $productNames[$product->id] = $product->name;
     }
     $quotes = Quote::model()->findAllByAttributes(array('associatedContacts' => $this->contactId));
     foreach ($quotes as $quote) {
         $products = Product::model()->findAll(array('select' => 'id, name, price'));
         $quoteProducts = QuoteProduct::model()->findAllByAttributes(array('quoteId' => $quote->id));
         // find associated products and their quantities
         $quotesProducts = QuoteProduct::model()->findAllByAttributes(array('quoteId' => $quote->id));
         $orders = array();
         // array of product-quantity pairs
         $total = 0;
         // total price for the quote
         foreach ($quotesProducts as $qp) {
             $price = $qp->price * $qp->quantity;
             if ($qp->adjustmentType == 'percent') {
                 $price += $price * ($qp->adjustment / 100);
                 $qp->adjustment = "{$qp->adjustment}%";
             } else {
                 $price += $qp->adjustment;
             }
             $orders[] = array('name' => $qp->name, 'id' => $qp->productId, 'unit' => $qp->price, 'quantity' => $qp->quantity, 'adjustment' => $qp->adjustment, 'price' => $price);
             $order = end($orders);
             $total += $order['price'];
         }
         $dataProvider = new CArrayDataProvider($orders, array('keyField' => 'name', 'sort' => array('attributes' => array('name', 'unit', 'quantity', 'price')), 'pagination' => array('pageSize' => false)));
         $newProductId = "new_product_" . $quote->id;
         $this->render('viewQuotes', array('quote' => $quote, 'contactId' => $this->contactId, 'dataProvider' => $dataProvider, 'products' => $products, 'productNames' => $productNames, 'orders' => $quoteProducts, 'total' => $total));
     }
     // Mini Create Quote Form
     $model = new Quote();
     $this->render('createQuote', array('model' => $model, 'contactId' => $this->contactId, 'productNames' => $productNames));
     echo "</div>";
     echo "</div>";
 }
Beispiel #11
0
 public function run()
 {
     $this->controller->layout = 'rss';
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     $criteria = new CDbCriteria();
     $criteria->order = 'approvedTime DESC';
     $criteria->condition = 'approvedTime';
     $criteria->limit = $config['pageSize'];
     $quotes = Quote::model()->with('author')->findAll($criteria);
     // Save statistics.
     $req = new RssRequest();
     $req->ip = Yii::app()->request->userHostAddress;
     $req->requestTime = time();
     $req->userAgent = Yii::app()->request->userAgent;
     $req->os = '';
     // TODO: Parse UA string and get OS details from it.
     $req->save();
     $this->controller->render('rss', array('quotes' => $quotes, 'config' => $config));
 }
 public function run()
 {
     if (Yii::app()->user->isAuthenticated() === false) {
         $this->controller->redirect(Yii::app()->user->loginUrl);
     }
     if (($user = Yii::app()->user->getProfile()) === null) {
         Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'User not found.'));
         Yii::app()->user->logout();
         $this->controller->redirect((array) '/user/account/login');
     }
     // Определяем программу, для которой необходимо загрузить интересные мысли
     $programId = (int) Yii::app()->request->getParam('programId');
     $program = CourseType::model()->published()->findByPk($programId);
     // Определяем, подписан ли данный пользователь на эту программу
     if (!$program || !Subscription::model()->isUserSubscribed($user, $program)) {
         throw new CHttpException(404);
     }
     //$quotes = Quote::model()->user($user->id)->program($program->id)->findAll();
     $dataProvider = new CActiveDataProvider(Quote::model()->user($user->id)->program($program->id)->with('user', 'courseType', 'block', 'block.entity', 'block.entity.day'), array('pagination' => array('pageVar' => 'page', 'pageSize' => 10), 'sort' => array('defaultOrder' => 't.id ASC')));
     $this->controller->render('interest', array('program' => $program, 'dataProvider' => $dataProvider));
 }
Beispiel #13
0
 public function run()
 {
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     $connection = Yii::app()->db;
     $tag = Tag::model()->findByAttributes(array('name' => $_GET['tag']));
     if ($tag === null) {
         throw new CHttpException(404, 'Tag not found');
     }
     /*
      * Get total number of approved quotes for this tag.
      */
     $countSql = "SELECT COUNT(*) AS totalCount FROM `Quote`\n                             LEFT JOIN QuoteTag\n                             ON Quote.id = QuoteTag.quoteId\n                             WHERE approvedTime AND tagId = {$tag->id}";
     $command = $connection->createCommand($countSql);
     $reader = $command->query();
     $reader->next();
     $row = $reader->current();
     $totalCount = $row['totalCount'];
     $pages = new CPagination($totalCount);
     $config->applyTo($pages);
     /*
      * Get IDs of current page quotes.
      */
     $offset = $pages->pageSize * $pages->currentPage;
     $limit = $pages->pageSize;
     $quotesIdSql = "SELECT id FROM Quote\n                                LEFT JOIN QuoteTag\n                                ON Quote.id = QuoteTag.quoteId\n                                WHERE approvedTime AND tagId = {$tag->id}\n                                GROUP BY quoteId\n                                ORDER BY approvedTime DESC\n                                LIMIT {$offset}, {$limit}";
     $command = $connection->createCommand($quotesIdSql);
     $reader = $command->query();
     $ids = array();
     foreach ($reader as $row) {
         $ids[] = $row['id'];
     }
     $criteria = new CDbCriteria();
     //$criteria->condition = 'approvedTime';
     $criteria->addInCondition('id', $ids);
     $criteria->order = 'approvedTime DESC';
     $quotes = Quote::model()->findAll($criteria);
     /*
     foreach($quotes as $quote)
     	echo $quote->id, ",";
     
     return;
     */
     /*
     $tagName = $_GET['tag'];
     $config = new CConfiguration(Yii::app()->basePath . '/config/pager.php');
     
     $criteria = new CDbCriteria();
     $criteria->condition = 'name = :name';
     $criteria->params = array(':name' => $tagName);
     
     /*
      * Find total count of this tag quotes.
      *
     $connection = Yii::app()->db;
     $command = $connection->createCommand("SELECT COUNT(*) AS totalCount FROM QuoteTag WHERE tagId = (
                                                                SELECT id FROM Tag WHERE `name` = '{$tagName}' LIMIT 1
                                                            )");
     $reader = $command->query();
     $row = $reader->read();
     $quotesCount = $row['totalCount'];
     
     $pages = new CPagination($quotesCount);
     $config->applyTo($pages);
     //$pages->applyLimit($criteria);
     
     $tag = Tag::model()->with(array('quotes' => array(
     					'condition' => 'approvedTime',
     					'order' => 'approvedTime DESC',
     					'offset' => 0,
     					'limit' => 1,
     				)))->find($criteria);
     
     if($tag === null)
     	throw new CHttpException(404, 'Tag not found');
     */
     $this->controller->render('tag', array('tag' => $tag, 'quotes' => $quotes, 'pages' => $pages));
 }
Beispiel #14
0
        $quoteAttributes = array();
        foreach (Contacts::model()->getAttributeLabels() as $fieldName => $label) {
            AuxLib::debugLog('Iterating over contact attributes ' . $fieldName . '=>' . $label);
            $index = Yii::t('contacts', "{contact}", array('{contact}' => $modTitles['contact'])) . ": {$label}";
            $contactAttributes[$index] = "{associatedContacts.{$fieldName}}";
        }
        foreach (Accounts::model()->getAttributeLabels() as $fieldName => $label) {
            AuxLib::debugLog('Iterating over account attributes ' . $fieldName . '=>' . $label);
            $index = Yii::t('accounts', "{account}", array('{account}' => $modTitles['account'])) . ": {$label}";
            $accountAttributes[$index] = "{accountName.{$fieldName}}";
        }
        $Quote = Yii::t('quotes', "{quote}: ", array('{quote}' => $modTitles['quote']));
        $quoteAttributes[$Quote . Yii::t('quotes', "Item Table")] = '{lineItems}';
        $quoteAttributes[$Quote . Yii::t('quotes', "Date printed/emailed")] = '{dateNow}';
        $quoteAttributes[$Quote . Yii::t('quotes', '{quote} or Invoice', array('{quote}' => $modTitles['quote']))] = '{quoteOrInvoice}';
        foreach (Quote::model()->getAttributeLabels() as $fieldName => $label) {
            $index = $Quote . "{$label}";
            $quoteAttributes[$index] = "{" . $fieldName . "}";
        }
    }
    if ($model->type === 'email') {
        $js = 'x2.insertableAttributes = ' . CJSON::encode(array(Yii::t('contacts', '{contact} Attributes', array('{contact}' => $modTitles['contact'])) => $attributes)) . ';';
    } else {
        $js = 'x2.insertableAttributes = ' . CJSON::encode(array(Yii::t('docs', '{contact} Attributes', array('{contact}' => $modTitles['contact'])) => $contactAttributes, Yii::t('docs', '{account} Attributes', array('{account}' => $modTitles['account'])) => $accountAttributes, Yii::t('docs', '{quote} Attributes', array('{quote}' => $modTitles['quote'])) => $quoteAttributes)) . ';';
    }
}
if ($model->type === 'email') {
    // allowable association types
    $associationTypeOptions = Docs::modelsWhichSupportEmailTemplates();
    // insertable attributes by model type
    $insertableAttributes = array();
Beispiel #15
0
 /**
  * Replace tokens with model attribute values.
  *
  * @param type $str Input text
  * @param X2Model $model Model to use for replacement
  * @param array $vars List of extra variables to replace
  * @param bool $encode Encode replacement values if true; use renderAttribute otherwise.
  * @return string
  */
 public static function replaceVariables($str, $model, $vars = array(), $encode = false, $renderFlag = true)
 {
     if ($encode) {
         foreach (array_keys($vars) as $key) {
             $vars[$key] = CHtml::encode($vars[$key]);
         }
     }
     $str = strtr($str, $vars);
     // replace any manually set variables
     if ($model instanceof X2Model) {
         if (get_class($model) !== 'Quote') {
             $str = Formatter::replaceVariables($str, $model, '', $renderFlag, false);
         } else {
             // Specialized, separate method for quotes that can use details from
             // either accounts or quotes.
             // There may still be some stray quotes with 2+ contacts on it, so
             // explode and pick the first to be on the safe side. The most
             // common use case by far is to have only one contact on the quote.
             $accountId = $model->accountName;
             $staticModels = array('Contact' => Contacts::model(), 'Account' => Accounts::model(), 'Quote' => Quote::model());
             $models = array('Contact' => $model->contact, 'Account' => empty($accountId) ? null : $staticModels['Account']->findByAttributes(array('nameId' => $accountId)), 'Quote' => $model);
             $attributes = array();
             foreach ($models as $name => $modelObj) {
                 $moduleRef = Modules::displayName(false, $name . "s");
                 if (empty($modelObj)) {
                     // Model will be blank
                     foreach ($staticModels[$name]->fields as $field) {
                         $attributes['{' . $moduleRef . '.' . $field->fieldName . '}'] = '';
                     }
                 } else {
                     // Insert attributes
                     foreach ($modelObj->attributes as $fieldName => $value) {
                         if ($renderFlag) {
                             $attributes['{' . $moduleRef . '.' . $fieldName . '}'] = $modelObj->renderAttribute($fieldName, false, true, $encode);
                         } else {
                             $attributes['{' . $moduleRef . '.' . $fieldName . '}'] = $modelObj->getAttribute($fieldName);
                         }
                     }
                 }
             }
             $quoteTitle = Modules::displayName(false, "Quotes");
             $quoteParams = array('{' . $quoteTitle . '.lineItems}' => $model->productTable(true), '{' . $quoteTitle . '.dateNow}' => date("F d, Y", time()), '{' . $quoteTitle . '.quoteOrInvoice}' => Yii::t('quotes', $model->type == 'invoice' ? 'Invoice' : $quoteTitle));
             // Run the replacement:
             $str = strtr($str, array_merge($attributes, $quoteParams));
             return $str;
         }
     }
     return $str;
 }
Beispiel #16
0
 /**
  * Creates a new model.
  *
  * If creation is successful, the browser will be redirected to the 'view' page.
  *
  * @param bool $quick If true, this indicates the action is being requested via AJAX
  */
 public function actionCreate($quick = false, $duplicate = false)
 {
     $model = new Quote();
     if ($duplicate && !isset($_POST['Quote'])) {
         $copiedModel = Quote::model()->findByPk($duplicate);
         if (!empty($copiedModel)) {
             foreach ($copiedModel->attributes as $name => $value) {
                 if ($name != 'id') {
                     $model->{$name} = $value;
                 }
             }
             $model->setLineItems($this->duplicateLineItems($copiedModel), false, true);
         }
     }
     $users = User::getNames();
     if ($quick && !Yii::app()->request->isAjaxRequest) {
         throw new CHttpException(400);
     }
     $currency = Yii::app()->params->currency;
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Quote'])) {
         $model->setX2Fields($_POST['Quote']);
         $model->currency = $currency;
         $model->createDate = time();
         $model->lastUpdated = $model->createDate;
         $model->createdBy = Yii::app()->user->name;
         $model->updatedBy = $model->createdBy;
         if (empty($model->name)) {
             $model->name = '';
         }
         if (isset($_POST['lineitem'])) {
             $model->lineItems = $_POST['lineitem'];
         }
         if (!$model->hasLineItemErrors) {
             if ($model->save()) {
                 $model->createEventRecord();
                 $model->createActionRecord();
                 $model->saveLineItems();
                 if (!$quick) {
                     $this->redirect(array('view', 'id' => $model->id));
                 } else {
                     if (isset($_GET['recordId']) && isset($_GET['recordType'])) {
                         $recordId = $_GET['recordId'];
                         $recordType = $_GET['recordType'];
                         $relatedModel = X2Model::model($_GET['recordType'])->findByPk($recordId);
                         // tie record to quote
                         if ($relatedModel) {
                             $relate = new Relationships();
                             $relate->firstId = $model->id;
                             $relate->firstType = "Quote";
                             $relate->secondId = $relatedModel->id;
                             $relate->secondType = $recordType;
                             $relate->save();
                             $model->createAssociatedAction(X2Model::getAssociationType(get_class($relatedModel)), $relatedModel->id);
                         }
                     }
                     return;
                 }
             }
         }
     }
     // get products
     $products = Product::activeProducts();
     $viewData = array('model' => $model, 'users' => $users, 'products' => $products, 'quick' => $quick);
     if (!$quick) {
         $this->render('create', $viewData);
     } else {
         if ($model->hasErrors() || $model->hasLineItemErrors) {
             // Sneak into the response that validation failed via setting
             // the response code manually:
             header('HTTP/1.1 400 Validation Error');
         }
         $this->renderPartial('create', $viewData, false, true);
     }
 }
Beispiel #17
0
 /**
  * Метод перед удалением:
  * 
  * @return void
  */
 public function beforeDelete()
 {
     if (User::model()->admin()->count() === 1 && $this->_oldRole === User::getSuperuserRole()) {
         $this->addError('role', Yii::t('UserModule.user', 'You can\'t make this changes!'));
         return false;
     }
     // убираем связь удаленного пользователя с ролью
     //$auth = Yii::app()->authManager;
     //$auth->revoke($this->role, $this->id);
     //$auth->save();
     // Удаляем токены
     foreach ($this->tokens as $token) {
         $token->delete();
     }
     // Обнуляем связанные элементы обратной связи
     Yii::import("application.modules.feedback.models.Feedback");
     foreach (Feedback::model()->findAllByAttributes(array('user_id' => $this->id)) as $item) {
         $item->user_id = null;
         $item->save(false, array('user_id'));
     }
     // Обнуляем связанные подписки
     Yii::import("application.modules.subscription.models.Subscription");
     foreach (Subscription::model()->findAllByAttributes(array('user_id' => $this->id)) as $item) {
         $item->user_id = null;
         $item->save(false, array('user_id'));
     }
     // Обнуляем связанные результаты голосования
     Yii::import("application.modules.poll.models.*");
     foreach (Result::model()->findAllByAttributes(array('user_id' => $this->id)) as $item) {
         $item->user_id = null;
         $item->save(false, array('user_id'));
     }
     // Удаляем интересные мысли пользователя
     Yii::import("application.modules.classroom.models.Quote");
     Quote::model()->deleteAllByAttributes(array('user_id' => $this->id));
     // Удаляем последние прочитанные страницы пользователя
     Yii::import("application.modules.classroom.models.LastReadPage");
     LastReadPage::model()->deleteAllByAttributes(array('user_id' => $this->id));
     // Удаляем настройки пользователя
     foreach (yupe\models\Settings::model()->findAllByAttributes(array('user_id' => $this->id)) as $item) {
         $item->delete();
     }
     // Удаляем профиль
     $this->profile->delete();
     return parent::beforeDelete();
 }
Beispiel #18
0
 /**
  * Called when a Contact opens an email sent from Inline Email Form. Inline Email Form
  * appends an image to the email with src pointing to this function. This function
  * creates an action associated with the Contact indicating that the email was opened.
  *
  * @param integer $uid The unique id of the recipient
  * @param string $type 'open', 'click', or 'unsub'
  *
  */
 public function actionEmailOpened($uid, $type)
 {
     // If the request is coming from within the web application, ignore it.
     $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
     $baseUrl = Yii::app()->request->getBaseUrl(true);
     $fromApp = strpos($referrer, $baseUrl) === 0;
     if ($type == 'open' && !$fromApp) {
         $track = TrackEmail::model()->findByAttributes(array('uniqueId' => $uid));
         if ($track && $track->opened == null) {
             $action = $track->action;
             if ($action) {
                 $note = new Actions();
                 switch ($action->type) {
                     case 'email_quote':
                     case 'email_invoice':
                         $subType = str_replace('email_', '', $action->type);
                         $note->type = "emailOpened_{$subType}";
                         $quote = Quote::model()->findByPk($action->associationId);
                         if ($quote instanceof Quote) {
                             $contact = $quote->associatedContactsModel;
                             if ($contact instanceof Contacts) {
                                 $note->associationType = 'contacts';
                                 $note->associationId = $contact->id;
                             }
                         }
                         break;
                     default:
                         $note->type = 'emailOpened';
                         $note->associationType = $action->associationType;
                         $note->associationId = $action->associationId;
                 }
                 $now = time();
                 $note->createDate = $now;
                 $note->lastUpdated = $now;
                 $note->completeDate = $now;
                 $note->complete = 'Yes';
                 $note->updatedBy = 'admin';
                 $note->associationName = $action->associationName;
                 $note->visibility = $action->visibility;
                 $note->assignedTo = $action->assignedTo;
                 $note->actionDescription = Yii::t('marketing', 'Contact has opened the email sent on ');
                 $note->actionDescription .= Formatter::formatLongDateTime($action->createDate) . "<br>";
                 $note->actionDescription .= $action->actionDescription;
                 if ($note->save()) {
                     $event = new Events();
                     $event->type = 'email_opened';
                     switch ($action->type) {
                         case 'email_quote':
                             $event->subtype = 'quote';
                             break;
                         case 'email_invoice':
                             $event->subtype = 'invoice';
                             break;
                         default:
                             $event->subtype = 'email';
                     }
                     $contact = isset($quote) && $quote instanceof Quote ? $quote->associatedContactsModel : X2Model::model('Contacts')->findByPk($action->associationId);
                     if (isset($contact)) {
                         $event->user = $contact->assignedTo;
                     }
                     $event->associationType = 'Contacts';
                     $event->associationId = isset($contact) ? $contact->id : $note->associationId;
                     if ($action->associationType == 'services') {
                         $case = X2Model::model('Services')->findByPk($action->associationId);
                         if (isset($case) && is_numeric($case->contactId)) {
                             $event->associationId = $case->contactId;
                         } elseif (isset($case)) {
                             $event->associationType = 'Services';
                             $event->associationId = $case->id;
                         }
                     }
                     $event->save();
                     $track->opened = $now;
                     $track->update();
                 }
             }
         }
     }
     //return a one pixel transparent png
     header('Content-Type: image/png');
     echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAAXNSR0IArs4c6QAAAAJiS0dEAP+Hj8y/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII=');
 }
Beispiel #19
0
 public function run()
 {
     if ($this->id == 'edit') {
         $id = !empty($_GET['id']) ? $_GET['id'] : 0;
         $quote = Quote::model()->with('tags', 'author')->findByPk($id);
         if ($quote === null) {
             throw new CHttpException(404, 'Quote not found');
         }
     } else {
         // add action
         $quote = new Quote();
     }
     if (!$quote->author) {
         $quote->author = new Author();
     }
     if (!empty($_POST['Quote']) && is_array($_POST['Quote'])) {
         $quote->attributes = $_POST['Quote'];
         /*
          * Process approved time.
          */
         $approved = !empty($_POST['Quote']['approvedTime']);
         if (!$quote->approvedTime && $approved) {
             $quote->approvedTime = time();
         } elseif (!$approved) {
             $quote->approvedTime = 0;
         }
         /*
          * Process author.
          */
         if ($_POST['Quote']['authorId']) {
             // Existing author.
             $author = Author::model()->findByPk($_POST['Quote']['authorId']);
             if ($author === null) {
                 throw new CException("Author with \"{$_POST['Quote']['authorId']}\" not found.");
             }
         } else {
             // New author.
             $authorName = $_POST['Quote']['authorCustomName'];
             // At first try to find author with the same name.
             $criteria = new CDbCriteria();
             $criteria->condition = 'name = :name';
             $criteria->params = array(':name' => $authorName);
             $author = Author::model()->find($criteria);
             if ($author === null) {
                 $author = new Author();
                 $author->name = $authorName;
                 $author->save();
             }
         }
         $quote->authorId = $author->id;
         /*
          * Process tags.
          */
         if (!empty($_POST['tags']) && is_array($_POST['tags'])) {
             $tags = $_POST['tags'];
         } else {
             $tags = array();
         }
         $tagsObj = array();
         foreach ($tags as $tag) {
             $tagsObj[] = Tag::model()->findByPk($tag);
         }
         $quote->tags = $tagsObj;
         if ($quote->save()) {
             Yii::app()->user->setFlash('generalMessage', 'Quote was saved successfully.');
             $this->controller->redirect(array('list'));
         }
     }
     $criteria = new CDbCriteria();
     $criteria->order = 'name';
     $authors = Author::model()->findAll($criteria);
     $this->controller->render('edit', array('quote' => $quote, 'authors' => $authors));
 }
 /**
  * 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 = Quote::model()->findByPk((int) $id);
     if ($model === null) {
         throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
     }
     return $model;
 }
 public function actionShow($courseAlias, $typeAlias)
 {
     // Авторизован ли пользователь
     if (Yii::app()->user->isAuthenticated() === false) {
         $this->redirect(Yii::app()->user->loginUrl);
     }
     if (($user = Yii::app()->user->getProfile()) === null) {
         Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'User not found.'));
         Yii::app()->user->logout();
         $this->redirect((array) '/user/account/login');
     }
     // Вид курса
     $courseType = CourseType::model()->published()->with('course')->find('course.alias = :courseAlias AND t.alias = :typeAlias', array(':courseAlias' => $courseAlias, ':typeAlias' => $typeAlias));
     if (!$courseType) {
         throw new CHttpException(404);
     }
     if (Yii::app()->user->isSuperUser()) {
         // Админ может просматривать любой тип курса
         if ($_GET['adminPackageId'] != '') {
             $adminPackageId = (int) Yii::app()->getRequest()->getParam('adminPackageId');
             if ($adminPackageId > 0) {
                 Yii::app()->user->setState('adminPackageId', $adminPackageId);
             } else {
                 Yii::app()->user->setState('adminPackageId', null);
             }
         }
         // Админ может просматривать курс с данными  другого пользователя
         if ($_GET['adminUserId'] != '') {
             $adminUserId = (int) Yii::app()->getRequest()->getParam('adminUserId');
             if ($adminUserId > 0) {
                 Yii::app()->user->setState('adminUserId', $adminUserId);
             } else {
                 Yii::app()->user->setState('adminUserId', null);
             }
         }
         // Подмена данных пользователя для администратора
         if (Yii::app()->user->getState('adminUserId') !== null) {
             $viewedUser = User::model()->findByPK((int) Yii::app()->user->getState('adminUserId'));
             if ($viewedUser) {
                 $user->code = $viewedUser->code;
                 $user->profile->setAttributes(array('name' => $viewedUser->profile->name, 'gender' => $viewedUser->profile->gender, 'birth_date' => $viewedUser->profile->birth_date, 'birth_time' => $viewedUser->profile->birth_time, 'city_id' => $viewedUser->profile->city_id));
                 $user->profile->city = $viewedUser->profile->city;
             }
         }
     }
     // Пакет
     if (Yii::app()->user->isSuperUser() && Yii::app()->user->getState('adminPackageId') !== null) {
         // Админ может просмотреть любой пакет
         $packageId = (int) Yii::app()->user->getState('adminPackageId');
         $this->package = Package::model()->published()->findByPK($packageId);
     } else {
         // Остальным подбираем пакет в зависимости от указанных данных
         $this->package = Package::model()->published()->find('t.type_id = :type_id AND t.gender = :gender AND t.notime = :notime', array(':type_id' => $courseType->id, ':gender' => $user->profile->gender, ':notime' => $user->profile->birth_time === null));
     }
     if (!$this->package) {
         throw new CHttpException(404);
     }
     // День
     $dayNumber = (int) Yii::app()->getRequest()->getParam('day', 1);
     $this->day = $day = Day::model()->published()->package($this->package->id)->findByNumber($dayNumber);
     if (!$day) {
         throw new CHttpException(404);
     }
     // Страница
     $pageNumber = (int) Yii::app()->getRequest()->getParam('page', 1);
     $page = Page::model()->published()->day($day->id)->with(array('blocks' => array('scopes' => 'published', 'order' => 'blocks.sort ASC')))->findByNumber($pageNumber);
     if (!$page) {
         throw new CHttpException(404);
     }
     // Определяем, имеет ли пользователь доступ к выбранной странице курса
     $this->_checkPermissions($user, $courseType, $dayNumber, $pageNumber);
     // Запоминаем последнюю прочитанную страницу для пользователя
     LastReadPage::model()->fixLastPage($user, $courseType, $page);
     // Определяем предыдущую и следующую страницы
     $prevPage = $page->getPrevPage();
     $nextPage = $page->getNextPage();
     // Выделяем интересную мысль, если она указана
     $quoteText = '';
     $highlightId = Yii::app()->getRequest()->getParam('highlight', null);
     if (!empty($highlightId)) {
         $quote = Quote::model()->findByPk($highlightId);
         $quoteText = $quote ? $quote->content : '';
     }
     // Вывод в шаблон
     $this->render('show', array('package' => $this->package, 'day' => $day, 'page' => $page, 'nextPage' => $nextPage, 'prevPage' => $prevPage, 'quoteText' => $quoteText));
 }
 public function actionSave()
 {
     $user = Yii::app()->user->getProfile();
     $quoteText = Yii::app()->getRequest()->getParam('text', null);
     if (!$quoteText === null) {
         return false;
     }
     $blockId = Yii::app()->getRequest()->getParam('blockId', null);
     if ($blockId !== null) {
         $arr = explode('-', $blockId);
         $blockId = key_exists(0, $arr) ? (int) $arr[0] : 0;
         $block = Block::model()->published()->findByPK($blockId);
         if ($block === false) {
             return false;
         }
     } else {
         return false;
     }
     // Создаем и сохраняем цитату
     $quote = new Quote();
     $quote->user_id = $user->id;
     $quote->block_id = $block->id;
     $quote->content = $quoteText;
     if ($quote->save()) {
         // Общее кол-во цитат
         $totalCount = Quote::model()->user($user->id)->program($quote->course_type_id)->count();
         // Возвращаем ответ
         $resp = array('status' => 1, 'data' => array('id' => $quote->id, 'text' => $quote->getContent(), 'url' => $quote->getUrl(), 'totalCount' => $totalCount));
         Yii::app()->ajax->raw($resp);
     } else {
         $resp = array('status' => 0, 'error' => 'Ошибка сохранения.');
         Yii::app()->ajax->raw($resp);
     }
 }