1<?php 2 3use dokuwiki\Extension\CLIPlugin; 4use splitbrain\phpcli\Exception; 5use splitbrain\phpcli\Options; 6 7class cli_plugin_notification extends CLIPlugin 8{ 9 /** @var helper_plugin_notification_db */ 10 protected $db_helper; 11 12 /** @var helper_plugin_notification_cron */ 13 protected $cron_helper; 14 15 /** 16 * Initialize helper plugin 17 */ 18 public function __construct() 19 { 20 parent::__construct(); 21 $this->db_helper = plugin_load('helper', 'notification_db'); 22 $this->cron_helper = plugin_load('helper', 'notification_cron'); 23 } 24 25 /** 26 * Register options and arguments on the given $options object 27 * 28 * @param Options $options 29 * @return void 30 * @throws Exception 31 */ 32 protected function setup(Options $options) 33 { 34 $options->setHelp('Bulk notification dispatcher'); 35 $options->registerCommand('send', 'Send all due notifications'); 36 } 37 38 /** 39 * Your main program 40 * 41 * Arguments and options have been parsed when this is run 42 * 43 * @param Options $options 44 * @return void 45 */ 46 protected function main(Options $options) 47 { 48 $cmd = $options->getCmd(); 49 switch ($cmd) { 50 case 'send': 51 $this->sendNotifications(); 52 break; 53 default: 54 $this->error('No command provided'); 55 exit(1); 56 } 57 } 58 59 /** 60 * Check and send notifications 61 */ 62 protected function sendNotifications() 63 { 64 $sqlite = $this->db_helper->getDB(); 65 66 // get users from DB 67 $sql = 'SELECT user FROM cron_check'; 68 $result = $sqlite->query($sql); 69 $rows = $sqlite->res2arr($result); 70 if (!is_array($rows)) { 71 $this->info('Exiting: no users to notify found.'); 72 return; 73 } 74 // gather new notifications per user 75 foreach ($rows as $row) { 76 $user = $row['user']; 77 78 // update timestamp of cron check 79 $sqlite->query('UPDATE cron_check SET timestamp=? WHERE user=?', date('c'), $user); 80 81 $notification_data = $this->cron_helper->getNotificationData($user); 82 83 //no notifications - nothing to send 84 if (empty($notification_data['notifications'])) { 85 $this->info('No notifications at all for user ' . $user); 86 continue; 87 } 88 89 $new_notifications = $this->cron_helper->getNewNotifications($user, $notification_data); 90 // send email 91 // no notifications left - nothing to send 92 if (!$new_notifications) { 93 $this->info('No new notifications for user ' . $user); 94 continue; 95 } 96 97 list($text, $html) = $this->cron_helper->composeEmail($new_notifications); 98 if ($this->cron_helper->sendMail($user, $text, $html)) { 99 $this->cron_helper->storeSentNotifications($user, $new_notifications); 100 $this->info('Sent notification to ' . $user); 101 } else { 102 $this->error('Failed sending notification to ' . $user); 103 } 104 } 105 } 106} 107