SysMsgController.php 21.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
<?php
class SysMsgController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
		
	/**
	 * 存放模板文件名
	 * @var array
	 */
	private static $templates = array('_sysMsgForHibox', '_sysMsgForDev');
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			//'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
	    /*
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
		*/
	}

	/**
	 * 查看系统通知
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}
	
	/**
	 * 显示首页
	 */
	public function actionIndex()
	{
	    $this->render('index');
	}
	
	/**
	 * 创建系统通知
	 */
	public function actionCreate()
	{
        $model = new SysMsg;
        
	    $this->performAjaxValidation($model);
	    
	    if (isset($_POST['SysMsg']))
	    {
	        $model->attributes = $_POST['SysMsg'];
	            
	        if ($model->validate())
	        {
	            // 指定默认的状态
	            $model->status = SysMsg::YSM_STATUS_CTA;
	            
	            if ($model->save())
	            {
	                $this->redirect(array('view','id'=>$model->id));
	                Yii::app()->end();
	            }
	        }
	        else
	        {
	            $this->redirect(array('index'));
	        }
	    }
	    
	    $this->renderPartial($this->getViewTemplate(), array(
			'model'=>$model,
		));
	}
	
	/**
	 * 更新系统通知
	 */
	public function actionUpdate()
	{
	    $model = $this->loadModel();
	    
		$this->performAjaxValidation($model);
	    
	    if (isset($_POST['SysMsg']))
	    {
	        $model->attributes = $_POST['SysMsg'];
	        
    	    $isSendToAll = Yii::app()->request->getPost("isSendToAll", false);
            
            if ($isSendToAll)
            {
                $model->to_user_id = SysMsg::YSM_VALUE_RECEIVER_EVERYONE;
            }
	            
	        if ($model->validate())
	        {
	            if ($model->save())
	            {
	                $this->redirect(array('view','id'=>$model->id));
	                Yii::app()->end();
	            }
	        }
	    }
	    
	    // 根据平台来获取相应的模板
	    $template = self::$templates[0];
	    $key = (int) $model->plat;
	    
	    if (array_key_exists($key, self::$templates))
	    {
	        $template = self::$templates[$key];
	    }

		$this->render('update',array(
			'model'=>$model,
		    'template'=>$template,
		));
	}
	
	/**
	 * 删除系统通知
	 */
    public function actionDelete()
	{
		if (Yii::app()->request->isPostRequest)
		{
		    $model = $this->loadModel();
		    $model->status = SysMsg::YSM_PLATFORM_DEV;
		    
		    if (! $model->save())
		    {
		        print_r($model->getErrors());
		    }
		    
			if (!isset($_GET['ajax']))
			{
				$this->redirect(array('admin'));
			}
		}
		else
		{
			throw new CHttpException(400,'抱歉,您无权执行此操作!');
		}
	}
	
	/**
	 * 系统通知管理
	 */
	public function actionAdmin()
	{
		$model = new SysMsg('search');
		$model->unsetAttributes();  // clear any default values
		
		if (isset($_GET['SysMsg']))
		{
			$model->attributes=$_GET['SysMsg'];
		}

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	
	/**
	 * 发送系统通知
	 */
    public function actionSendMessage()
    {
        $model = $this->loadModel();
        
        if ($model->status == SysMsg::YSM_STATUS_CTA)
        {
            require_once realpath(Yii::app()->basePath. '/extensions/systemWave/YSSWSystemWaveService.class.php');
            require_once realpath(Yii::app()->basePath. '/extensions/MQ/SystemMessageReceiver/YMQSystemMessageReceiverSetData.class.php');
            require_once realpath(Yii::app()->basePath. '/extensions/MQ/SystemMessageReceiver/YMQSystemMessageReceiverGetData.class.php');
            
            // 检查系统消息模板类文件是否存在, 不存在抛出异常
            if (!class_exists('YSSWSystemWaveService'))
            {
                throw new CHttpException(400, '系统消息模板类文件不存在!');
            }
            
            // 用指定的系统通知消息模板组装消息
            $params = array(
            			       'title' => $model->title ,
            				   'content' => $model->content ,
            				   'link' => (!empty($model->link)) ? $model->link: "",
			               );
            $systemWaveService = new YSSWSystemWaveService();
	        $templateParam = $systemWaveService->getTemplateJsonParam(BACKSTAGE_NOTICE_SERIES, BACKSTAGE_GENERAL_NOTICE, $params);
	            
            // 根据接收者类型来发送系统通知消息
            switch ($model->to_user_id)
            {
                // 向平台所人的用户发送消息
                case SysMsg::YSM_VALUE_RECEIVER_EVERYONE:
                    $this->handleSendToAllReceivers($templateParam);
                    break;
	            // 向平台所人男用户发送消息
                case SysMsg::YSM_VALUE_RECEIVER_MALEUSERS:
                    break;
	            // 向平台所人女用户发送消息
                case SysMsg::YSM_VALUE_RECEIVER_FEMALEUSERS:
                    break;
	            // 向平台所人的会员发送消息
                case SysMsg::YSM_VALUE_RECEIVER_VIPUSERS:
                    break;
                // add
                default:
                    $this->handleSendToAssignedReceivers($templateParam, $model->to_user_id);
            }
            
            // 设置消息发送后的状态
        	$model->status = SysMsg::YSM_STATUS_ATS;
	    	
        	if ($model->save())
	    	{
	    	    $this->redirect(array('admin'));
	    	}
        }
        else
        {
            throw new CHttpException(400, '抱歉, 已发送过系统通知消息!');
        }
    }
    
    /**
     * Lists all models.
     */
    public function actionSearchAll()
    {
        $ID = null;
        $userName = isset($_POST['username']) ? $_POST['username'] : '';
        $Sex = isset($_POST['sex']) ? $_POST['sex'] : '';
        $Prov = isset($_POST['prov']) ? (($_POST['prov'] == 0) ? '' : $_POST['prov']): '';
        $City= isset($_POST['city']) ? (($_POST['city'] == 0) ? '' : $_POST['city']) : '';
        if ( $_POST['platform'] == 0 )
        {
            $sql = "SELECT A.id FROM i_user A, i_userBasic B WHERE A.id = B.id ";
            if(strlen($userName))
            {
                $sql .= " and  A.userName ='".$userName."'";
            }
            if(strlen($Sex))
            {
                $sql .= " and  A.sex ='".$Sex."'";

            }
            if(strlen($City))
            {
                $sql .= " and  B.city ='".$City."'";
            }
            if(strlen($Prov))
            {
                $sql .= " and  B.prov ='".$Prov."'";
            }
        }
        else
        {
            if( strlen($userName) )
            {
                $sql = "select * from open_developers where email='".$userName."';";
            }            
        }
        if ( isset($sql) )
        {
            $command = Yii::app()->db->createCommand($sql);
            $result = $command->queryAll();
        }
        else
        {
            print_r("查无结果!");
        }
        //暂时显示只有id
        if ( count($result) > 0 )
        {
            if ( count($result) > 1 )
            {
                foreach( $result as $ids )
                {
                    $ID .= $ids['id'].",";
                }
            }
            else
            {
                $ID = $result[0]['id'];
            }
            print_r($ID);
        }
        else
        {
            print_r("查无结果!");
        }
    }
    
	/**
	 * 根据主键获取数据
	 * @throws CHttpException
	 * @return object
	 */
	public function loadModel()
	{
		if ($this->_model === null)
		{
			if (isset($_GET['id']))
			{
				$this->_model=SysMsg::model()->findbyPk($_GET['id']);
			}
			if ($this->_model === null)
			{
				throw new CHttpException(404,'抱歉, 您访问的页面不存!');
			}
		}
		return $this->_model;
	}
	
	public function actionTest()
	{
	    $result = $this->querySysMsgReceivers("", 0, 10000);
	    var_dump(count($result));
	}
	
	/**
	 * 查询系统消息接收者信息
	 * 
	 * @param string $condition SQL语句  查询条件
	 * @param int $offset SQL语句LIMIT 开始位置
	 * @param int $limit SQL语句LIMIT 长度
	 * @return array
	 */
	protected function querySysMsgReceivers($condition = "", $offset = 0, $limit = HiboxUserSysMsgWaveID::YSM_ROWS_MAX_VALUE)
	{
	    $result = null;

        if (is_numeric($offset) && is_numeric($limit))
        {
            $condition .= " LIMIT $offset,$limit";
        } 

	    $sqlStatement = "SELECT `user_id`, `wave_id` FROM `wave_sys_user_waveid` AS `a` ";
	    $sqlStatement.= "JOIN `i_user` AS `b` ON a.user_id=b.id $condition";
        
	    $model = Yii::app()->db->createCommand($sqlStatement)->queryAll();
		
        if ((is_array($model)) && ($rowCount = count($model)))
        {
            foreach ($model as $key => $receiver)
            {
                if (isset($receiver['user_id'], $receiver['wave_id']))
                {
                    $key = $receiver['user_id'];
                    $result[$key] = $receiver['wave_id'];
                }
            }
            $result[YMQ_SM_RECEIVER_SECTION_VALUE_ROWCOUNT] = $rowCount;
        }
	    
	    return $result;
	}
	
	/**
	 * 查询最新注册用户的时间
	 * 
	 * @param string $condition SQL语句  查询条件
	 * @param string $updateTime 原来的更新时间
	 * @return string
	 */
	protected function queryNewUpdateTime($condition = "", $updateTime = "")
	{
	    if (is_string($condition) && is_string($updateTime))
	    {
    	    $sqlStatement = "SELECT max(b.up_time) FROM `wave_sys_user_waveid` AS `a` ";
    	    $sqlStatement.= "JOIN `i_user` AS `b` ON a.user_id=b.id $condition";
    	    
            $updateTime = Yii::app()->db->createCommand($sqlStatement)->queryScalar();
	    }
        
        return $updateTime;
	}
	
   /**
    * 将消息添加进系统消息wave中并添加到MQ中
    * 
    * @param $receiver 接受消息的联系人
    * @param $templateParam 插入消息表中的模板数据, 为json格式的
    * @param $userID 发送者, 这里默认为系统发送的消息
    */
    protected function addSysMsgAndSendToMQ($receiver, $templateParam, $userID = SW_WAVE_SYSID)
    {
        if (is_array($receiver) && count($receiver) && is_string($templateParam) && is_numeric($userID))
        {
            // 移除数组的总数字段
            array_pop($receiver);
           
            foreach ($receiver as $userID => $waveID)
            {
                $procedure = "CALL  p_im_userMsgs_i($waveID,$userID,'$templateParam','0')";
                // 向wave中添加内容数据库操作,返回消息ID
                $msgID = Yii::app()->db->createCommand($procedure)->queryScalar();
                // 添加消息后成功后发送即时消息
                if ($msgID)
                {
                    // 处理发送消息数据实体类
    	    		$IMServer = new YSIIMService();
    	            // 构造添加消息MQ格式
    	    		$messageProtocol = array(
                    	    					'user' 	=> $userID,
                    	    					'type'  => '',
                    	                        'data'	=> array(
                    	    									 	'wave' => $waveID,
                    	    		                                // 此处修改插入内存数据库中的数据为系统消息json模板而不是html
                    	    										'info' => $templateParam,
                    	    										'infoID' => $msgID,
                    	    								    )
    	    					            );
    	    		// 如果添加成功,将发送到MQ中
    	    		$IMServer->sendMessage($messageProtocol);
                }
            }
        }
    }
    
    /**
     * 处理向平台所有用户发送消息
     * 
     * 具体算法:
     * [
     *   A. 检查MQ中是否已经存在发送者的信息列表, 有直接取出来; 
     *      检查数据库中是否有新注册的用户;
     *      [无: 不处理; 有: 将新数据存放到MQ, 并更新MQ中原来节点段存放的"updateTime"即"用户最新注册时间"]
     *   B. 没有, 则查询数据库, 并将查询到的记录添加到MQ中为以后服务.
     * ]
     * 
     * @param string $data
     */
    protected function handleSendToAllReceivers($data)
    {         
        if (!empty($data) && class_exists('YMQSystemMessageReceiverGetData'))
        {
            // 每个节点段所限制存放的最大记录数
            $limit = HiboxUserSysMsgWaveID::YSM_ROWS_MAX_VALUE;
            // 检查MQ中是否有存放数据, 存在: 返回节点段信息array("sectionCount":int, "updateTime":string), 不存在: 返回array().
            $section = YMQSystemMessageReceiverGetData::getSingle(YMQ_SM_RECEIVER_SECTION_KEY_EVERYONE);
            // 数据库查询发送者记录的SQL语句条件
            $condition = null;
            
            if (is_array($section) && count($section))
            {
                $sectionCount = (int) $section[YMQ_SM_RECEIVER_SECTION_VALUE_SECTIONCOUNT];
                $updateTime = $section[YMQ_SM_RECEIVER_SECTION_VALUE_UPDATETIME];
                $condition = 'AND b.up_time'. '>"' . $updateTime . '"';
                
                // 检查是否有新注册用户, 有: 返回array, 无: 返回null
                $newUpdateData = $this->querySysMsgReceivers($condition);
                
                // 如果有新注册的用户, 则追加到MQ 中相应的节点段尾部
                if ($newUpdateData !== null)
                {
                    $key = YMQ_SM_RECEIVER_SECTION_KEY_EVERYONE. '_'. $sectionCount;
                    $lastSectionRow = YMQSystemMessageReceiverGetData::getSingle($key);
                    
                    if (is_array($lastSectionRow) && count($lastSectionRow))
                    {
                        $sectionRowCount = intval(array_pop($lastSectionRow));
                        $newUpdateRowCount = intval(array_pop($newUpdateData));
                        
                        // 如果存放数据个数小于限制个数10000, 追加到最后一个节点段尾部
                        if ( ($sectionRowCount + $newUpdateRowCount) < HiboxUserSysMsgWaveID::YSM_ROWS_MAX_VALUE )
                        {
                            // 更新MQ中最后一个节点段的数据
                            $lastSectionRow = array_merge($lastSectionRow, $newUpdateData);
                            $lastSectionRow[YMQ_SM_RECEIVER_SECTION_VALUE_ROWCOUNT] = $sectionRowCount + $newUpdateRowCount;
                            $value = json_encode($lastSectionRow);
                            YMQSystemMessageReceiverSetData::update($key, $value);
                            // 更新MQ中分割节点段的 "updateTime" 即 "用户最新注册时间"
                            $section[YMQ_SM_RECEIVER_SECTION_VALUE_UPDATETIME] = $this->queryNewUpdateTime($condition, $updateTime);
                            $value = json_encode($section);
                            YMQSystemMessageReceiverSetData::update(YMQ_SM_RECEIVER_SECTION_KEY_EVERYONE, $value);
                        }
                        else
                        {
                            // 建立一个新节点存放数据
                            $appendSectionCount = ceil($newUpdateRowCount / $limit);
                            
                            for ($i = 1; $i <= $appendSectionCount; $i++)
                            {
                                $key = YMQ_SM_RECEIVER_SECTION_KEY_EVERYONE. '_'. ($sectionCount + $i);
                                $value = json_encode($newUpdateData);
                                YMQSystemMessageReceiverSetData::set($key, $value);
                            }
                        }
                    }
                }
                
                for ($i = 1; $i <= $sectionCount; $i++)
                {
                    // 节点段的名称: 平台所有用户 eg: "everyone_1"
                    $key = YMQ_SM_RECEIVER_SECTION_KEY_EVERYONE. '_' . $i;
                    // 获取各个节点段存放的数据 , 返回 "[{userID:waveID}]"
                    $value = YMQSystemMessageReceiverGetData::getSingle($key);
                    // 如果MQ中存在数据
                    if (is_array($value) && count($value))
                    {
                        // 向这些发送者们发送即时消息
                        $this->addSysMsgAndSendToMQ($value, $data);
                        echo 'MQ: '. $key. ' Send OK.'. PHP_EOL;
                    }
                    // 间隔1秒执行
                    sleep(1);
                }
            }
            else
            {
                // 查询数据库获取记录总数
                $count = HiboxUserSysMsgWaveID::model()->count();
                $count = (int) $count;
                
                // 总共的存放节点个数
                $sectionCount = ceil($count / $limit);
                
                // 以键值队列key,value方式存入到MQ中, 存放命名 eg: "section_1"
                for ($i = 1; $i <= $sectionCount; $i++)
                {
                    // 数据库查询的开始位置(偏移量)
                    $offset = ($i - 1) * $limit;
                    // 如果是最后一个节点段
                    if ($i === $sectionCount)
                    {
                        // 计算最后一个节点存放的记录个数
                        $limit = $count - ($sectionCount - 1) * $limit;
                    }
                    // 数据库查询接收者的数据
                    $value = $this->querySysMsgReceivers($condition, $offset, $limit);
                    // 如果查询的记录存在
                    if ($value !== null)
                    {
                        // 向这些从数据库中查找到的接收者们发送即时消息
                        $this->addSysMsgAndSendToMQ($value, $data);
                        // 存放节点段的名称: 平台所有用户 eg: "everyone_1"
                        $key = YMQ_SM_RECEIVER_SECTION_KEY_EVERYONE. '_' . $i;
                        $value = json_encode($value);
                        // 添加到MQ中为以后服务
                        YMQSystemMessageReceiverSetData::set($key, $value);
                        echo 'DB: '. 'FROM '. $offset . ' Send OK.'. PHP_EOL;
                    }
                    // 间隔1秒执行
                    sleep(1);
                }
            }
        }
    }
    
    /**
     * 处理向指定的用户发送系统消息 [默认]
     * 
     * @param string $data 
     * @param string $userIDs eg: "1,2,3"
     */
    protected function handleSendToAssignedReceivers($data, $userIDs)
    {
        if (!empty($data) && is_string($userIDs))
        {
            // 数据库查询接收者记录 SQL语句的条件
            $condition = "AND a.user_id IN($userIDs)";
            // 数据库查询发送者记录
            $value = $this->querySysMsgReceivers($condition);
            
            // 如果查询的记录存在
            if ($value !== null)
            {
                // 向这些从数据库中查找到的发送者们发送即时消息
                $this->addSysMsgAndSendToMQ($value, $data);
            }
        }
    }
	
	/**
	 * AJAX 验证表单.
	 * @param CModel $model
	 */
	protected function performAjaxValidation($model)
	{
		if (isset($_POST['ajax']) && $_POST['ajax']==='sys-msg-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 根据请求参数获取渲染的模板
	 * 
	 * @throws CHttpException
	 * @return string
	 */
	private function getViewTemplate()
	{
	    // 存放模板文件名
	    $template = null;
	    // 存放模板文件名的数组的键名
	    $key = 0;
	    
	    if (isset($_REQUEST['q']) && is_numeric($_REQUEST['q']))
	    {
	        $key = (int) $_REQUEST['q'];
	    }
        if (is_array(self::$templates) && array_key_exists($key, self::$templates))
        {
            $template = self::$templates[$key];
        }
	    if (is_null($template))
	    {
	        throw new CHttpException(404, '抱歉, 您访问的页面不存!');
	    }
	    return $template;
	}
}
?>