message.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  1. <?php
  2. class imMessage extends model
  3. {
  4. /**
  5. * @var imModel
  6. */
  7. public $im;
  8. /**
  9. * @var settingModel
  10. */
  11. public $setting;
  12. /**
  13. * Get message by id.
  14. * @param int $id
  15. * @param bool $format
  16. * @access public
  17. * @return object
  18. */
  19. public function getById($id, $format = true)
  20. {
  21. $message = $this->dbh->query("SELECT * FROM " . TABLE_IM_MESSAGE . " WHERE id = $id")->fetch();
  22. return $format ? $this->format($message) : $message;
  23. }
  24. /**
  25. * Get message list.
  26. *
  27. * @param string $cgid
  28. * @param array $idList
  29. * @param object $pager
  30. * @param string $startDate
  31. * @param string $type
  32. * @param bool $format
  33. * @param bool $masterOnly
  34. * @param int $userID
  35. * @access public
  36. * @return array
  37. */
  38. public function getList($cgid = '', $idList = array(), $pager = null, $startDate = '', $type = '', $format = true, $masterOnly = false, $userID = null)
  39. {
  40. if($masterOnly)
  41. {
  42. $tables = array((object)array('tableName' => TABLE_IM_MESSAGE, 'messages' => $idList));
  43. }
  44. else
  45. {
  46. if(!empty($idList)) $tables = $this->getTableByMessages($idList);
  47. if(!empty($startDate)) $tables = $this->getTablesByDateRange($startDate);
  48. if(empty($idList) && empty($startDate)) $tables = $this->getAllTables();
  49. if(empty($tables)) return array();
  50. }
  51. $queries = array();
  52. foreach($tables as $table)
  53. {
  54. $queries[] = $this->dao->select('*')->from($table->tableName)->where('1=1')
  55. ->beginIF(!empty($cgid))->andWhere('cgid')->eq($cgid)->fi()
  56. ->beginIF(!empty($idList))->andWhere('id')->in($table->messages)->fi()
  57. ->beginIF(!empty($startDate))->andWhere('date')->ge($startDate)->fi()
  58. ->beginIF(!empty($type) && strpos($type, '!') === 0)->andWhere('type')->ne(substr($type, 1))->fi()
  59. ->beginIF(!empty($type) && strpos($type, '!') !== 0)->andWhere('type')->eq($type)->fi()
  60. ->beginIF($userID != null)->andWhere('user')->eq($userID)->fi()
  61. ->get();
  62. }
  63. $query = join(' UNION ALL ', $queries);
  64. $sql = $this->dao->select('*')->from(TABLE_IM_MESSAGE);
  65. $sql->sqlobj->sql = 'SELECT * FROM (' . $query . ') as t';
  66. /* Assemble order by and pager stuff. */
  67. $messages = $sql
  68. ->orderBy('id_desc')
  69. ->beginIF($pager != null)->page($pager)->fi()
  70. ->fetchAll();
  71. $messages = $this->decodeMessages($messages);
  72. return $format ? $this->format($messages) : $messages;
  73. }
  74. /**
  75. * Get message list by indexes.
  76. *
  77. * @param string $cgid
  78. * @param array $indexList
  79. * @param object $pager
  80. * @param string $startDate
  81. * @param string $type
  82. * @param bool $format
  83. * @param bool $masterOnly
  84. * @param int $userID
  85. * @access public
  86. * @return array
  87. */
  88. public function getListByIndexes($cgid = '', $indexList = array(), $pager = null, $startDate = '', $type = '', $format = true, $masterOnly = false, $userID = null)
  89. {
  90. if($cgid == '') return array();
  91. if($masterOnly)
  92. {
  93. $tables = array((object)array('tableName' => TABLE_IM_MESSAGE, 'messages' => $indexList));
  94. }
  95. else
  96. {
  97. if(!empty($indexList)) $tables = $this->getChatTablesByChatIndexes($cgid, $indexList);
  98. if(!empty($startDate)) $tables = $this->getChatTablesByDateRange($cgid, $startDate);
  99. if(empty($indexList) && empty($startDate)) $tables = $this->getChatAllTables($cgid);
  100. if(empty($tables)) return array();
  101. }
  102. $queries = array();
  103. foreach($tables as $table)
  104. {
  105. $queries[] = $this->dao->select('*')->from($table->tableName)->where('1=1')
  106. ->andWhere('cgid')->eq($cgid)
  107. ->beginIF(!empty($indexList))->andWhere('`index`')->in($table->messages)->fi()
  108. ->beginIF(!empty($startDate))->andWhere('date')->ge($startDate)->fi()
  109. ->beginIF(!empty($type) && strpos($type, '!') === 0)->andWhere('type')->ne(substr($type, 1))->fi()
  110. ->beginIF(!empty($type) && strpos($type, '!') !== 0)->andWhere('type')->eq($type)->fi()
  111. ->beginIF($userID != null)->andWhere('user')->eq($userID)->fi()
  112. ->get();
  113. }
  114. $query = join(' UNION ALL ', $queries);
  115. $sql = $this->dao->select('*')->from(TABLE_IM_MESSAGE);
  116. $sql->sqlobj->sql = 'SELECT * FROM (' . $query . ') as t';
  117. /* Assemble order by and pager stuff. */
  118. $messages = $sql
  119. ->orderBy('id_desc')
  120. ->beginIF($pager != null)->page($pager)->fi()
  121. ->fetchAll();
  122. $messages = $this->decodeMessages($messages);
  123. return $format ? $this->format($messages) : $messages;
  124. }
  125. /**
  126. * Get messages ranged from id for user.
  127. *
  128. * @param string $cgid
  129. * @param int $fromID
  130. * @param bool $reverse
  131. * @param int $limit
  132. * @param int $userID
  133. * @param bool $returnID return id list only.
  134. * @access public
  135. * @return array
  136. */
  137. public function getListAroundIDForUser($cgid, $fromID, $reverse = false, $limit = 50, $userID = 0, $returnID = false)
  138. {
  139. if($fromID == 0 && $reverse) $fromID = PHP_INT_MAX;
  140. $chats = empty($cgid) ? $this->loadModel('im')->chatGetGidListByUserID($userID, true) : array($cgid);
  141. $tables = $this->getTablesByChats($chats);
  142. if(!empty($tables)) $tables = $this->dao->select('tableName')->from(TABLE_IM_MESSAGE_INDEX)->where(1)
  143. ->beginIF($reverse)->andWhere('start')->le($fromID)->fi()
  144. ->beginIF(!$reverse)->andWhere('end')->ge($fromID)->fi()
  145. ->andWhere('tableName')->in($tables)
  146. ->fetchAll();
  147. $tables[] = (object)array('tableName' => TABLE_IM_MESSAGE);
  148. $queries = array();
  149. foreach($tables as $table)
  150. {
  151. $queries[] = $this->dao->select($returnID ? 'id' : '*')->from($table->tableName)->where(1)
  152. ->beginIF($reverse)->andWhere('id')->le($fromID)->fi()
  153. ->beginIF(!$reverse)->andWhere('id')->ge($fromID)->fi()
  154. ->andWhere('cgid')->in($chats)
  155. ->get();
  156. }
  157. $query = join(' UNION ALL ', $queries);
  158. $sql = $this->dao->select('*')->from(TABLE_IM_MESSAGE);
  159. $sql->sqlobj->sql = 'SELECT * FROM (' . $query . ') as t';
  160. $messages = $sql
  161. ->beginIF($reverse)->orderBy('id_desc')->fi()
  162. ->beginIF(!$reverse)->orderBy('id')->fi()
  163. ->limit($limit)
  164. ->fetchAll();
  165. $messages = $this->decodeMessages($messages);
  166. return $returnID ? array_map(function($obj){return (int)$obj->id;}, $messages) : $this->format($messages);
  167. }
  168. /**
  169. * Get chat messages by indexes.
  170. *
  171. * @param string $cgid
  172. * @param array $indexList
  173. * @param bool $reverse
  174. * @param bool $returnID return id list only.
  175. * @access public
  176. * @return array
  177. */
  178. public function getListAroundIDByIndexes($cgid, $indexList, $reverse = false, $returnID = false)
  179. {
  180. $tables = $this->getChatTablesByChatIndexes($cgid, $indexList);
  181. $queries = array();
  182. foreach($tables as $table)
  183. {
  184. $queries[] = $this->dao->select($returnID ? 'id' : '*')->from($table->tableName)
  185. ->where('cgid')->eq($cgid)
  186. ->beginIF(!empty($indexList))->andWhere('`index`')->in($table->messages)->fi()
  187. ->get();
  188. }
  189. $query = join(' UNION ALL ', $queries);
  190. $sql = $this->dao->select('*')->from(TABLE_IM_MESSAGE);
  191. $sql->sqlobj->sql = 'SELECT * FROM (' . $query . ') as t';
  192. /* Assemble order by and pager stuff. */
  193. $messages = $sql
  194. ->beginIF($reverse)->orderBy('id_desc')->fi()
  195. ->beginIF(!$reverse)->orderBy('id')->fi()
  196. ->fetchAll();
  197. $messages = $this->decodeMessages($messages);
  198. return $returnID ? array_map(function($obj){return (int)$obj->id;}, $messages) : $this->format($messages);
  199. }
  200. /**
  201. * Get last messages of chats.
  202. *
  203. * @param array $cgids
  204. * @access public
  205. * @return array
  206. */
  207. public function getLast($cgids)
  208. {
  209. $chatMessages = $this->dao->select('gid,lastMessage')->from(TABLE_IM_CHAT)->where('gid')->in($cgids)->fetchPairs();
  210. return $chatMessages ? $this->getList('', array_values($chatMessages)) : array();
  211. }
  212. /**
  213. * Get voice message read by message id.
  214. * @param int $messageID
  215. * @access public
  216. * @return string
  217. */
  218. public function getVoiceRead($messageID)
  219. {
  220. $this->dao->select('read')
  221. ->from(TABLE_IM_MESSAGE)
  222. ->where('id')->eq($messageID)
  223. ->fetch();
  224. }
  225. /**
  226. * read voice message.
  227. * @param int $messageID
  228. * @param int $userID
  229. * @access public
  230. * @return int
  231. */
  232. public function readVoice($messageID, $userID)
  233. {
  234. return $this->dbh->exec('UPDATE ' . TABLE_IM_MESSAGE . " SET `read` = JSON_ARRAY_APPEND(IFNULL(`read`, '[]'), '$', $userID) WHERE `id` = $messageID AND `contentType` = 'voice'");
  235. }
  236. /**
  237. * Get read status on messages.
  238. *
  239. * @param array $messageIds message ids to get read status
  240. * @param bool $detailed return detailed read status or not
  241. * @param int $currentUser user id to get read status for
  242. * @access public
  243. * @return array array(messageId => array(userId => readStatus)
  244. */
  245. public function getReadStatus($messageIds, $detailed = false, $currentUser = 0)
  246. {
  247. $systemGroupChat = $this->dao->select('gid')->from(TABLE_IM_CHAT)->where('type')->eq('system')->fetch('gid');
  248. $messageChats = $this->dao->select('id,cgid')->from(TABLE_IM_MESSAGE)->where('id')->in($messageIds)->groupBy('id')->fetchPairs();
  249. $systemMessages = array();
  250. $chatMessages = array();
  251. foreach($messageChats as $messageId => $cgid)
  252. {
  253. if($cgid == $systemGroupChat)
  254. {
  255. $systemMessages[] = $messageId;
  256. continue;
  257. }
  258. if(!isset($chatMessages[$cgid])) $chatMessages[$cgid] = array();
  259. $chatMessages[$cgid][] = $messageId;
  260. }
  261. $chatReads = $this->dao->select('cgid,user,lastReadMessage')
  262. ->from(TABLE_IM_CHATUSER)
  263. ->where('cgid')
  264. ->in(array_keys($chatMessages))
  265. ->andWhere("(quit is null or quit = null)")
  266. ->fetchGroup('cgid');
  267. $readStatuses = array();
  268. foreach($chatMessages as $cgid => $messages)
  269. {
  270. if(!isset($chatReads[$cgid])) continue;
  271. foreach($chatReads[$cgid] as $chatRead)
  272. {
  273. foreach($messages as $messageId)
  274. {
  275. if(!isset($readStatuses[$messageId])) $readStatuses[$messageId] = array();
  276. if($chatRead->user != $currentUser) $readStatuses[$messageId][$chatRead->user] = $messageId <= $chatRead->lastReadMessage ? 1 : 0;
  277. }
  278. }
  279. }
  280. if(!empty($systemMessages))
  281. {
  282. $accountIdPairs = $this->dao->select('account,id')->from(TABLE_USER)->fetchPairs('account');
  283. $lastReadIds = $this->dao->select('`owner`,`value`')->from(TABLE_CONFIG)->where('module')->eq('chat')->andWhere('section')->eq('system')->andWhere('`key`')->eq('lastreadid')->fetchPairs('owner');
  284. foreach($systemMessages as $messageId)
  285. {
  286. $readStatuses[$messageId] = array();
  287. foreach($accountIdPairs as $account => $userId)
  288. {
  289. if ($userId != $currentUser) $readStatuses[$messageId][$userId] = $messageId <= (isset($lastReadIds[$account]) ? $lastReadIds[$account] : 0) ? 1 : 0;
  290. }
  291. }
  292. }
  293. if($detailed) return $readStatuses;
  294. foreach($readStatuses as $messageId => $readStatus)
  295. {
  296. $readCount = array_reduce($readStatus, function($carry, $item) { return $carry + $item; }, 0);
  297. $readStatuses[$messageId] = (object)array('read' => $readCount, 'total' => count($readStatus));
  298. }
  299. return $readStatuses;
  300. }
  301. /**
  302. * Format messages.
  303. *
  304. * @param mixed $messages object | array
  305. * @access public
  306. * @return object | array
  307. */
  308. public function format($messages)
  309. {
  310. $isObject = false;
  311. if(is_object($messages))
  312. {
  313. $isObject = true;
  314. $messages = array($messages);
  315. }
  316. $messageList = array();
  317. foreach($messages as $message)
  318. {
  319. $message->id = (int)$message->id;
  320. $message->index = (int)$message->index;
  321. $message->user = (int)$message->user;
  322. $message->date = strtotime($message->date);
  323. $message->deleted = isset($message->deleted) ? (bool)$message->deleted : false;
  324. /* Clear content for retracted messages */
  325. if($message->deleted) $message->content = '';
  326. $messageList[$message->gid] = $message;
  327. }
  328. if($isObject) return reset($messageList);
  329. return $messageList;
  330. }
  331. /**
  332. * Insert message into message table, ensuring unique index, retrying up to 3 times.
  333. *
  334. * @param object $messageData
  335. * @param int $retries
  336. * @access private
  337. * @return int|false message index or false if failed.
  338. */
  339. private function insertMessageEnsuringUniqueIndex($messageData, $retries = 0)
  340. {
  341. try
  342. {
  343. $stmt = $this->dao->insert(TABLE_IM_MESSAGE)->data($messageData)->get();
  344. $this->dao->dbh->exec($stmt);
  345. return $messageData->index;
  346. }
  347. catch(PDOException $e)
  348. {
  349. /* Handle constraint violation, which is likely caused by index collision, increase index and retry. */
  350. if(++$retries > 3) return false;
  351. $maxIndex = $this->dao->select('MAX(`index`)')->from(TABLE_IM_MESSAGE)
  352. ->where('cgid')->eq($messageData->cgid)
  353. ->fetch('MAX(`index`)');
  354. $messageData->index = $maxIndex + 1;
  355. $retries++;
  356. return $this->insertMessageEnsuringUniqueIndex($messageData, $retries);
  357. }
  358. }
  359. /**
  360. * Create messages.
  361. *
  362. * @param array $messageList
  363. * @param int $userID
  364. * @access public
  365. * @return array
  366. */
  367. public function create($messageList = array(), $userID = 0)
  368. {
  369. $idList = array();
  370. $now = helper::now();
  371. foreach($messageList as $message)
  372. {
  373. $message = (object) $message;
  374. $msg = $this->dao->select('*')->from(TABLE_IM_MESSAGE)->where('gid')->eq($message->gid)->fetch();
  375. if($msg)
  376. {
  377. if($msg->contentType == 'image' || $msg->contentType == 'file')
  378. {
  379. $message = $this->encodeMessage($message);
  380. $this->dao->update(TABLE_IM_MESSAGE)->set('content')->eq($message->content)->where('id')->eq($msg->id)->exec();
  381. }
  382. $idList[] = $msg->id;
  383. }
  384. elseif(!$msg)
  385. {
  386. if(!(isset($message->user) && $message->user)) $message->user = $userID;
  387. if(!(isset($message->date) && $message->date)) $message->date = $now;
  388. $initialMsgIndex = $this->dao->select('`lastMessageIndex` + 1 as msgIndex')->from(TABLE_IM_CHAT)->where('gid')->eq($message->cgid)->fetch('msgIndex');
  389. if(empty($initialMsgIndex)) $initialMsgIndex = 1;
  390. $message->index = $initialMsgIndex;
  391. $message->index = $this->insertMessageEnsuringUniqueIndex($this->encodeMessage($message));
  392. if($message->index === false) continue;
  393. /* Get last insert id from dbh directly, as dao->lastInsertID() is not usable for records inserted by dbh. */
  394. $message->id = $this->dao->dbh->lastInsertId();
  395. if(empty($message->id)) continue;
  396. $chatUpdateData = "lastActiveTime = '$now', lastMessage = $message->id, lastMessageIndex = $message->index";
  397. $this->dao->update(TABLE_IM_CHAT)
  398. ->set($chatUpdateData)
  399. ->where('gid')->eq($message->cgid)
  400. ->exec();
  401. $idList[] = $message->id;
  402. }
  403. }
  404. if(empty($idList)) return array();
  405. return $this->getList('', $idList);
  406. }
  407. /**
  408. * @param object $inviteMessageContent
  409. * @param int $userID
  410. * @return stdclass
  411. */
  412. public function createConferenceMessage($inviteMessageContent, $userID)
  413. {
  414. $this->loadModel('im');
  415. $sender = $this->im->bot->createDefaultBotSender($this->lang->im->conference->botName);
  416. $inviteMessage = new stdclass();
  417. $inviteMessage->gid = imModel::createGID();
  418. $inviteMessage->cgid = "$userID&xuanbot";
  419. $inviteMessage->user = "xuanbot";
  420. $inviteMessage->content = json_encode($inviteMessageContent);
  421. $inviteMessage->type = 'normal';
  422. $inviteMessage->contentType = 'object';
  423. $inviteMessage->data = new stdclass();
  424. $inviteMessage->data->sender = $sender;
  425. $inviteMessage->data = json_encode($inviteMessage->data);
  426. $chatMessages = $this->create(array($inviteMessage), $userID);
  427. $chatOutput = new stdclass();
  428. $chatOutput->result = 'success';
  429. $chatOutput->method = 'messagesend';
  430. $chatOutput->users = array($userID);
  431. $chatOutput->data = $chatMessages;
  432. return $chatOutput;
  433. }
  434. /**
  435. * create xuanbot message.
  436. *
  437. * @param int $userID
  438. * @param string $content
  439. * @param string $contentType
  440. * @param object $sender
  441. * @return stdclass
  442. */
  443. public function createXuanBotMessage($userID, $content, $contentType, $sender = null)
  444. {
  445. $message = new stdclass();
  446. $message->gid = imModel::createGID();
  447. $message->cgid = "$userID&xuanbot";
  448. $message->user = "xuanbot";
  449. $message->type = 'normal';
  450. $message->content = $content;
  451. $message->contentType = $contentType;
  452. if ($sender)
  453. {
  454. $message->data = new stdclass();
  455. $message->data->sender = $sender;
  456. $message->data = json_encode($message->data);
  457. }
  458. $chatMessages = $this->create(array($message), $userID);
  459. $chatOutput = new stdclass();
  460. $chatOutput->result = 'success';
  461. $chatOutput->method = 'messagesend';
  462. $chatOutput->users = array($userID);
  463. $chatOutput->data = $chatMessages;
  464. return $chatOutput;
  465. }
  466. /**
  467. * set message with new content.
  468. * @param $message
  469. * @return void
  470. */
  471. public function setMessage($message)
  472. {
  473. $msg = $this->encodeMessage($message);
  474. $this->dao->update(TABLE_IM_MESSAGE)->set('content')->eq($msg->content)->where('id')->eq($message->id)->exec();
  475. }
  476. /**
  477. * Get message list by cgid.
  478. *
  479. * @param string|array $cgid
  480. * @param object $pager
  481. * @param string $startDate
  482. * @access public
  483. * @return array
  484. */
  485. public function getListByCgid($cgid, $pager = null, $startDate = '')
  486. {
  487. if(empty($startDate)) $tables = $this->getAllTables();
  488. if(!empty($startDate)) $tables = $this->getTablesByDateRange($startDate);
  489. if(empty($tables)) return array();
  490. $queries = array();
  491. foreach($tables as $table)
  492. {
  493. $queries[] = $this->dao->select('*')->from($table->tableName)->where('1=1')
  494. ->beginIF(!is_array($cgid))->andWhere('cgid')->eq($cgid)->fi()
  495. ->beginIF(is_array($cgid))->andWhere('cgid')->in($cgid)->fi()
  496. ->beginIF(!empty($startDate))->andWhere('date')->ge($startDate)->fi()
  497. ->get();
  498. }
  499. $query = join(' UNION ALL ', $queries);
  500. $sql = $this->dao->select('*')->from(TABLE_IM_MESSAGE);
  501. $sql->sqlobj->sql = 'SELECT * FROM (' . $query . ') as t';
  502. /* Assemble order by and pager stuff. */
  503. $messages = $sql
  504. ->orderBy('id_desc')
  505. ->beginIF($pager != null)->page($pager)->fi()
  506. ->fetchAll();
  507. return $this->format($this->decodeMessages($messages));
  508. }
  509. /**
  510. * Fetch chat and message information if chat's last read is greater than user's last known.
  511. *
  512. * @param int $lastKnownMessage
  513. * @param int $userID
  514. * @access public
  515. * @return array of chat => lastReadMessage, empty if all last reads are not greater than last known.
  516. */
  517. public function getMissedByLastKnown($lastKnownMessage, $userID = 0)
  518. {
  519. $missedMessageChats = $this->dao->select('cgid,lastReadMessage')->from(TABLE_IM_CHATUSER)
  520. ->where('user')->eq($userID)
  521. ->andWhere('lastReadMessage')->gt($lastKnownMessage)
  522. ->fetchPairs();
  523. $messageIDs = array();
  524. foreach($missedMessageChats as $cgid => $lastReadID)
  525. {
  526. $chatMessageIDs = $this->getListAroundIDForUser($cgid, $lastReadID, true, 5, $userID, true);
  527. $messageIDs = array_merge($messageIDs, $chatMessageIDs);
  528. }
  529. $unreadIDs = $this->dao->select('message')->from(TABLE_IM_MESSAGESTATUS)
  530. ->where('user')->eq($userID)
  531. ->andWhere('status')->eq('waiting')
  532. ->fetchAll();
  533. $missedIDs = array_diff($messageIDs, array_keys($unreadIDs));
  534. if(empty($missedIDs)) return array();
  535. return $this->getList('', $missedIDs);
  536. }
  537. /**
  538. * Get offline messages.
  539. *
  540. * @param bool $full
  541. * @param int $userID
  542. * @access public
  543. * @return array
  544. */
  545. public function getOfflineList($full = false, $userID = 0)
  546. {
  547. $messageIDs = $this->dao->select('message')->from(TABLE_IM_MESSAGESTATUS)
  548. ->where('user')->eq($userID)
  549. ->andWhere('status')->eq('waiting')
  550. ->fetchPairs('message');
  551. if(empty($messageIDs)) return array();
  552. if(!$full)
  553. {
  554. $firstRecordID = $this->dao->select('MIN(id)')->from(TABLE_IM_MESSAGE)->fetch('MIN(id)');
  555. $messageIDs = array_filter(
  556. $messageIDs,
  557. function($id) use ($firstRecordID)
  558. {
  559. return $id >= $firstRecordID;
  560. }
  561. );
  562. }
  563. if(empty($messageIDs)) return array();
  564. $messages = $this->getList('', $messageIDs, null, '', '!notify', false);
  565. $messageIDs = array();
  566. foreach($messages as $message) array_push($messageIDs, $message->id);
  567. $this->dao->delete()->from(TABLE_IM_MESSAGESTATUS)
  568. ->where('user')->eq($userID)
  569. ->andWhere('message')->in($messageIDs)
  570. ->exec();
  571. return $this->format($messages);
  572. }
  573. /**
  574. * Get history list.
  575. *
  576. * @param object $user
  577. * @param string $device
  578. * @access public
  579. * @return array
  580. */
  581. public function getHistoryList($user, $device = 'desktop')
  582. {
  583. $gids = $this->loadModel('im')->chat->getGidListByUserID($user->id);
  584. $startDate = $this->loadModel('setting')->getItem("owner={$user->account}&module=common&section=lastLogin&key={$device}");
  585. if(!empty($startDate) && !empty($gids)) return $this->getListByCgid($gids, null, $startDate);
  586. }
  587. /**
  588. * Create a output of broadcast.
  589. *
  590. * @param string $type
  591. * @param object $chat
  592. * @param array $onlineUsers
  593. * @param int $userID
  594. * @param array $members
  595. * @param bool $setReminders if true, send members and userID as property "reminders" in $message->data.
  596. * @access public
  597. * @return object
  598. */
  599. public function createBroadcast($type, $chat, $onlineUsers, $userID, $members = array(), $setReminders = false)
  600. {
  601. $adminUsers = array();
  602. $message = new stdclass();
  603. $message->gid = imModel::createGID();
  604. $message->cgid = $chat->gid;
  605. $message->type = 'broadcast';
  606. $message->contentType = 'text';
  607. $message->content = $this->getBroadcastContent($type, $chat, $userID, $members);
  608. $message->date = helper::now();
  609. $message->user = $userID;
  610. if($setReminders)
  611. {
  612. $membersData = array_merge($members, array($userID));
  613. $message->data = json_encode(array('reminders' => $membersData));
  614. }
  615. /* If quit a chat, only send broadcast to the admins or the created user of chat. */
  616. if($type == 'leaveChat')
  617. {
  618. if($chat->admins)
  619. {
  620. if(is_array($chat->admins))
  621. {
  622. $adminUsers = array_map(function($value){
  623. return trim($value);
  624. }, $chat->admins);
  625. }
  626. if(is_string($chat->admins))
  627. {
  628. $adminUsers = explode(',', trim($chat->admins, ','));
  629. }
  630. }
  631. if(!$adminUsers)
  632. {
  633. $user = $this->loadModel('user')->getByAccount($chat->createdBy);
  634. if($user) $adminUsers = array($user->id);
  635. }
  636. $users = $this->loadModel('im')->user->getList($status = 'online', $adminUsers);
  637. $onlineUsers = array_keys($users);
  638. }
  639. /* Save broadcast to im_message. */
  640. $messages = $this->create(array($message), $userID);
  641. $offlineUsers = $this->loadModel('im')->user->getList($status = 'offline', $chat->members);
  642. $this->saveOfflineList($messages, array_keys($offlineUsers));
  643. $output = new stdclass();
  644. $output->method = 'messagesend';
  645. if(dao::isError())
  646. {
  647. $output->result = 'fail';
  648. $output->message = 'Send message failed.';
  649. }
  650. else
  651. {
  652. $output->result = 'success';
  653. $output->users = $onlineUsers;
  654. $output->data = $messages;
  655. }
  656. return $output;
  657. }
  658. /**
  659. * Get content of broadcast.
  660. *
  661. * @param string $type
  662. * @param object $chat
  663. * @param int $userID
  664. * @param array $members
  665. * @access public
  666. * @return string
  667. */
  668. public function getBroadcastContent($type, $chat, $userID, $members)
  669. {
  670. $user = $this->loadModel('im')->userGetByID($userID);
  671. $userName = empty($user->realname) ? $user->account : $user->realname;
  672. $userMention = "[@$userName](@#$user->id)";
  673. if(stripos($type, 'changeChatOwnership') === 0)
  674. {
  675. $nameInMarkdown = preg_replace('/([#\\`*_{}\[\]\(\)\+\-\.!])/i', '\\\\$1', $chat->name);
  676. return sprintf($this->lang->im->broadcast->$type, $nameInMarkdown, $chat->gid, $userMention);
  677. }
  678. if($type == 'chatMerged')
  679. {
  680. return sprintf($this->lang->im->broadcast->$type, $chat->name, $chat->intoName);
  681. }
  682. if($type == 'mergeChat')
  683. {
  684. return sprintf($this->lang->im->broadcast->$type, $chat->name);
  685. }
  686. if($type == 'renamePrivate')
  687. {
  688. $nameInMarkdown = preg_replace('/([#\\`*_{}\[\]\(\)\+\-\.!])/i', '\\\\$1', $chat->name);
  689. return sprintf($this->lang->im->broadcast->$type, $nameInMarkdown, $chat->gid);
  690. }
  691. if($type == 'createChat' or $type == 'renameChat')
  692. {
  693. $nameInMarkdown = preg_replace('/([#\\`*_{}\[\]\(\)\+\-\.!])/i', '\\\\$1', $chat->name);
  694. return sprintf($this->lang->im->broadcast->$type, $userMention, $nameInMarkdown, $chat->gid);
  695. }
  696. if(in_array($type, array('inviteUser', 'createConferenceInvitation', 'mergeChatWithMembers')))
  697. {
  698. $memberMentions = array();
  699. $membersList = $this->im->userGetList('', $members, true, true);
  700. foreach($membersList as $member)
  701. {
  702. $memberName = empty($member->realname) ? $member->account : $member->realname;
  703. $memberMentions[] = "[@$memberName](@#$member->id)";
  704. }
  705. $memberMentions = implode($this->lang->im->connector, $memberMentions);
  706. if($type == 'mergeChatWithMembers') return sprintf($this->lang->im->broadcast->mergeChatWithMembers, $chat->name, $memberMentions);
  707. return sprintf($this->lang->im->broadcast->$type, $userMention, $memberMentions);
  708. }
  709. if($type == 'archiveChat' or $type == 'unarchiveChat')
  710. {
  711. $nameInMarkdown = preg_replace('/([#\\`*_{}\[\]\(\)\+\-\.!])/i', '\\\\$1', $chat->name);
  712. return sprintf($this->lang->im->broadcast->$type, $userMention, $nameInMarkdown);
  713. }
  714. return sprintf($this->lang->im->broadcast->$type, $userMention);
  715. }
  716. /**
  717. * Retract one message.
  718. *
  719. * @param string $gid
  720. * @param boolean $byAdmin
  721. * @param int $deletedBy
  722. * @access public
  723. * @return array
  724. */
  725. public function retract($gid = '', $byAdmin = false, $deletedBy = 0)
  726. {
  727. $message = $this->dao->select('id, gid, cgid, `index`, user, date, data, deleted, type, contentType')->from(TABLE_IM_MESSAGE)->where('gid')->eq($gid)->fetch();
  728. $archiveDate = $this->dao->select('archiveDate')->from(TABLE_IM_CHAT)->where('gid')->eq($message->cgid)->fetch('archiveDate');
  729. if(!empty($archiveDate) && $archiveDate != null) return array();
  730. $messageLife = (strtotime(helper::now()) - strtotime($message->date)) / 60;
  731. if($messageLife <= $this->config->im->retract->validTime && $message->user == $deletedBy)
  732. {
  733. $message->deleted = 1;
  734. $this->dao->update(TABLE_IM_MESSAGE)->set('deleted')->eq($message->deleted)->where('gid')->eq($gid)->exec();
  735. }
  736. elseif($byAdmin)
  737. {
  738. $messageData = empty($message->data) ? new stdClass() : json_decode($message->data);
  739. $bySelf = $message->user == $deletedBy;
  740. if(!$bySelf)
  741. {
  742. $messageData->deletedBy = $deletedBy;
  743. $message->data = $messageData;
  744. }
  745. $message->deleted = 1;
  746. if($bySelf) $this->dao->update(TABLE_IM_MESSAGE)->set('deleted')->eq($message->deleted)->where('gid')->eq($gid)->exec();
  747. else $this->dao->update(TABLE_IM_MESSAGE)->set('deleted')->eq($message->deleted)->set('data')->eq(json_encode($messageData))->where('gid')->eq($gid)->exec();
  748. }
  749. return $this->format(array($message));
  750. }
  751. /**
  752. * Save offline messages.
  753. *
  754. * @param array $messages
  755. * @param array $users
  756. * @access public
  757. * @return bool
  758. */
  759. public function saveOfflineList($messages = array(), $users = array())
  760. {
  761. /* Prevent deleted users from being stored in TABLE_MESSAGESTATUS. */
  762. $deletedUsers = $this->dao->select('id')->from(TABLE_USER)->where('deleted')->eq('1')->fetchPairs();
  763. $users = array_values(array_diff($users, $deletedUsers));
  764. foreach($messages as $message)
  765. {
  766. $this->saveStatus($users, $message->id, 'waiting');
  767. }
  768. return !dao::isError();
  769. }
  770. /**
  771. * Save message status.
  772. *
  773. * @param array $users
  774. * @param int $message
  775. * @param string $status
  776. * @access public
  777. * @return bool
  778. */
  779. public function saveStatus($users, $message, $status = 'waiting')
  780. {
  781. if(empty($users) || empty($message)) return false;
  782. if($this->config->db->driver == 'mysql') // Optimized for mysql.
  783. {
  784. $queryData = array_map(
  785. function($user) use ($message, $status)
  786. {
  787. return "($user,$message,'$status')";
  788. },
  789. $users
  790. );
  791. $query = "INSERT INTO " . TABLE_IM_MESSAGESTATUS . "(`user`,`message`,`status`) VALUES " . join(',', $queryData) . "ON DUPLICATE KEY UPDATE `status`=`status`";
  792. $this->dao->query($query); $this->dao->setCache(trim(TABLE_IM_MESSAGESTATUS, "`"));
  793. }
  794. else
  795. {
  796. foreach($users as $user)
  797. {
  798. $data = new stdclass();
  799. $data->user = $user;
  800. $data->message = $message;
  801. $data->status = $status;
  802. $this->dao->replace(TABLE_IM_MESSAGESTATUS)->data($data)->exec();
  803. }
  804. }
  805. return !dao::isError();
  806. }
  807. /**
  808. * Get notify.
  809. * @access public
  810. * @return array
  811. */
  812. public function getNotifyList()
  813. {
  814. $onlineUsers = $this->loadModel('im')->user->getList('online');
  815. if(empty($onlineUsers)) return array();
  816. $onlineUsers = array_keys($onlineUsers);
  817. $messageUserPairsData = $this->dao->select('message,user')->from(TABLE_IM_MESSAGESTATUS)
  818. ->where('status')->eq('waiting')
  819. ->andWhere('user')->in($onlineUsers)
  820. ->fetchAll();
  821. if(empty($messageUserPairsData)) return array();
  822. $messageUserPairs = array();
  823. foreach($messageUserPairsData as $data)
  824. {
  825. if(isset($messageUserPairs[$data->message]))
  826. {
  827. $messageUserPairs[$data->message][] = $data->user;
  828. continue;
  829. }
  830. $messageUserPairs[$data->message] = array($data->user);
  831. }
  832. $notifyMessages = $this->getList('', array_keys($messageUserPairs), null, '', 'notify', false);
  833. if(empty($notifyMessages)) return array();
  834. $messageIDs = array();
  835. foreach($notifyMessages as $message) $messageIDs[] = $message->id;
  836. $messageUserPairs = array_intersect_key($messageUserPairs, array_flip($messageIDs));
  837. $notifications = $this->formatNotify($notifyMessages);
  838. $data = array();
  839. $messages = array();
  840. foreach($notifications as $message)
  841. {
  842. foreach($messageUserPairs[$message->id] as $userID)
  843. {
  844. $messages[$userID][] = $message->id;
  845. $data[$userID][] = $message;
  846. }
  847. }
  848. foreach($messages as $userID => $message)
  849. {
  850. $this->dao->delete()->from(TABLE_IM_MESSAGESTATUS)
  851. ->where('message')->in($message)
  852. ->andWhere('user')->eq($userID)
  853. ->exec();
  854. }
  855. return $data;
  856. }
  857. /**
  858. * Get offline notify.
  859. * @param $userID
  860. * @return array
  861. */
  862. public function getNotifyByUserID($userID)
  863. {
  864. $messageIDs = $this->dao->select('message')->from(TABLE_IM_MESSAGESTATUS)
  865. ->where('user')->eq($userID)
  866. ->andWhere('status')->eq('waiting')
  867. ->fetchPairs('message');
  868. if(empty($messageIDs)) return array();
  869. $messages = $this->getList('', $messageIDs, null, '', 'notify', false);
  870. if(empty($messages)) return array();
  871. $notifications = $this->formatNotify($messages);
  872. $messages = array();
  873. foreach($notifications as $message) $messages[] = $message->id;
  874. $this->dao->delete()->from(TABLE_IM_MESSAGESTATUS)
  875. ->where('message')->in($messages)
  876. ->andWhere('user')->eq($userID)
  877. ->exec();
  878. return $notifications;
  879. }
  880. /**
  881. * Foramt messages for notify.
  882. * @param object $messages
  883. * @access public
  884. * @return array
  885. */
  886. public function formatNotify($messages)
  887. {
  888. $notifications = array();
  889. foreach($messages as $message)
  890. {
  891. $data = new stdClass();
  892. $messageData = json_decode($message->data);
  893. $data->id = $message->id;
  894. $data->gid = $message->gid;
  895. $data->cgid = $message->cgid;
  896. $data->type = $message->type;
  897. $data->content = $message->deleted ? '' : $message->content;
  898. $data->date = strtotime($message->date);
  899. $data->contentType = $message->contentType;
  900. $data->title = $messageData->title;
  901. $data->subtitle = $messageData->subtitle;
  902. $data->url = $messageData->url;
  903. $data->actions = $messageData->actions;
  904. $data->sender = $messageData->sender;
  905. $data->users = $messageData->target;
  906. if($data->cgid != 'notification' && !empty($message->index)) $data->index = $message->index;
  907. $notifications[] = $data;
  908. }
  909. return $notifications;
  910. }
  911. /**
  912. * Create a bot welcome message.
  913. *
  914. * @param int $userID
  915. * @param bool $needUpdate
  916. * @access public
  917. * @return void
  918. */
  919. public function createXuanbotWelcomeNotify($userID, $needUpdate = false)
  920. {
  921. $sender = $this->loadModel('im')->bot->createDefaultBotSender();
  922. if($needUpdate) $this->createNotify(array($userID), $this->lang->im->bot->upgradeWelcome->title, '', $this->lang->im->bot->upgradeWelcome->content, 'text', $this->lang->im->bot->upgradeWelcome->link, array(), $sender);
  923. $this->createNotify(array($userID), $this->lang->im->bot->welcome->title, '', $this->lang->im->bot->welcome->content, 'text', $this->lang->im->bot->welcome->link, array(), $sender);
  924. }
  925. /**
  926. * Notify that detached conference is enabled.
  927. *
  928. * @access public
  929. * @return void
  930. */
  931. public function createDetachedConferenceEnableNotify()
  932. {
  933. $sender = $this->loadModel('im')->bot->createDefaultBotSender();
  934. $allUsers = $this->im->userGetList();
  935. $allUsers = array_keys($allUsers);
  936. $this->createNotify($allUsers, $this->lang->im->detachedConferenceUpgradeMessage->title, '', $this->lang->im->detachedConferenceUpgradeMessage->content, 'text', $this->lang->im->bot->upgradeWelcome->link, array(), $sender);
  937. }
  938. /**
  939. * Insert message for notify.
  940. * @param string $target
  941. * @param string $title
  942. * @param string $subtitle
  943. * @param string $content
  944. * @param string $contentType
  945. * @param string $url
  946. * @param array $actions
  947. * @param int $sender
  948. * @access public
  949. * @return bool
  950. */
  951. public function createNotify($target = '', $title = '', $subtitle = '', $content = '', $contentType = 'text', $url = '', $actions = array(), $sender = 0)
  952. {
  953. /* Check if target is a chat gid or a list of users. */
  954. if(is_array($target))
  955. {
  956. $cgid = 'notification';
  957. }
  958. else
  959. {
  960. $cgid = $target;
  961. $target = $this->dao->select('user')->from(TABLE_IM_CHATUSER)
  962. ->where('cgid')->eq($target)
  963. ->andWhere("(quit is null or quit = null)")
  964. ->fetchPairs('user');
  965. }
  966. $users = $this->loadModel('im')->user->getList('', $target);
  967. $info = array();
  968. $info['title'] = $title;
  969. $info['subtitle'] = $subtitle;
  970. $info['url'] = $url;
  971. $info['actions'] = $actions;
  972. $info['sender'] = $sender;
  973. $info['target'] = array_keys($users);
  974. $notify = new stdClass();
  975. $notify->gid = imModel::createGID();
  976. $notify->cgid = $cgid;
  977. $notify->user = 0;
  978. $notify->date = helper::now();
  979. $notify->type = 'notify';
  980. $notify->content = $content;
  981. $notify->contentType = $contentType;
  982. $notify->data = json_encode($info);
  983. $msgIndex = $this->dao->select('`lastMessageIndex` + 1 as msgIndex')->from(TABLE_IM_CHAT)->where('gid')->eq($cgid)->fetch('msgIndex');
  984. if(empty($msgIndex)) $msgIndex = 1;
  985. $notify->index = $msgIndex;
  986. $msgIndex = $this->insertMessageEnsuringUniqueIndex($this->encodeMessage($notify));
  987. if($msgIndex === false) return false;
  988. /* Get last insert id from dbh directly, as dao->lastInsertID() is not usable for records inserted by dbh. */
  989. $message = $this->dao->dbh->lastInsertId();
  990. if(empty($message)) return false;
  991. $this->dao->update(TABLE_IM_CHAT)
  992. ->set('lastActiveTime')->eq(helper::now())
  993. ->set('lastMessage')->eq($message)
  994. ->set('lastMessageIndex')->eq($msgIndex)
  995. ->where('gid')->eq($cgid)->exec();
  996. $this->saveStatus($info['target'], $message, 'waiting');
  997. return !dao::isError();
  998. }
  999. /**
  1000. * Add offline messages according to the gid of messages that failed to be sent.
  1001. * @param array $sendfail
  1002. * @access public
  1003. * @return bool
  1004. */
  1005. public function sendFailures($sendfail = array())
  1006. {
  1007. foreach($sendfail as $userID => $gid)
  1008. {
  1009. if(empty($gid)) continue;
  1010. $idList = $this->dao->select('id')->from(TABLE_IM_MESSAGE)->where('gid')->in($gid)->fetchPairs();
  1011. $messages = $this->getList('', $idList);
  1012. $this->saveOfflineList($messages, array($userID));
  1013. }
  1014. return !dao::isError();
  1015. }
  1016. /**
  1017. * Get message count for block.
  1018. *
  1019. * @access public
  1020. * @return object
  1021. */
  1022. public function getCountForBlock()
  1023. {
  1024. $masterTableTotal = $this->dao->select('COUNT(*) AS masterTableTotal')->from(TABLE_IM_MESSAGE)->where('deleted')->eq('0')->fetch('masterTableTotal');
  1025. $partitionsTotal = $this->dao->select('SUM(`count`) AS partitionsTotal')->from(TABLE_IM_CHAT_MESSAGE_INDEX)->fetch('partitionsTotal');
  1026. $dayCount = $this->dao->select("count(1) AS dayCount")->from(TABLE_IM_MESSAGE)->where('date')->gt(date('Y-m-d H:i', strtotime('-1 day')))->andWhere('deleted')->eq('0')->fetch('dayCount');
  1027. $hourCount = $this->dao->select("count(1) AS hourCount")->from(TABLE_IM_MESSAGE)->where('date')->gt(date('Y-m-d H:i', strtotime('-1 hour')))->andWhere('deleted')->eq('0')->fetch('hourCount');
  1028. $count = new stdClass();
  1029. $count->total = $masterTableTotal + ($partitionsTotal || 0);
  1030. $count->day = $dayCount;
  1031. $count->hour = $hourCount;
  1032. if(empty($count->total))
  1033. {
  1034. $count->total = 0;
  1035. $count->day = 0;
  1036. $count->hour = 0;
  1037. }
  1038. return $count;
  1039. }
  1040. /**
  1041. * Get all message tables.
  1042. *
  1043. * @access public
  1044. * @return array
  1045. */
  1046. public function getAllTables()
  1047. {
  1048. $tables = $this->dao->select('tableName')->from(TABLE_IM_MESSAGE_INDEX)->fetchAll();
  1049. foreach($tables as $key => $table) $tables[$key]->messages = '';
  1050. $master = new stdclass;
  1051. $master->tableName = TABLE_IM_MESSAGE;
  1052. $master->messages = '';
  1053. $tables[] = $master;
  1054. return $tables;
  1055. }
  1056. /**
  1057. * Get all message tables with cgid.
  1058. *
  1059. * @param string $cgid
  1060. * @access public
  1061. * @return array
  1062. */
  1063. public function getChatAllTables($cgid = '')
  1064. {
  1065. if($cgid == '') return array();
  1066. $tables = $this->dao->select('DISTINCT tableName')->from(TABLE_IM_CHAT_MESSAGE_INDEX)->fetchAll();
  1067. foreach($tables as $key => $table) $tables[$key]->messages = '';
  1068. $master = new stdclass;
  1069. $master->tableName = TABLE_IM_MESSAGE;
  1070. $master->messages = '';
  1071. $tables[] = $master;
  1072. return $tables;
  1073. }
  1074. /**
  1075. * Get message table names by message IDs.
  1076. *
  1077. * @param array $messageIDs
  1078. * @access public
  1079. * @return array
  1080. */
  1081. public function getTableByMessages($messageIDs)
  1082. {
  1083. $tables = array();
  1084. $indices = $this->dao->select('tableName,start,end')->from(TABLE_IM_MESSAGE_INDEX)->fetchAll('tableName');
  1085. $processedIDs = array();
  1086. foreach($indices as $index)
  1087. {
  1088. $min = $index->start;
  1089. $max = $index->end;
  1090. $ids = array_filter(
  1091. $messageIDs,
  1092. function($id) use ($min, $max)
  1093. {
  1094. return $id >= $min && $id <= $max;
  1095. }
  1096. );
  1097. if(!empty($ids))
  1098. {
  1099. $result = new stdclass();
  1100. $result->tableName = $index->tableName;
  1101. $result->messages = $ids;
  1102. $tables[$index->tableName] = $result;
  1103. $processedIDs = array_merge($processedIDs, $ids);
  1104. }
  1105. }
  1106. $unindexed = array_diff($messageIDs, $processedIDs);
  1107. if(!empty($unindexed))
  1108. {
  1109. $result = new stdclass();
  1110. $result->tableName = TABLE_IM_MESSAGE;
  1111. $result->messages = $unindexed;
  1112. $tables[TABLE_IM_MESSAGE] = $result;
  1113. }
  1114. return $tables;
  1115. }
  1116. /**
  1117. * Get chat message table names by message indexes.
  1118. *
  1119. * @param string $cgid
  1120. * @param array $indexes
  1121. * @access public
  1122. * @return array
  1123. */
  1124. public function getChatTablesByChatIndexes($cgid, $indexes)
  1125. {
  1126. if($cgid == '') return array();
  1127. $indexIds = $indexes;
  1128. $tables = array();
  1129. $indices = $this->dao->select('tableName,startIndex,endIndex')->from(TABLE_IM_CHAT_MESSAGE_INDEX)->where('gid')->eq($cgid)->fetchAll('tableName');
  1130. $processedIDs = array();
  1131. foreach($indices as $index)
  1132. {
  1133. $min = $index->startIndex;
  1134. $max = $index->endIndex;
  1135. $ids = array_filter(
  1136. $indexes,
  1137. function($id) use ($min, $max)
  1138. {
  1139. return $id >= $min && $id <= $max;
  1140. }
  1141. );
  1142. $indexes = array_diff($indexes, $ids);
  1143. if(!empty($ids))
  1144. {
  1145. $result = new stdclass();
  1146. $result->tableName = $index->tableName;
  1147. $result->messages = $ids;
  1148. $tables[$index->tableName] = $result;
  1149. $processedIDs = array_merge($processedIDs, $ids);
  1150. }
  1151. }
  1152. $unindexed = array_diff($indexIds, $processedIDs);
  1153. if(!empty($unindexed))
  1154. {
  1155. $result = new stdclass();
  1156. $result->tableName = TABLE_IM_MESSAGE;
  1157. $result->messages = $unindexed;
  1158. $tables[TABLE_IM_MESSAGE] = $result;
  1159. }
  1160. return $tables;
  1161. }
  1162. /**
  1163. * Get tables by start (and / or) end date).
  1164. *
  1165. * @param string $startDate
  1166. * @param string $endDate
  1167. * @access public
  1168. * @return array
  1169. */
  1170. public function getTablesByDateRange($startDate = '', $endDate = '')
  1171. {
  1172. $tables = $this->dao->select('tableName,startDate,endDate')->from(TABLE_IM_MESSAGE_INDEX)
  1173. ->where('1=1')
  1174. ->beginIF(!empty($startDate))->andWhere('endDate')->ge($startDate)->fi()
  1175. ->beginIF(!empty($endDate))->andWhere('startDate')->le($endDate)->fi()
  1176. ->fetchAll('tableName');
  1177. if(empty($tables)) $appendMaster = true;
  1178. /* If endDate is even later than the max endDate we have in the index, append the master table. */
  1179. elseif(!empty($endDate))
  1180. {
  1181. $maxEndDate = max(array_map(
  1182. function($t)
  1183. {
  1184. return $t->endDate;
  1185. },
  1186. $tables
  1187. ));
  1188. if($maxEndDate < $endDate) $appendMaster = true;
  1189. }
  1190. if(isset($appendMaster))
  1191. {
  1192. $master = new stdclass();
  1193. $master->tableName = TABLE_IM_MESSAGE;
  1194. $master->startDate = isset($maxEndDate) ? $maxEndDate : null;
  1195. $master->endDate = '9999-12-31 23:59:59';
  1196. $tables[] = $master;
  1197. }
  1198. return $tables;
  1199. }
  1200. /**
  1201. * Get chat tables by start (and / or) end date).
  1202. *
  1203. * @param string $cgid
  1204. * @param string $startDate
  1205. * @param string $endDate
  1206. * @access public
  1207. * @return array
  1208. */
  1209. public function getChatTablesByDateRange($cgid = '', $startDate = '', $endDate = '')
  1210. {
  1211. if($cgid == '') return array();
  1212. $tables = $this->dao->select('tableName,startDate,endDate')->from(TABLE_IM_CHAT_MESSAGE_INDEX)
  1213. ->where('gid')->eq($cgid)
  1214. ->beginIF(!empty($startDate))->andWhere('endDate')->ge($startDate)->fi()
  1215. ->beginIF(!empty($endDate))->andWhere('startDate')->le($endDate)->fi()
  1216. ->fetchAll('tableName');
  1217. if(empty($tables)) $appendMaster = true;
  1218. /* If endDate is even later than the max endDate we have in the index, append the master table. */
  1219. elseif(!empty($endDate))
  1220. {
  1221. $maxEndDate = max(array_map(
  1222. function($t)
  1223. {
  1224. return $t->endDate;
  1225. },
  1226. $tables
  1227. ));
  1228. if($maxEndDate < $endDate) $appendMaster = true;
  1229. }
  1230. if(isset($appendMaster))
  1231. {
  1232. $master = new stdclass();
  1233. $master->tableName = TABLE_IM_MESSAGE;
  1234. $master->startDate = isset($maxEndDate) ? $maxEndDate : null;
  1235. $master->endDate = '9999-12-31 23:59:59';
  1236. $tables[] = $master;
  1237. }
  1238. return $tables;
  1239. }
  1240. /**
  1241. * Get tables by gids of chats.
  1242. *
  1243. * @param array|string $cgids
  1244. * @access public
  1245. * @return array
  1246. */
  1247. public function getTablesByChats($cgids)
  1248. {
  1249. return $this->dao->select('DISTINCT tableName')->from(TABLE_IM_CHAT_MESSAGE_INDEX)
  1250. ->where('gid')->in($cgids)
  1251. ->fetchPairs();
  1252. }
  1253. /**
  1254. * Mark an ongoing partition opreation.
  1255. *
  1256. * @param bool $ongoing
  1257. * @access public
  1258. * @return bool true if successfully marked, otherwise there already is another ongoing opreation.
  1259. */
  1260. public function markOngoingPartition($ongoing)
  1261. {
  1262. $this->loadModel('setting');
  1263. $lastStatus = $this->setting->getItem("owner=system&module=common&section=partition&key=ongoing");
  1264. if($ongoing != $lastStatus)
  1265. {
  1266. $this->setting->setItem('system.common.partition.ongoing', $ongoing);
  1267. return true;
  1268. }
  1269. return false;
  1270. }
  1271. /**
  1272. * Check if message count in the master table exceeds twice the partition size.
  1273. *
  1274. * @access public
  1275. * @return bool true if partition is needed.
  1276. */
  1277. public function needPartition()
  1278. {
  1279. $currentID = $this->dao->select('id')->from(TABLE_IM_MESSAGE)->orderBy('id_desc')->limit(1)->fetch('id');
  1280. $lastIndexID = $this->dao->select('end')->from(TABLE_IM_MESSAGE_INDEX)->orderBy('end_desc')->limit(1)->fetch('end');
  1281. return $currentID > ($lastIndexID + 2 * $this->config->im->partition->messagePerTable);
  1282. }
  1283. /**
  1284. * Backup master message table.
  1285. *
  1286. * @param int $fromID
  1287. * @param int $toID
  1288. * @access public
  1289. * @return int count of message affected.
  1290. */
  1291. public function backupMasterTable($fromID, $toID = 0)
  1292. {
  1293. $insertStmt = $this->dao->insert(TABLE_IM_MESSAGE_BACKUP)->get();
  1294. $selectStmt = $this->dao->select('*')->from(TABLE_IM_MESSAGE)
  1295. ->where('id')->ge($fromID)
  1296. ->beginIF(!empty($toID))->andWhere('id')->le($toID)->fi()
  1297. ->get();
  1298. $stmt = substr($insertStmt, 0, -4) . $selectStmt;
  1299. return $this->dao->exec($stmt);
  1300. }
  1301. /**
  1302. * Delete a large amount of rows from im_message table
  1303. * by selecting the rest into a new table and replace current table with the new one.
  1304. *
  1305. * @param int $end
  1306. * @param int $start
  1307. * @access public
  1308. * @return bool
  1309. */
  1310. public function deleteFromMasterTable($end, $start = 0)
  1311. {
  1312. $tmpTable = str_replace(array('`', '-'), '', sprintf("%s_%s", TABLE_IM_MESSAGE, 'tmp_' . helper::today()));
  1313. $oldTable = str_replace(array('`', '-'), '', sprintf("%s_%s", TABLE_IM_MESSAGE, 'old_' . helper::today()));
  1314. $zdb = $this->app->loadClass('zdb');
  1315. $fields = $zdb->getTableFields(TABLE_IM_MESSAGE);
  1316. foreach($fields as $k => $f) if($f->default === "'\\''") $fields[$k]->default = ''; // fix wrong values from zdb of zentao
  1317. $zdb->createTable($tmpTable, $fields);
  1318. $insertStmt = $this->dao->insert($tmpTable)->get();
  1319. $selectStmt = $this->dao->select('*')->from(TABLE_IM_MESSAGE)
  1320. ->where('id')->gt($end)
  1321. ->beginIF($start)->orWhere('id')->lt($start)->fi()
  1322. ->get();
  1323. $stmt = substr($insertStmt, 0, -4) . $selectStmt;
  1324. $this->dao->exec($stmt);
  1325. $renameQuery = 'RENAME TABLE ' . TABLE_IM_MESSAGE . ' TO ' . $oldTable . '; ';
  1326. $renameQuery .= 'RENAME TABLE ' . $tmpTable . ' TO ' . TABLE_IM_MESSAGE . '; ';
  1327. $this->dao->exec($renameQuery);
  1328. $dropQuery = "DROP TABLE $oldTable;";
  1329. $this->dao->exec($dropQuery);
  1330. return !dao::isError();
  1331. }
  1332. /**
  1333. * Partition master message table into smaller tables.
  1334. *
  1335. * @access public
  1336. * @return bool
  1337. */
  1338. public function partitionTable()
  1339. {
  1340. /* Check if creation of a new partition is needed. */
  1341. if(!$this->needPartition()) return false;
  1342. /* Set memory limit to avoid OOMs. */
  1343. ini_set('memory_limit', -1);
  1344. /* Start a transaction. */
  1345. $this->dao->begin();
  1346. /* Create a new message table. */
  1347. $zdb = $this->app->loadClass('zdb');
  1348. $fields = $zdb->getTableFields(TABLE_IM_MESSAGE);
  1349. $fields['id']->extra = ''; // disable auto_increment.
  1350. $currentTable = $this->dao->select('id,end')->from(TABLE_IM_MESSAGE_INDEX)->orderBy('id_desc')->limit(1)->fetch();
  1351. $newTable = str_replace('`', '', sprintf("%s_%s", TABLE_IM_MESSAGE, ++$currentTable->id));
  1352. foreach($fields as $k => $f) if($f->default === "'\\''") $fields[$k]->default = ''; // fix wrong values from zdb of zentao
  1353. $zdb->createTable($newTable, $fields);
  1354. /* Select messages and insert into the new table. */
  1355. $insertStmt = $this->dao->insert($newTable)->get();
  1356. $selectStmt = $this->dao->select('*')->from(TABLE_IM_MESSAGE)
  1357. ->where('id')->gt($currentTable->end)
  1358. ->andWhere('id')->le($currentTable->end + $this->config->im->partition->messagePerTable)
  1359. ->get();
  1360. $stmt = substr($insertStmt, 0, -4) . $selectStmt;
  1361. $this->dao->exec($stmt);
  1362. /* Index the new table. */
  1363. $this->reindex($newTable);
  1364. /* Backup the master table. */
  1365. $this->backupMasterTable($currentTable->end + 1, $currentTable->end + $this->config->im->partition->messagePerTable);
  1366. /* Delete messages from master table on success. */
  1367. $this->deleteFromMasterTable($currentTable->end + $this->config->im->partition->messagePerTable);
  1368. /* End the transaction. */
  1369. $this->dao->commit();
  1370. return !dao::isError();
  1371. }
  1372. /**
  1373. * Index partitions.
  1374. *
  1375. * @param string $table table to index
  1376. * @access public
  1377. * @return void
  1378. */
  1379. public function reindex($table = '')
  1380. {
  1381. $MAXID = 'MAX(id)';
  1382. $MINID = 'MIN(id)';
  1383. $MAXINDEX = 'MAX(`index`)';
  1384. $MININDEX = 'MIN(`index`)';
  1385. $IDDATE = 'id,date';
  1386. $messageMeta = new stdclass();
  1387. $firstRecord = $this->dao->select($IDDATE)->from($table)->orderBy('id')->limit(1)->fetch();
  1388. $lastRecord = $this->dao->select($IDDATE)->from($table)->orderBy('id_desc')->limit(1)->fetch();
  1389. $chats = $this->dao->select('DISTINCT(cgid)')->from($table)->fetchPairs();
  1390. $messageMeta->tableName = $table;
  1391. $messageMeta->start = $firstRecord->id;
  1392. $messageMeta->end = $lastRecord->id;
  1393. $messageMeta->startDate = $firstRecord->date;
  1394. $messageMeta->endDate = $lastRecord->date;
  1395. $messageMeta->chats = ',' . join(',', $chats) . ',';
  1396. $this->dao->insert(TABLE_IM_MESSAGE_INDEX)->data($messageMeta)->exec();
  1397. $chatsInfo = $this->dao->select('cgid,MAX(id),MIN(id),MAX(`index`),MIN(`index`),count(*)')->from($table)->groupBy('cgid')->fetchAll();
  1398. $messages = array();
  1399. foreach($chatsInfo as $info)
  1400. {
  1401. $messages[] = $info->{$MAXID};
  1402. $messages[] = $info->{$MINID};
  1403. }
  1404. $messages = array_unique($messages);
  1405. $messageDates = $this->dao->select($IDDATE)->from($table)->where('id')->in($messages)->fetchPairs('id');
  1406. $values = array();
  1407. foreach($chatsInfo as $info)
  1408. {
  1409. $meta = array();
  1410. $meta[] = $table;
  1411. $meta[] = $info->cgid;
  1412. $meta[] = $info->{$MINID};
  1413. $meta[] = $info->{$MAXID};
  1414. $meta[] = $info->{$MININDEX};
  1415. $meta[] = $info->{$MAXINDEX};
  1416. $meta[] = $messageDates[$info->{$MINID}];
  1417. $meta[] = $messageDates[$info->{$MAXID}];
  1418. $meta[] = $info->{'count(*)'};
  1419. $data = "('" . join("','", $meta) . "')";
  1420. $values[] = $data;
  1421. }
  1422. $insertStmt = $this->dao->insert(TABLE_IM_CHAT_MESSAGE_INDEX)->get();
  1423. $insertStmt = substr($insertStmt, 0, -4) . '(`tableName`,`gid`,`start`,`end`,`startIndex`,`endIndex`,`startDate`,`endDate`,`count`) VALUES ' . join(',', $values);
  1424. $this->dao->exec($insertStmt);
  1425. }
  1426. /**
  1427. * codec string with rot47.
  1428. *
  1429. * @access public
  1430. * @param string $str string to be rot47
  1431. * @return string
  1432. */
  1433. public function codecWithRot47($str)
  1434. {
  1435. return strtr($str, '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~', 'PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO');
  1436. }
  1437. /**
  1438. * decode text with rot47 & base64.
  1439. *
  1440. * @access public
  1441. * @param string $text text to be rot47
  1442. * @return string
  1443. */
  1444. public function decodeText($text)
  1445. {
  1446. $rot47Encoded = $this->codecWithRot47($text);
  1447. return base64_decode($rot47Encoded);
  1448. }
  1449. /**
  1450. * decode chat messages.
  1451. *
  1452. * @access public
  1453. * @param array $messages messages to be decode
  1454. * @return array
  1455. */
  1456. public function decodeMessages($messages)
  1457. {
  1458. if(isset($this->config->xuanxuan->messageEncrypt) && ($this->config->xuanxuan->messageEncrypt == 'on') && commonModel::isLicensedMethod('im', 'messageEncrypt'))
  1459. {
  1460. $config = $this->config;
  1461. return array_map(function($msg) use ($config)
  1462. {
  1463. if(isset($msg->content) && isset($config->xuanxuan->lastUnEncryptMessageId) && intval($config->xuanxuan->lastUnEncryptMessageId) <= $msg->id)
  1464. {
  1465. $msg->content = $this->decodeText($msg->content);
  1466. }
  1467. return $msg;
  1468. }, $messages);
  1469. }
  1470. return $messages;
  1471. }
  1472. /**
  1473. * decode one chat message.
  1474. *
  1475. * @access public
  1476. * @param object $message message to be decode
  1477. * @return string
  1478. */
  1479. public function decodeMessage($message)
  1480. {
  1481. if(isset($this->config->xuanxuan->messageEncrypt) && ($this->config->xuanxuan->messageEncrypt == 'on') && commonModel::isLicensedMethod('im', 'messageEncrypt') && isset($this->config->xuanxuan->lastUnEncryptMessageId) && intval($this->config->xuanxuan->lastUnEncryptMessageId) <= $message->id)
  1482. {
  1483. $message->content = $this->decodeText($message->content);
  1484. }
  1485. return $message;
  1486. }
  1487. /**
  1488. * encode one chat message.
  1489. *
  1490. * @access public
  1491. * @param object $message message to be encode
  1492. * @return object
  1493. */
  1494. public function encodeMessage($message)
  1495. {
  1496. if(isset($this->config->xuanxuan->messageEncrypt) && ($this->config->xuanxuan->messageEncrypt == 'on') && commonModel::isLicensedMethod('im', 'messageEncrypt'))
  1497. {
  1498. $message->content = $this->codecWithRot47(base64_encode($message->content));
  1499. }
  1500. return $message;
  1501. }
  1502. /**
  1503. * get last message id
  1504. *
  1505. * @access public
  1506. * @return int
  1507. */
  1508. public function getLastMessageId()
  1509. {
  1510. $lastMessageId = $this->dao->select('id')
  1511. ->from(TABLE_IM_MESSAGE)
  1512. ->orderBy('id desc')
  1513. ->limit(1)
  1514. ->fetch('id');
  1515. if(!$lastMessageId)
  1516. {
  1517. $messagesCount = $this->dao->select('COUNT(*)')->from(TABLE_IM_MESSAGE)->fetch('COUNT(*)');
  1518. if($messagesCount == 0)
  1519. {
  1520. $messagesIdxCount = $this->dao->select('COUNT(*)')->from(TABLE_IM_MESSAGE_INDEX)->fetch('COUNT(*)');
  1521. if($messagesIdxCount > 0)
  1522. {
  1523. $lastMessageId = $this->dao->select('MAX(end)')->from(TABLE_IM_MESSAGE_INDEX)->fetch('MAX(end)');
  1524. }
  1525. else
  1526. {
  1527. $lastMessageId = 0;
  1528. }
  1529. }
  1530. }
  1531. return $lastMessageId;
  1532. }
  1533. }