diff --git a/MessageModule.php b/MessageModule.php new file mode 100644 index 0000000..40dde9e --- /dev/null +++ b/MessageModule.php @@ -0,0 +1,117 @@ + + * @link http://yupe.ru + * @copyright 2014 BrusSENS + * @package yupe.modules.message + * @since 0.6-beta + * + */ + + +use yupe\components\WebModule; + +class MessageModule extends WebModule +{ + // название модуля + public function getName() + { + return Yii::t('MessageModule.client', 'Приватные сообщения'); + } + + // описание модуля + public function getDescription() + { + return Yii::t('MessageModule.client', 'Модуль для организации приватных сообщений между пользователями'); + } + + // автор модуля (Ваше Имя, название студии и т.п.) + public function getAuthor() + { + return Yii::t('MessageModule.client', 'Дмитрий Брусенский (BrusSENS)'); + } + + // контактный email автора + public function getAuthorEmail() + { + return Yii::t('MessageModule.client', 'brussens@hoswac.com'); + } + + // сайт автора или страничка модуля + public function getUrl() + { + return Yii::t('MessageModule.client', 'http://hoswac.com'); + } + + public function getCategory() + { + return Yii::t('MessageModule.client', 'Сервисы'); + } + + public function getIsInstallDefault() + { + return false; + } + + public function getIsNoDisable() + { + return false; + } + + public function getVersion() + { + return Yii::t('MessageModule.user', '0.1-alpha'); + } + + public function getIcon() + { + return 'envelope'; + } + + public function getDependencies() + { + return array('user'); + } + + public function init() + { + // this method is called when the module is being created + // you may place code here to customize the module or the application + + // import the module-level models and components + $this->setImport(array( + 'message.models.*', + 'message.components.*', + )); + } + + public function getAdminPageLink() + { + return '/message/messageBackend/index'; + } + + public function getNavigation() + { + return array( + array('label' => Yii::t('MessageModule.user', 'Users')), + array('icon' => 'list-alt', 'label' => Yii::t('MessageModule.user', 'Manage users'), 'url' => array('/user/userBackend/index')), + array('icon' => 'plus-sign', 'label' => Yii::t('MessageModule.user', 'Create user'), 'url' => array('/user/userBackend/create')), + array('label' => Yii::t('MessageModule.user', 'Tokens')), + array('icon' => 'list-alt', 'label' => Yii::t('MessageModule.user', 'Token list'), 'url' => array('/user/tokensBackend/index')), + ); + } + + public function beforeControllerAction($controller, $action) + { + if(parent::beforeControllerAction($controller, $action)) + { + // this method is called before any module controller action is performed + // you may place customized code here + return true; + } + else + return false; + } +} diff --git a/controllers/MessageBackendController.php b/controllers/MessageBackendController.php new file mode 100644 index 0000000..20acc61 --- /dev/null +++ b/controllers/MessageBackendController.php @@ -0,0 +1,18 @@ +render('index'); + } + public function spam() { + $this->render('spam'); + } +} \ No newline at end of file diff --git a/controllers/MessageController.php b/controllers/MessageController.php new file mode 100644 index 0000000..4c08a20 --- /dev/null +++ b/controllers/MessageController.php @@ -0,0 +1,71 @@ +clientScript->registerCssFile( + Yii::app()->assetManager->publish( + Yii::getPathOfAlias('application.modules.message.views.assets.css').'/messageModule.css' + ) + ); + return parent::init(); + } + public function actionInbox() + { + $dataProvider= Message::model()->inbox; + $this->render('index', array('dataProvider'=>$dataProvider)); + } + public function actionOutbox() + { + $dataProvider= Message::model()->outbox; + $this->render('index', array('dataProvider'=>$dataProvider)); + } + public function actionView() { + $stat= Message::model()->countMessages(); + $model = Message::model()->messageView($_GET['message_id']); + if (!$model) { + throw new CHttpException(404, Yii::t('MessageModule.message', 'This message does not exist')); + } + $this->render('show',array('model'=>$model, 'stat'=>$stat)); + } + public function actionCreate() + { + $model=new Message; + $user=new User; + // uncomment the following code to enable ajax-based validation + + if(isset($_POST['ajax']) && $_POST['ajax']==='message-CreateMessage-form') + { + echo CActiveForm::validate($model); + Yii::app()->end(); + } + + if(isset($_POST['Message'])) + { + $model->attributes=$_POST['Message']; + if($model->validate()) + { + if($model->save()) { + Yii::app()->user->setFlash( + YFlashMessages::SUCCESS_MESSAGE, + Yii::t('MessageModule.message', 'Message sent successfully!') + ); + } + } + } + $this->render('create',array('model'=>$model, 'user'=>$user->findAll())); + } + public function toCut($str,$len=30,$div=" "){ + //Обрезка Строки до заданной максимальной длинны, с округлением до посленего символа - разделителя (в меньшую сторону) + //например toCut('Мама мыла раму',14," ") вернет "Мама мыла" + if (strlen($str)<=$len){ + return $str; + } + else{ + $str=substr($str,0,$len); + $pos=strrpos($str,$div); + $str=substr($str,0,$pos); + return $str.' ...'; + } + } +} \ No newline at end of file diff --git a/install/message.php b/install/message.php new file mode 100644 index 0000000..fe2f5e4 --- /dev/null +++ b/install/message.php @@ -0,0 +1,27 @@ + + * @link http://yupe.ru + * @copyright 2014 BrusSENS + * @package yupe.modules.message + * @since 0.6-beta + * + */ +return array( + 'module' => array( + 'class' => 'application.modules.message.MessageModule', + ), + 'import' => array( + 'application.modules.message.models.*', + ), + 'component' => array(), + + 'rules' => array( + '/messages'=> 'message/message/inbox', + '/messages/outbox'=> 'message/message/outbox', + '/message/create'=> 'message/message/create', + '/message/view/'=> 'message/message/view', + ), +); \ No newline at end of file diff --git a/install/migrations/m140201_133405_message_message.php b/install/migrations/m140201_133405_message_message.php new file mode 100644 index 0000000..9cfb959 --- /dev/null +++ b/install/migrations/m140201_133405_message_message.php @@ -0,0 +1,53 @@ + + * @license BSD https://raw.github.com/yupe/yupe/master/LICENSE + * @link http://yupe.ru + **/ +class m140201_133405_message_message extends yupe\components\DbMigration +{ + /** + * Функция настройки и создания таблицы: + * + * @return null + **/ + public function safeUp() + { + $this->createTable( + '{{message_message}}', + array( + 'id' => 'pk', + 'subject' => 'varchar(150)', + 'body' => 'text NOT NULL', + 'send_date' => 'datetime NOT NULL', + 'sender_id' => 'INT(11) NOT NULL', + 'recipient_id' => 'INT(11) NOT NULL', + 'is_spam' => "BIT(1) NOT NULL DEFAULT b'0'", + 'is_read' => "BIT(1) NOT NULL DEFAULT b'0'", + 'sender_del' => "BIT(1) NOT NULL DEFAULT b'0'", + 'recipient_del' => "BIT(1) NOT NULL DEFAULT b'0'", + ), + $this->getOptions() + ); + + //ix + $this->addForeignKey('fk_recipient', '{{message_message}}', 'recipient_id', + '{{user_user}}', 'id', 'CASCADE', 'CASCADE'); + $this->addForeignKey('fk_sender', '{{message_message}}', 'sender_id', + '{{user_user}}', 'id', 'CASCADE', 'CASCADE'); + } + /** + * Функция удаления таблицы: + * + * @return null + **/ + public function safeDown() + { + $this->dropTableWithForeignKeys('{{message_message}}'); + } +} diff --git a/messages/en/message.php b/messages/en/message.php new file mode 100644 index 0000000..5aa8a1a --- /dev/null +++ b/messages/en/message.php @@ -0,0 +1,46 @@ + '', + 'Removed' => '', + 'Submitted' => '', + 'Inbox' => '', + 'Write' => '', + 'Cancel' => '', + 'Send' => '', + 'This is spam!' => '', + 'Remove' => '', + 'This user does not exist' => '', + 'You can not send messages to yourself' => '', + 'Subject' => '', + 'Content' => '', + 'Dispatch date' => '', + 'Sender ID' => '', + 'Recipient nickname' => '', + 'Recipient ID' => '', + 'Marked by the recipient as "Spam"' => '', + 'Read by the recipient' => '', + 'Deleted sender' => '', + 'Deleted recipient' => '', + 'Message sent successfully!' => '', + 'This message does not exist' => '', + 'Fields with * are required' => '', + 'Yesterday at' => '', + 'Today at' => '', +); diff --git a/messages/ru/message.php b/messages/ru/message.php new file mode 100644 index 0000000..0a910f3 --- /dev/null +++ b/messages/ru/message.php @@ -0,0 +1,46 @@ + 'Спам', + 'Removed' => 'Удалённые', + 'Submitted' => 'Отправленные', + 'Inbox' => 'Входящие', + 'Write' => 'Написать', + 'Cancel' => 'Отмена', + 'Send' => 'Отправить', + 'This is spam!' => 'Это спам!', + 'Remove' => 'Удалить', + 'This user does not exist' => 'Такого пользователя не существует', + 'You can not send messages to yourself' => 'Нельзя отправлять сообщения самому себе', + 'Subject' => 'Тема', + 'Content' => 'Содержание', + 'Dispatch date' => 'Дата отправки', + 'Sender ID' => 'ID отправителя', + 'Recipient nickname' => 'Никнейм получателя', + 'Recipient ID' => 'ID получателя', + 'Marked by the recipient as "Spam"' => 'Помечено получателем, как "Спам"', + 'Read by the recipient' => 'Прочтено получателем', + 'Deleted sender' => 'Удалено отправителем', + 'Deleted recipient' => 'Удалено получателем', + 'Message sent successfully!' => 'Сообщение успешно отправлено!', + 'This message does not exist' => 'Такого сообщения не существует', + 'Fields with * are required' => 'Поля, помеченные * обязательны для заполнения', + 'Yesterday at' => 'Вчера в', + 'Today at' => 'Сегодня в', +); diff --git a/models/Message.php b/models/Message.php new file mode 100644 index 0000000..16b3d42 --- /dev/null +++ b/models/Message.php @@ -0,0 +1,290 @@ +true), + array('subject', 'length', 'max'=>150), + array('send_date','default', 'value'=>new CDbExpression('NOW()')), + array('sender_id','default', 'value'=>Yii::app()->user->id), + array('nick_name', 'recipientValidate'), + //array('recipient_id','default', 'value'=>2), + array('body','filter', 'filter'=>array($obj=new CHtmlPurifier(),'purify')), + // The following rule is used by search(). + // @todo Please remove those attributes that should not be searched. + array('nick_name', 'safe'), + array('id, subject, body, send_date, sender_id, recipient_id, is_spam, is_read, sender_del, recipient_del', 'safe', 'on'=>'search'), + ); + } + + /** + * @return array relational rules. + */ + public function relations() + { + // NOTE: you may need to adjust the relation name and the related + // class name for the relations automatically generated below. + return array( + 'sender' => array(self::BELONGS_TO, 'User', 'sender_id'), + 'recipient' => array(self::BELONGS_TO, 'User', 'recipient_id'), + ); + } + + /** + * @return array customized attribute labels (name=>label) + */ + public function attributeLabels() + { + return array( + 'id' => 'ID', + 'subject' => Yii::t('MessageModule.message', 'Subject'), + 'body' => Yii::t('MessageModule.message', 'Content'), + 'send_date' => Yii::t('MessageModule.message', 'Dispatch date'), + 'sender_id' => Yii::t('MessageModule.message', 'Sender ID'), + 'nick_name' => Yii::t('MessageModule.message', 'Recipient nickname'), + 'recipient_id' => Yii::t('MessageModule.message', 'Recipient ID'), + 'is_spam' => Yii::t('MessageModule.message', 'Marked by the recipient as "Spam"'), + 'is_read' => Yii::t('MessageModule.message', 'Read by the recipient'), + 'sender_del' => Yii::t('MessageModule.message', 'Deleted sender'), + 'recipient_del' => Yii::t('MessageModule.message', 'Deleted recipient'), + ); + } + + /** + * Retrieves a list of models based on the current search/filter conditions. + * + * Typical usecase: + * - Initialize the model fields with values from filter form. + * - Execute this method to get CActiveDataProvider instance which will filter + * models according to data in model fields. + * - Pass data provider to CGridView, CListView or any similar widget. + * + * @return CActiveDataProvider the data provider that can return the models + * based on the search/filter conditions. + */ + public function search() + { + // @todo Please modify the following code to remove attributes that should not be searched. + + $criteria=new CDbCriteria; + + $criteria->compare('id',$this->id,true); + $criteria->compare('subject',$this->subject,true); + $criteria->compare('body',$this->body,true); + $criteria->compare('send_date',$this->send_date,true); + $criteria->compare('sender_id',$this->sender_id); + $criteria->compare('recipient_id',$this->recipient_id); + $criteria->compare('is_spam',$this->is_spam); + $criteria->compare('is_read',$this->is_read); + $criteria->compare('sender_del',$this->sender_del); + $criteria->compare('recipient_del',$this->recipient_del); + + return new CActiveDataProvider($this, array( + 'criteria'=>$criteria, + )); + } + + public function messageView($id) { + $message=$this->findByPk($id); + if($message->is_read==self::NOT_READ) { + $message->is_read=self::READ; + $message->update(array('is_read')); + } + return $message; + } + + /** + * Returns the static model of the specified AR class. + * Please note that you should have this exact method in all your CActiveRecord descendants! + * @param string $className active record class name. + * @return MessageMessage the static model class + */ + public static function model($className=__CLASS__) + { + return parent::model($className); + } + + /** + * Метод валидации пользователя по введённому nick_name + */ + public function recipientValidate() { + //Вытаскиваем данные пользователя + $user=User::model()->findByAttributes(array('nick_name'=>$this->nick_name)); + if($user) {//если такой пользователь существует + if(Yii::app()->user->id==$user->id) {//проверяем, не отправляет ли он сообщение самому себе + $this->addError('nick_name', Yii::t('MessageModule.message', 'You can not send messages to yourself'));//если отправляет себе, то выдаём ошибку валидации + } + else {//если отправляет другому пользователю + $this->recipient_id=$user->id;//записываем id получателя в соответствующее свойство + } + } + else {//если пользователя с введёным nick_name не существует + $this->addError('nick_name', Yii::t('MessageModule.message', 'This user does not exist'));//выдаём ошибку валидации + } + } + + /** + * @param string $type = inbox, sent, spam, drop + * По умолчанию inbox + * Метод получения количества сообщений + * inbox - входящие + * sent - отправленные + * spam - помеченные пользователем, как спам. + * drop - помеченные пользователем, как удалённые. + */ + public function countMessages() { + $stat=array(); + $criteriaSpam = new CDbCriteria; + $criteriaSpam->condition = 'recipient_id = ' . Yii::app()->user->id; + $criteriaSpam->addCondition("is_spam = " . self::SPAM); + $criteriaSpam->addCondition("recipient_del = " . self::NOT_DROP); + $stat['spam']=$this->count($criteriaSpam); + + $criteriaDrop = new CDbCriteria; + $criteriaDrop->condition = 'recipient_id = ' . Yii::app()->user->id; + $criteriaDrop->addCondition("recipient_del = " . self::DROP); + $stat['drop']=$this->count($criteriaDrop); + + return $stat; + } + public function getInboxcount() { + $criteria= new CDbCriteria; + $criteria->condition = 'recipient_id = ' . Yii::app()->user->id; + $criteria->addCondition("is_spam = " . self::NOT_SPAM); + $criteria->addCondition("recipient_del = " . self::NOT_DROP); + $criteria->addCondition("is_read = " . self::NOT_READ); + return $this->count($criteria); + } + public function getOutboxcount() { + $criteria = new CDbCriteria; + $criteria->condition = 'sender_id = ' . Yii::app()->user->id; + $criteria->addCondition("sender_del = " . self::NOT_DROP); + return $this->count($criteria); + } + public function getInbox() { + $criteria = new CDbCriteria; + $criteria->condition = 'recipient_id = ' . Yii::app()->user->id; + $criteria->addCondition("is_spam = " . self::NOT_SPAM); + $criteria->addCondition("recipient_del = " . self::NOT_DROP); + $criteria->with = array('sender'=>array('alias'=>'author')); + $criteria->order='send_date DESC'; + $dataProvider=new CActiveDataProvider($this, array( + 'pagination'=>array( + 'pageSize'=>3, + ), + 'criteria'=>$criteria, + )); + return $dataProvider; + } + public function getOutbox() { + $criteria = new CDbCriteria; + $criteria->condition = 'sender_id = ' . Yii::app()->user->id; + $criteria->addCondition("sender_del = " . self::NOT_DROP); + $criteria->order='send_date DESC'; + $dataProvider=new CActiveDataProvider($this, array( + 'pagination'=>array( + 'pageSize'=>3, + ), + 'criteria'=>$criteria, + )); + return $dataProvider; + } + + /** + * @param string $type = inbox, sent, spam, drop + * По умолчанию inbox + * Метод получения списка сообщений. + * inbox - входящие + * sent - отправленные + * spam - помеченные пользователем, как спам. + * drop - помеченные пользователем, как удалённые. + * @param boolean $dataProvider + * По умолчанию true + * При false возвращает criteria + * + */ + public function giveMessages($type='inbox', $dataProvider=true) { + $criteria = new CDbCriteria; + switch ($type) { + case "spam": + $criteria->condition = 'recipient_id = ' . Yii::app()->user->id; + $criteria->addCondition("is_spam = " . self::SPAM); + $criteria->addCondition("recipient_del = " . self::NOT_DROP); + break; + case "drop": + $criteria->condition = 'recipient_id = ' . Yii::app()->user->id; + $criteria->addCondition("recipient_del = " . self::DROP); + break; + } + $criteria->order='send_date DESC'; + $dataProvider=new CActiveDataProvider($this, array( + 'pagination'=>array( + 'pageSize'=>3, + ), + 'criteria'=>$criteria, + )); + return $dataProvider; + } + public function getRelation($actionId) { + switch($actionId) { + case "outbox": + return $this->recipient; + break; + case "inbox": + return $this->sender; + break; + } + } + public function getIsRead() { + if($this->is_read!=0) { + return true; + } + else { + return false; + } + } +} diff --git a/views/assets/css/messageModule.css b/views/assets/css/messageModule.css new file mode 100644 index 0000000..650239f --- /dev/null +++ b/views/assets/css/messageModule.css @@ -0,0 +1,25 @@ +.y-mess-item { + border-bottom:1px solid #EFEFEF; +} +.y-mess-item a { + display:inline-block; +} +.y-mess-item:hover { + cursor:pointer; + background:#eff0ef; +} +.items { + border-top:1px solid #EFEFEF; +} +.y-mess-no-read { + background:#f6f6f6; +} +.y-mess-no-read:hover { + background:#e2e7ed !important; +} +.y-mess-item .y-mess-buttons { + display:none; +} +.y-mess-item:hover .y-mess-buttons { + display:block; +} \ No newline at end of file diff --git a/views/message/_view.php b/views/message/_view.php new file mode 100644 index 0000000..cfecfbf --- /dev/null +++ b/views/message/_view.php @@ -0,0 +1,39 @@ +
+
+
+ <?php echo $data->getRelation(Yii::app()->controller->action->id)->nick_name; ?> +
+
getRelation(Yii::app()->controller->action->id)->nick_name, array('/user/people/userInfo', 'username'=>$data->getRelation(Yii::app()->controller->action->id)->nick_name)); ?>
+
widget('application.modules.message.widgets.PeopleDate',array('date'=>$data->send_date, 'type' => 1)); ?>
+
+
+
+
+
toCut($data->subject), array('message/view', 'message_id'=>$data->id)); ?>
+
body; ?>
+
+
+
+ widget( + 'bootstrap.widgets.TbButtonGroup', + array( + 'size' => 'mini', + 'type' => 'primary', + 'buttons' => array( + array( + 'label' => '', + 'htmlOptions' => array( + 'class'=>'y-mess-buttons' + ), + 'icon' => 'cog', + 'items' => array( + array('label' => Yii::t('MessageModule.message', 'Remove'), 'url' => '#', 'icon' => 'remove',), + array('label' => Yii::t('MessageModule.message', 'This is spam!'), 'url' => '#', 'icon' => 'warning-sign',), + ) + ), + ), + ) + );?> +
+
+
\ No newline at end of file diff --git a/views/message/create.php b/views/message/create.php new file mode 100644 index 0000000..d9060f0 --- /dev/null +++ b/views/message/create.php @@ -0,0 +1,64 @@ + + +
+
+ widget( + 'application.modules.message.widgets.MessageMenu' + );?> +
+
+
+ beginWidget('bootstrap.widgets.TbActiveForm', array( + 'id'=>'message-CreateMessage-form', + 'enableAjaxValidation'=>true, + 'htmlOptions'=>array('class'=>'well'), + )); ?> + +

* are required');?>

+ + errorSummary($model); ?> + textFieldRow($model, 'nick_name', array('class'=>'span3')); ?> + textFieldRow($model, 'subject', array('class'=>'span3')); ?> + + textAreaRow($model, 'body', array('class'=>'span6', 'rows'=>9)); ?> + + widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'success', 'label'=>Yii::t('MessageModule.message','Send'))); ?> + widget( + 'bootstrap.widgets.TbButton', + array( + 'label' => Yii::t('MessageModule.message', 'Cancel'), + 'type' => 'danger', + 'url'=>array('message/inbox'), + ) + ); ?> + + endWidget(); ?> + +
+
+
\ No newline at end of file diff --git a/views/message/index.php b/views/message/index.php new file mode 100644 index 0000000..56481d7 --- /dev/null +++ b/views/message/index.php @@ -0,0 +1,34 @@ +breadcrumbs=array( + Yii::t('MessageModule.message', 'Inbox'), +); +?> +
+
+ widget( + 'bootstrap.widgets.TbButton', + array( + 'label' => Yii::t('MessageModule.message', 'Write'), + 'type' => 'success', + 'block'=>true, + 'url'=>array('message/create'), + ) + ); ?> +
+ widget( + 'application.modules.message.widgets.MessageMenu' + );?> +
+
+ widget( + 'bootstrap.widgets.TbThumbnails', + array( + 'dataProvider' => $dataProvider, + 'template' => "{items} {pager}", + 'itemView' => '_view', + ) + );?> +
+
\ No newline at end of file diff --git a/views/message/show.php b/views/message/show.php new file mode 100644 index 0000000..740ed34 --- /dev/null +++ b/views/message/show.php @@ -0,0 +1,53 @@ + +
+
+ widget( + 'bootstrap.widgets.TbButton', + array( + 'label' => Yii::t('MessageModule.message', 'Write'), + 'type' => 'success', + 'block'=>true, + 'url'=>array('message/create'), + ) + ); ?> +
+ widget( + 'application.modules.message.widgets.MessageMenu' + );?> +
+
+ + + + + + + + + + + + +
<?php echo $model->sender->nick_name; ?>send_date; ?>
sender->nick_name; ?>subject; ?>
body; ?>
+
+
\ No newline at end of file diff --git a/views/messageBackend/index.php b/views/messageBackend/index.php new file mode 100644 index 0000000..0af8135 --- /dev/null +++ b/views/messageBackend/index.php @@ -0,0 +1,14 @@ +breadcrumbs = array( + Yii::t('MessageModule.message', 'Приватные сообщения') => array('/message/messageBackend/index'), + Yii::t('MessageModule.message', 'Управление'), + ); + + $this->pageTitle = Yii::t('MessageModule.message', 'Приватные сообщения - Управление'); + + $this->menu = array( + array('label' => Yii::t('MessageModule.message', 'Спам'), 'items' => array( + array('icon' => 'list-alt', 'label' => Yii::t('MessageModule.message', 'Список спама'), 'url' => array('/message/spamBackend/index')), + )), + ); +?> \ No newline at end of file diff --git a/views/messageBackend/spam.php b/views/messageBackend/spam.php new file mode 100644 index 0000000..b5da638 --- /dev/null +++ b/views/messageBackend/spam.php @@ -0,0 +1,9 @@ +type='list'; + $this->type='list'; + $this->encodeLabel=false; + $this->items=$this->items(); + parent::init(); + } + public function items() { + $items[]=array('label' => Yii::t('MessageModule.message', 'Inbox') . ((Message::model()->inboxcount!=0) ? '' . Message::model()->inboxcount . '':''),'url' => array('message/inbox'),'active' => (Yii::app()->getController()->getAction()->getId() == 'inbox') ? true : null); + $items[]=array('label' => Yii::t('MessageModule.message', 'Submitted') . ((Message::model()->outboxcount!=0) ? '' . Message::model()->outboxcount . '':''),'url' => array('message/outbox'),'active' => (Yii::app()->getController()->getAction()->getId() == 'outbox') ? true : null); + return $items; + } +} \ No newline at end of file diff --git a/widgets/PeopleDate.php b/widgets/PeopleDate.php new file mode 100644 index 0000000..fa69169 --- /dev/null +++ b/widgets/PeopleDate.php @@ -0,0 +1,221 @@ +date)) { + switch ($this->type) { + case 1: { + echo $this->dateFormat($this->date); + break; + } + case 2: { + echo $this->getTimeAgo($this->date); + break; + } + } + } + } + + function dateFormat($string, $format="%e %b %Y в %H:%M", $lang = 'ru') + { + $strtime=strtotime($string); + $timeAgo = time() - $strtime; + $deftime=array(24=>3600*24, 48=>3600*48); + if (substr(PHP_OS,0,3) == 'WIN') { + $_win_from = array ('%e', '%T', '%D'); + if($timeAgo<$deftime[24]) { + $format=Yii::t('MessageModule.message', 'Today at') . " %H:%M"; + } + elseif($deftime[24]<$timeAgo && $timeAgo<$deftime[48]) { + $format=Yii::t('MessageModule.message', 'Yesterday at') . " %H:%M"; + } + else { + $_win_to = array ('%#d', '%H:%M:%S', '%m/%d/%y'); + } + + $format = str_replace($_win_from, $_win_to, $format); + } + + if($string != '') { + $out = strftime($format, $strtime); + } else { + $out = ''; + } + + $strFrom = array( + 'january', 'jan', + 'february', 'feb', + 'march', 'mar', + 'april', 'apr', + 'may', 'may', + 'june', 'jun', + 'july', 'jul', + 'august', 'aug', + 'september', 'sep', + 'october', 'oct', + 'november', 'nov', + 'december', 'dec', + 'monday', + 'tuesday', + 'wednesday', + 'thursday', + 'friday', + 'saturday', + 'sunday', + 'mon', + 'tue', + 'wed', + 'thu', + 'fri', + 'sat', + 'sun', + ); + $strTo = array('ru' => array( + 'январь', 'янв', + 'февраль', 'фев', + 'март', 'мар', + 'апрель', 'апр', + 'май', 'май', + 'июнь', 'июн', + 'июль', 'июл', + 'август', 'фвг', + 'сентябрь', 'сен', + 'октябрь', 'окт', + 'ноябрь', 'ноя', + 'декабрь', 'дек', + 'понедельник', + 'вторник', + 'среда', + 'четверг', + 'пятница', + 'суббота', + 'воскресенье', + 'пн', + 'вт', + 'ср', + 'чт', + 'пт', + 'сб', + 'вс', + ), + 'ua' => array( + 'Січень','Січ', + 'Лютий', 'Лют', + 'Березень', 'Бер', + 'Квітень', 'Кві', + 'Травень', 'Тра', + 'Червень', 'Чер', + 'Липень', 'Лип', + 'Серпень', 'Сер', + 'Вересень', 'Вер', + 'Жовтень', 'Жов', + 'Листопад', 'Лис', + 'Грудень', 'Грд', + 'Понеділок', + 'Вівторок', + 'Середа', + 'Четвер', + 'П\'ятниця', + 'Субота', + 'Неділя', + 'Пн', + 'Вт', + 'Ср', + 'Чт', + 'Пт', + 'Сб', + 'Нд', + ) + + ); + + $outOld = $out; + $out = str_replace($strFrom, $strTo[$lang], strtolower($out)); + if ($out == strtolower($outOld)){ + $out = $outOld; + } + $out = str_replace('Май.', 'мая', $out); + return $out; + } + + function dateRidN2R($str) + { + $arrFrom = array( + 'январь', + 'февраль', + 'март', + 'апрель', + 'май', + 'июнь', + 'июль', + 'август', + 'сентябрь', + 'октябрь', + 'ноябрь', + 'декабрь', ); + $arrTo = array( + 'января', + 'февраля', + 'марта', + 'апреля', + 'мая', + 'июня', + 'июля', + 'августа', + 'сентября', + 'октября', + 'ноября', + 'декабря'); + $str = str_replace($arrFrom, $arrTo, strtolower($str)); + return $str; + } + + /** + * Переводим TIMESTAMP в формат вида: 5 дн. назад + * или 1 мин. назад и тп. + * + * @param unknown_type $date_time + * @return unknown + */ + function getTimeAgo($date_time) + { + $timeAgo = time() - strtotime($date_time); + $timePer = array( + 'day' => array(3600 * 24, 'дн.'), + 'hour' => array(3600, ''), + 'min' => array(60, 'мин.'), + 'sek' => array(1, 'сек.'), + ); + foreach ($timePer as $type => $tp) { + $tpn = floor($timeAgo / $tp[0]); + if ($tpn){ + + switch ($type) { + case 'hour': + if (in_array($tpn, array(1, 21))){ + $tp[1] = 'час'; + }elseif (in_array($tpn, array(2, 3, 4, 22, 23)) ) { + $tp[1] = 'часa'; + }else { + $tp[1] = 'часов'; + } + break; + } + return $tpn.' '.$tp[1].' назад'; + } + } + + } +} \ No newline at end of file