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