protected function build($siteid, $slug, Request $request, Application $app)
 {
     $this->parameters = array('user' => null, 'eventCreated' => null, 'eventDupe' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $repo = new NewEventDraftRepository();
     $this->parameters['draft'] = $repo->loadBySlugForSite($slug, $this->parameters['site']);
     if (!$this->parameters['draft']) {
         $app->abort(404);
     }
     if ($this->parameters['draft']->getUserAccountId()) {
         $ur = new UserAccountRepository();
         $this->parameters['user'] = $ur->loadByID($this->parameters['draft']->getUserAccountId());
     }
     if ($this->parameters['draft']->getEventId()) {
         $er = new EventRepository();
         $this->parameters['eventCreated'] = $er->loadByID($this->parameters['draft']->getEventId());
     }
     if ($this->parameters['draft']->getWasExistingEventId()) {
         $er = new EventRepository();
         $this->parameters['eventDupe'] = $er->loadByID($this->parameters['draft']->getWasExistingEventId());
     }
 }
 protected function build($siteid, $slug, Request $request, Application $app)
 {
     $this->parameters = array('group' => null, 'venue' => null, 'country' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $er = new EventRepository();
     $this->parameters['event'] = $er->loadBySlug($this->parameters['site'], $slug);
     $this->parameters['eventisduplicateof'] = $this->parameters['event']->getIsDuplicateOfId() ? $er->loadById($this->parameters['event']->getIsDuplicateOfId()) : null;
     if (!$this->parameters['event']) {
         $app->abort(404);
     }
     if ($this->parameters['event']->getGroupId()) {
         $gr = new GroupRepository();
         $this->parameters['group'] = $gr->loadById($this->parameters['event']->getGroupId());
     }
     if ($this->parameters['event']->getCountryID()) {
         $cr = new CountryRepository();
         $this->parameters['country'] = $cr->loadById($this->parameters['event']->getCountryID());
     }
     if ($this->parameters['event']->getVenueID()) {
         $cr = new VenueRepository();
         $this->parameters['venue'] = $cr->loadById($this->parameters['event']->getVenueID());
     }
 }
 protected function build($id, Request $request, Application $app)
 {
     $this->parameters = array('group' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($id);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
 }
 function listForSite($siteid, Request $request, Application $app)
 {
     $sr = new SiteRepository();
     $site = $sr->loadById($siteid);
     if (!$site) {
         die("404");
     }
     $nedrb = new NewEventDraftRepositoryBuilder();
     $nedrb->setSite($site);
     $drafts = $nedrb->fetchAll();
     return $app['twig']->render('sysadmin/neweventdraftlist/index.html.twig', array('site' => $site, 'neweventdrafts' => $drafts));
 }
 function listForSite($siteid, Request $request, Application $app)
 {
     $sr = new SiteRepository();
     $site = $sr->loadById($siteid);
     if (!$site) {
         die("404");
     }
     $ilrb = new IncomingLinkRepositoryBuilder();
     $ilrb->setSite($site);
     $incominglinks = $ilrb->fetchAll();
     return $app['twig']->render('sysadmin/incominglinklist/forSite.html.twig', array('site' => $site, 'incominglinks' => $incominglinks));
 }
 function index($siteid, Request $request, Application $app)
 {
     $sr = new SiteRepository();
     $site = $sr->loadById($siteid);
     if (!$site) {
         die("404");
     }
     $grb = new GroupRepositoryBuilder();
     $grb->setSite($site);
     $groups = $grb->fetchAll();
     return $app['twig']->render('sysadmin/grouplist/index.html.twig', array('site' => $site, 'groups' => $groups));
 }
 function index($siteid, Request $request, Application $app)
 {
     $sr = new SiteRepository();
     $site = $sr->loadById($siteid);
     if (!$site) {
         die("404");
     }
     $rb = new CuratedListRepositoryBuilder();
     $rb->setSite($site);
     $curatedlists = $rb->fetchAll();
     return $app['twig']->render('sysadmin/curatedlistlist/index.html.twig', array('site' => $site, 'curatedlists' => $curatedlists));
 }
 function index($siteid, Request $request, Application $app)
 {
     $sr = new SiteRepository();
     $site = $sr->loadById($siteid);
     if (!$site) {
         die("404");
     }
     $mrb = new MediaRepositoryBuilder();
     $mrb->setIncludeDeleted(true);
     $mrb->setSite($site);
     $medias = $mrb->fetchAll();
     return $app['twig']->render('sysadmin/medialist/index.html.twig', array('site' => $site, 'medias' => $medias));
 }
 function index($siteid, Request $request, Application $app)
 {
     $sr = new SiteRepository();
     $site = $sr->loadById($siteid);
     if (!$site) {
         die("404");
     }
     $erb = new EventRepositoryBuilder();
     $erb->setSite($site);
     $erb->setOrderByStartAt(true);
     $events = $erb->fetchAll();
     return $app['twig']->render('sysadmin/eventlist/index.html.twig', array('site' => $site, 'events' => $events));
 }
 protected function build($siteid, $fieldid, Request $request, Application $app)
 {
     $this->parameters = array();
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $repo = new EventCustomFieldDefinitionRepository();
     $this->parameters['field'] = $repo->loadBySiteIDAndID($this->parameters['site']->getId(), $fieldid);
     if (!$this->parameters['field']) {
         $app->abort(404);
     }
 }
 protected function build($siteid, $id, Request $request, Application $app)
 {
     $this->parameters = array();
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $sr = new UserGroupRepository();
     $this->parameters['usergroup'] = $sr->loadByIdInSite($id, $this->parameters['site']);
     if (!$this->parameters['usergroup']) {
         $app->abort(404);
     }
 }
 protected function build($siteid, $slug, Request $request, Application $app)
 {
     $this->parameters = array('group' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $clr = new CuratedListRepository();
     $this->parameters['curatedlist'] = $clr->loadBySlug($this->parameters['site'], $slug);
     if (!$this->parameters['curatedlist']) {
         $app->abort(404);
     }
 }
 protected function build($siteid, $slug, Request $request, Application $app)
 {
     $this->parameters = array('group' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $vr = new VenueRepository();
     $this->parameters['venue'] = $vr->loadBySlug($this->parameters['site'], $slug);
     if (!$this->parameters['venue']) {
         $app->abort(404);
     }
     $this->parameters['venueisduplicateof'] = $this->parameters['venue']->getIsDuplicateOfId() ? $vr->loadById($this->parameters['venue']->getIsDuplicateOfId()) : null;
 }
 protected function build($siteid, $slug, Request $request, Application $app)
 {
     $this->parameters = array('area' => null, 'parentarea' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $ar = new AreaRepository();
     $this->parameters['area'] = $ar->loadBySlug($this->parameters['site'], $slug);
     if (!$this->parameters['area']) {
         $app->abort(404);
     }
     $this->parameters['areaisduplicateof'] = $this->parameters['area']->getIsDuplicateOfId() ? $ar->loadById($this->parameters['area']->getIsDuplicateOfId()) : null;
     if ($this->parameters['area']->getParentAreaId()) {
         $this->parameters['parentarea'] = $ar->loadById($this->parameters['area']->getParentAreaId());
     }
     $cr = new CountryRepository();
     $this->parameters['country'] = $this->parameters['area']->getCountryId() ? $cr->loadById($this->parameters['area']->getCountryId()) : null;
 }
 function __construct(ImportURLModel $importURL, SiteModel $site = null)
 {
     $this->importURL = $importURL;
     $this->realurl = $importURL->getUrl();
     if ($site) {
         $this->site = $site;
     } else {
         $siteRepo = new SiteRepository();
         $this->site = $siteRepo->loadById($importURL->getSiteId());
     }
     if ($importURL->getCountryId()) {
         $countryRepo = new CountryRepository();
         $this->country = $countryRepo->loadById($importURL->getCountryId());
     }
     if ($importURL->getAreaId()) {
         $areaRepo = new AreaRepository();
         $this->area = $areaRepo->loadById($importURL->getAreaId());
     }
     $groupRepository = new GroupRepository();
     $this->group = $groupRepository->loadById($importURL->getGroupId());
 }
 public function buildEvents(Application $app)
 {
     global $CONFIG;
     $repo = new SiteRepository();
     $site = $repo->loadById($this->site_id);
     $start = \TimeSource::getDateTime();
     $end = \TimeSource::getDateTime();
     $end->add(new \DateInterval("P" . ($this->days_into_future + 1) . "D"));
     $calendar = new \RenderCalendar();
     $calendar->setStartAndEnd($start, $end);
     $calendar->getEventRepositoryBuilder()->setSite($site);
     $calendar->getEventRepositoryBuilder()->setIncludeDeleted(true);
     $calData = $calendar->getData();
     $this->events = $calendar->getEvents();
     $this->event_text = $app['twig']->render('email/sendemail.eventview.calendar.txt.twig', array('data' => $calData, 'currentSite' => $site));
     if ($CONFIG->isDebug) {
         file_put_contents('/tmp/sendemail.eventview.calendar.txt', $this->event_text);
     }
     $this->event_html = $app['twig']->render('email/sendemail.eventview.calendar.html.twig', array('data' => $calData, 'currentSite' => $site));
     if ($CONFIG->isDebug) {
         file_put_contents('/tmp/sendemail.eventview.calendar.html', $this->event_html);
     }
 }
 function create(Request $request, Application $app)
 {
     $siteRepository = new SiteRepository();
     $form = $app['form.factory']->create(new CreateForm());
     if ('POST' == $request->getMethod()) {
         $form->bind($request);
         $data = $form->getData();
         $site = $siteRepository->loadBySlug($data['slug']);
         if ($site) {
             $form->addError(new FormError('That address is already taken'));
         }
         if ($form->isValid()) {
             $site = new SiteModel();
             $site->setSlug($data['slug']);
             $site->setTitle($data['title']);
             if ($data['read'] == 'public') {
                 $site->setIsListedInIndex(true);
                 $site->setIsWebRobotsAllowed(true);
             } else {
                 $site->setIsListedInIndex(false);
                 $site->setIsWebRobotsAllowed(false);
             }
             if ($data['write'] == 'public') {
                 $isAllUsersEditors = true;
             } else {
                 $isAllUsersEditors = false;
             }
             $site->setPromptEmailsDaysInAdvance($app['config']->newSitePromptEmailsDaysInAdvance);
             $countryRepository = new CountryRepository();
             $siteQuotaRepository = new SiteQuotaRepository();
             $siteRepository->create($site, $app['currentUser'], array($countryRepository->loadByTwoCharCode("GB")), $siteQuotaRepository->loadByCode($app['config']->newSiteHasQuotaCode), $isAllUsersEditors);
             if ($app['config']->hasSSL) {
                 return $app->redirect("https://" . $site->getSlug() . "." . $app['config']->webSiteDomainSSL);
             } else {
                 return $app->redirect("http://" . $site->getSlug() . "." . $app['config']->webSiteDomain);
             }
         }
     }
     $sites = array();
     $repo = new SiteRepository();
     if (isset($_COOKIE['sitesSeen'])) {
         foreach (explode(",", $_COOKIE['sitesSeen']) as $siteID) {
             if (intval($siteID) > 0) {
                 $site = $repo->loadById($siteID);
                 if ($site && !$site->getIsClosedBySysAdmin() && $site->getSlug() != $app['config']->siteSlugDemoSite) {
                     $sites[$site->getId()] = $site;
                 }
             }
         }
     }
     $srb = new SiteRepositoryBuilder();
     $srb->setIsOpenBySysAdminsOnly(true);
     $srb->setUserInterestedIn($app['currentUser']);
     foreach ($srb->fetchAll() as $site) {
         $sites[$site->getId()] = $site;
     }
     return $app['twig']->render('index/index/create.html.twig', array('form' => $form->createView(), 'sites' => $sites));
 }
 public static function run(Application $app, $verbose = false)
 {
     global $CONFIG;
     if ($verbose) {
         print "Starting " . date("c") . "\n";
     }
     $siteRepo = new SiteRepository();
     $groupRepo = new GroupRepository();
     $importURLRepo = new ImportURLRepository();
     $userRepo = new UserAccountRepository();
     $userWatchesSiteStopRepository = new UserWatchesSiteStopRepository();
     $userWatchesGroupStopRepository = new UserWatchesGroupStopRepository();
     $userAccountGeneralSecurityKeyRepository = new UserAccountGeneralSecurityKeyRepository();
     $userNotificationRepo = new UserNotificationRepository();
     /** @var usernotifications/UpcomingEventsUserNotificationType **/
     $userNotificationType = $app['extensions']->getCoreExtension()->getUserNotificationType('ImportURLExpired');
     $iurlBuilder = new ImportURLRepositoryBuilder();
     foreach ($iurlBuilder->fetchAll() as $importURL) {
         $site = $siteRepo->loadById($importURL->getSiteID());
         $group = $groupRepo->loadById($importURL->getGroupId());
         if ($verbose) {
             print date("c") . " ImportURL " . $importURL->getId() . " " . $importURL->getTitle() . " Site " . $site->getTitle() . "\n";
         }
         if ($site->getIsClosedBySysAdmin()) {
             if ($verbose) {
                 print " - site closed by sys admin\n";
             }
         } else {
             if (!$site->getIsFeatureImporter()) {
                 if ($verbose) {
                     print " - site feature disabled\n";
                 }
             } else {
                 if (!$group) {
                     if ($verbose) {
                         print " - no group - this should be impossible\n";
                     }
                 } else {
                     if ($group->getIsDeleted()) {
                         if ($verbose) {
                             print " - group deleted\n";
                         }
                     } else {
                         if ($importURL->getExpiredAt()) {
                             if ($verbose) {
                                 print " - expired\n";
                             }
                         } else {
                             if (!$importURL->getIsEnabled()) {
                                 if ($verbose) {
                                     print " - not enabled\n";
                                 }
                             } else {
                                 if ($importURL->isShouldExpireNow()) {
                                     if ($verbose) {
                                         print " - expiring\n";
                                     }
                                     $importURLRepo->expire($importURL);
                                     configureAppForSite($site);
                                     $uwsb = new UserWatchesSiteRepositoryBuilder();
                                     $uwsb->setSite($site);
                                     foreach ($uwsb->fetchAll() as $userWatchesSite) {
                                         $user = $userRepo->loadByID($userWatchesSite->getUserAccountId());
                                         if ($userWatchesSite->getIsWatching()) {
                                             /// Notification Class
                                             $userNotification = $userNotificationType->getNewNotification($user, $site);
                                             $userNotification->setImportURL($importURL);
                                             $userNotification->setGroup($group);
                                             ////// Save Notification Class
                                             $userNotificationRepo->create($userNotification);
                                             ////// Send Email
                                             if ($userNotification->getIsEmail()) {
                                                 configureAppForUser($user);
                                                 $userAccountGeneralSecurityKey = $userAccountGeneralSecurityKeyRepository->getForUser($user);
                                                 $userWatchesSiteStop = $userWatchesSiteStopRepository->getForUserAndSite($user, $site);
                                                 $message = \Swift_Message::newInstance();
                                                 $message->setSubject("Please confirm this is still valid: " . $importURL->getTitle());
                                                 $message->setFrom(array($CONFIG->emailFrom => $CONFIG->emailFromName));
                                                 $message->setTo($user->getEmail());
                                                 $messageText = $app['twig']->render('email/importURLExpired.watchesSite.txt.twig', array('user' => $user, 'importurl' => $importURL, 'stopCode' => $userWatchesSiteStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey()));
                                                 if ($CONFIG->isDebug) {
                                                     file_put_contents('/tmp/importURLExpired.watchesSite.txt', $messageText);
                                                 }
                                                 $message->setBody($messageText);
                                                 $messageHTML = $app['twig']->render('email/importURLExpired.watchesSite.html.twig', array('user' => $user, 'importurl' => $importURL, 'stopCode' => $userWatchesSiteStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey()));
                                                 if ($CONFIG->isDebug) {
                                                     file_put_contents('/tmp/importURLExpired.watchesSite.html', $messageHTML);
                                                 }
                                                 $message->addPart($messageHTML, 'text/html');
                                                 if (!$CONFIG->isDebug) {
                                                     $app['mailer']->send($message);
                                                 }
                                                 $userNotificationRepo->markEmailed($userNotification);
                                             }
                                         }
                                     }
                                     $uwgb = new UserWatchesGroupRepositoryBuilder();
                                     $uwgb->setGroup($group);
                                     foreach ($uwgb->fetchAll() as $userWatchesGroup) {
                                         $user = $userRepo->loadByID($userWatchesGroup->getUserAccountId());
                                         if ($userWatchesGroup->getIsWatching()) {
                                             /// Notification Class
                                             $userNotification = $userNotificationType->getNewNotification($user, $site);
                                             $userNotification->setImportURL($importURL);
                                             $userNotification->setGroup($group);
                                             ////// Save Notification Class
                                             $userNotificationRepo->create($userNotification);
                                             ////// Send Email
                                             if ($userNotification->getIsEmail()) {
                                                 $userAccountGeneralSecurityKey = $userAccountGeneralSecurityKeyRepository->getForUser($user);
                                                 $userWatchesGroupStop = $userWatchesGroupStopRepository->getForUserAndGroup($user, $group);
                                                 $message = \Swift_Message::newInstance();
                                                 $message->setSubject("Please confirm this is still valid: " . $importURL->getTitle());
                                                 $message->setFrom(array($CONFIG->emailFrom => $CONFIG->emailFromName));
                                                 $message->setTo($user->getEmail());
                                                 $messageText = $app['twig']->render('email/importURLExpired.watchesGroup.txt.twig', array('user' => $user, 'importurl' => $importURL, 'stopCode' => $userWatchesGroupStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey(), 'group' => $group));
                                                 if ($CONFIG->isDebug) {
                                                     file_put_contents('/tmp/importURLExpired.watchesGroup.txt', $messageText);
                                                 }
                                                 $message->setBody($messageText);
                                                 $messageHTML = $app['twig']->render('email/importURLExpired.watchesGroup.html.twig', array('user' => $user, 'importurl' => $importURL, 'stopCode' => $userWatchesGroupStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey(), 'group' => $group));
                                                 if ($CONFIG->isDebug) {
                                                     file_put_contents('/tmp/importURLExpired.watchesGroup.html', $messageHTML);
                                                 }
                                                 $message->addPart($messageHTML, 'text/html');
                                                 if (!$CONFIG->isDebug) {
                                                     $app['mailer']->send($message);
                                                 }
                                                 $userNotificationRepo->markEmailed($userNotification);
                                             }
                                         }
                                     }
                                 } else {
                                     $lastRunDate = $importURLRepo->getLastRunDateForImportURL($importURL);
                                     $nowDate = \TimeSource::getDateTime();
                                     if (!$lastRunDate || $lastRunDate->getTimestamp() < $nowDate->getTimestamp() - $CONFIG->importURLSecondsBetweenImports) {
                                         if ($verbose) {
                                             print " - importing\n";
                                         }
                                         $runner = new ImportURLRunner();
                                         $runner->go($importURL);
                                     } else {
                                         if ($verbose) {
                                             print " - already done on " . $lastRunDate->format("c") . "\n";
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($verbose) {
         print "Finished " . date("c") . "\n";
     }
 }
 public static function run(Application $app, $verbose = false)
 {
     global $CONFIG;
     if ($verbose) {
         print "Starting " . date("c") . "\n";
     }
     $userRepo = new UserAccountRepository();
     $siteRepo = new SiteRepository();
     $groupRepo = new GroupRepository();
     $eventRepo = new EventRepository();
     $userWatchesGroupRepository = new UserWatchesGroupRepository();
     $userWatchesGroupStopRepository = new UserWatchesGroupStopRepository();
     $userAccountGeneralSecurityKeyRepository = new UserAccountGeneralSecurityKeyRepository();
     $userNotificationRepo = new UserNotificationRepository();
     $userHasNoEditorPermissionsInSiteRepo = new UserHasNoEditorPermissionsInSiteRepository();
     $userPermissionsRepo = new UserPermissionsRepository($app['extensions']);
     /** @var usernotifications/UserWatchesGroupPromptNotificationType **/
     $userNotificationType = $app['extensions']->getCoreExtension()->getUserNotificationType('UserWatchesGroupPrompt');
     $b = new UserWatchesGroupRepositoryBuilder();
     foreach ($b->fetchAll() as $userWatchesGroup) {
         $user = $userRepo->loadByID($userWatchesGroup->getUserAccountId());
         $group = $groupRepo->loadById($userWatchesGroup->getGroupId());
         $site = $siteRepo->loadById($group->getSiteID());
         // This is not the most efficient as it involves DB access and the results might not be used. But it'll do for now.
         $userPermissions = $userPermissionsRepo->getPermissionsForUserInSite($user, $site, false, true);
         if ($verbose) {
             print date("c") . " User " . $user->getEmail() . " Site " . $site->getTitle() . " Group " . $group->getTitle() . "\n";
         }
         // UserWatchesGroupRepositoryBuilder() should only return instances where site is not also watched
         if ($site->getIsClosedBySysAdmin()) {
             if ($verbose) {
                 print " ... site is closed\n";
             }
         } else {
             if ($group->getIsDeleted()) {
                 if ($verbose) {
                     print " ... group is deleted\n";
                 }
             } else {
                 if ($userHasNoEditorPermissionsInSiteRepo->isUserInSite($user, $site)) {
                     if ($verbose) {
                         print " ... user does not have edit permissions allowed in site\n";
                     }
                 } else {
                     if (!$userPermissions->hasPermission("org.openacalendar", "CALENDAR_CHANGE")) {
                         if ($verbose) {
                             print " ... user does not have org.openacalendar/CALENDAR_CHANGE permission in site\n";
                         }
                         // Technically UserWatchesSiteRepositoryBuilder() should only return getIsWatching() == true but lets double check
                     } else {
                         if ($userWatchesGroup->getIsWatching()) {
                             if ($verbose) {
                                 print " ... searching for data\n";
                             }
                             $lastEvent = $eventRepo->loadLastNonDeletedNonImportedByStartTimeInGroupId($group->getId());
                             $data = $userWatchesGroup->getPromptEmailData($site, $lastEvent);
                             if ($data['moreEventsNeeded']) {
                                 if ($verbose) {
                                     print " ... found data\n";
                                 }
                                 ///// Notification Class
                                 $userNotification = $userNotificationType->getNewNotification($user, $site);
                                 $userNotification->setGroup($group);
                                 ////// Save Notification Class
                                 $userNotificationRepo->create($userNotification);
                                 ////// Send Email
                                 if ($userNotification->getIsEmail()) {
                                     $userWatchesGroupStop = $userWatchesGroupStopRepository->getForUserAndGroup($user, $group);
                                     configureAppForSite($site);
                                     configureAppForUser($user);
                                     $userAccountGeneralSecurityKey = $userAccountGeneralSecurityKeyRepository->getForUser($user);
                                     $unsubscribeURL = $CONFIG->getWebIndexDomainSecure() . '/you/emails/' . $user->getId() . '/' . $userAccountGeneralSecurityKey->getAccessKey();
                                     $lastEventsBuilder = new EventRepositoryBuilder();
                                     $lastEventsBuilder->setSite($site);
                                     $lastEventsBuilder->setGroup($group);
                                     $lastEventsBuilder->setOrderByStartAt(true);
                                     $lastEventsBuilder->setIncludeDeleted(false);
                                     $lastEventsBuilder->setIncludeImported(false);
                                     $lastEventsBuilder->setLimit($CONFIG->userWatchesGroupPromptEmailShowEvents);
                                     $lastEvents = $lastEventsBuilder->fetchAll();
                                     $message = \Swift_Message::newInstance();
                                     $message->setSubject("Any news about " . $group->getTitle() . "?");
                                     $message->setFrom(array($CONFIG->emailFrom => $CONFIG->emailFromName));
                                     $message->setTo($user->getEmail());
                                     $messageText = $app['twig']->render('email/userWatchesGroupPromptEmail.txt.twig', array('group' => $group, 'user' => $user, 'lastEvents' => $lastEvents, 'stopCode' => $userWatchesGroupStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey(), 'unsubscribeURL' => $unsubscribeURL));
                                     if ($CONFIG->isDebug) {
                                         file_put_contents('/tmp/userWatchesGroupPromptEmail.txt', $messageText);
                                     }
                                     $message->setBody($messageText);
                                     $messageHTML = $app['twig']->render('email/userWatchesGroupPromptEmail.html.twig', array('group' => $group, 'user' => $user, 'lastEvents' => $lastEvents, 'stopCode' => $userWatchesGroupStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey(), 'unsubscribeURL' => $unsubscribeURL));
                                     if ($CONFIG->isDebug) {
                                         file_put_contents('/tmp/userWatchesGroupPromptEmail.html', $messageHTML);
                                     }
                                     $message->addPart($messageHTML, 'text/html');
                                     $headers = $message->getHeaders();
                                     $headers->addTextHeader('List-Unsubscribe', $unsubscribeURL);
                                     if ($verbose) {
                                         print " ... sending\n";
                                     }
                                     if (!$CONFIG->isDebug) {
                                         $app['mailer']->send($message);
                                     }
                                     $userNotificationRepo->markEmailed($userNotification);
                                 }
                                 $userWatchesGroupRepository->markPromptEmailSent($userWatchesGroup, $data['checkTime']);
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($verbose) {
         print "Finished " . date("c") . "\n";
     }
 }
 public function setFromJSON($json)
 {
     if (isset($json->event)) {
         if (isset($json->event->summary)) {
             $this->summary = $json->event->summary;
         }
         if (isset($json->event->description)) {
             $this->description = $json->event->description;
         }
         if (isset($json->event->url)) {
             $this->url = $json->event->url;
         }
         $timezone = new \DateTimeZone($this->timezone);
         if (isset($json->event->start->str)) {
             $this->start_at = new \DateTime($json->event->start->str, $timezone);
         }
         if (isset($json->event->end->str)) {
             $this->end_at = new \DateTime($json->event->end->str, $timezone);
         }
         if (isset($json->event->country) && isset($json->event->country->code) && $json->event->country->code) {
             $countryRepo = new CountryRepository();
             // Delibrately setting NULL on failure so user gets an error message.
             $this->country = $countryRepo->loadByTwoCharCode($json->event->country->code);
             // TODO check allowed in this site
         }
         if (isset($json->event->timezone)) {
             // Delibrately setting NULL on failure so user gets an error message.
             $this->timezone = $this->country && in_array($json->event->timezone, $this->country->getTimezonesAsList()) ? $json->event->timezone : null;
         }
     }
     if (isset($json->site)) {
         $siteRepo = new SiteRepository();
         if (isset($json->site->id)) {
             $this->site = $siteRepo->loadById($json->site->id);
         }
         if (isset($json->site->slug)) {
             $this->site = $siteRepo->loadBySlug($json->site->slug);
         }
     }
     if (isset($json->user)) {
         $userRepo = new UserAccountRepository();
         if (isset($json->user->email)) {
             $this->user = $userRepo->loadByEmail($json->user->email);
         } else {
             if (isset($json->user->username)) {
                 $this->user = $userRepo->loadByUserName($json->user->username);
             }
         }
     }
     if (isset($json->group)) {
         $groupRepo = new GroupRepository();
         if (isset($json->group->slug) && $this->site) {
             $this->group = $groupRepo->loadBySlug($this->site, $json->group->slug);
         } else {
             if (isset($json->group->id)) {
                 $this->group = $groupRepo->loadById($json->group->id);
             }
         }
     }
 }
/**
 *
 * @package Core
 * @link http://ican.openacalendar.org/ OpenACalendar Open Source Software
 * @license http://ican.openacalendar.org/license.html 3-clause BSD
 * @copyright (c) 2013-2014, JMB Technology Limited, http://jmbtechnology.co.uk/
 * @author James Baster <*****@*****.**>
 */
if (!$CONFIG->isSingleSiteMode) {
    die("Single Site Mode Not Enabled");
}
$app->before(function (Request $request) use($app) {
    global $CONFIG, $WEBSESSION;
    # ////////////// Site
    $siteRepository = new SiteRepository();
    $site = $siteRepository->loadById($CONFIG->singleSiteID);
    if (!$site) {
        die("404 Not Found");
        // TODO
    }
    $app['twig']->addGlobal('currentSite', $site);
    $app['currentSite'] = $site;
    # ////////////// Site closed
    if ($app['currentSite']->getIsClosedBySysAdmin()) {
        $app['twig']->addGlobal('currentUserInSite', null);
        $app['twig']->addGlobal('currentUserCanAdminSite', false);
        $app['twig']->addGlobal('currentUserCanEditSite', false);
        return new Response($app['twig']->render('site/closed_by_sys_admin.html.twig', array()));
    }
    # ////////////// Timezone
    $timezone = "";
$environment = $argv[2];
# change to directory of the ini file so all paths to intro files can be relative to that.
if (substr($argv[1], 0, 1) == '/') {
    $configDataDir = dirname($argv[1]);
} else {
    $configDataDir = getcwd() . '/' . dirname($argv[1]);
}
$thisconfig = new IniConfigWithEnvironment($environment, $argv[1]);
foreach (array('SiteID', 'Subject', 'FromEmail', 'FromName', 'TimeZone', 'IntroTXTFile', 'IntroHTMLFile') as $key) {
    if (!$thisconfig->hasValue($key)) {
        die("NO CONFIG " . $key . " ?\n");
    }
}
// ######################################################### Load site, build query
$siteRepository = new SiteRepository();
$site = $siteRepository->loadById($thisconfig->get('SiteID'));
if (!$site) {
    die("NO SITE?\n");
}
$calendar = new \RenderCalendar();
$calendar->getEventRepositoryBuilder()->setSite($site);
$calendar->getEventRepositoryBuilder()->setIncludeDeleted(false);
// ######################################################### Set Start and End
$start = \TimeSource::getDateTime();
$start->setTime(0, 0, 0);
$end = \TimeSource::getDateTime();
$end->setTime(0, 0, 0);
if ($thisconfig->hasValue("Month") && $thisconfig->hasValue("Year")) {
    // Options for setting end; by a set month and year
    if ($thisconfig->get('Month') == 12) {
        $end->setDate($thisconfig->get('Year') + 1, 1, 1);
 protected function run()
 {
     global $CONFIG;
     $userRepo = new UserAccountRepository();
     $siteRepo = new SiteRepository();
     $eventRepo = new EventRepository();
     $userWatchesSiteRepository = new UserWatchesSiteRepository();
     $userWatchesSiteStopRepository = new UserWatchesSiteStopRepository();
     $userAccountGeneralSecurityKeyRepository = new UserAccountGeneralSecurityKeyRepository();
     $userNotificationRepo = new UserNotificationRepository();
     /** @var usernotifications/UserWatchesSiteGroupPromptNotificationType **/
     $userNotificationType = $this->app['extensions']->getCoreExtension()->getUserNotificationType('UserWatchesSiteGroupPrompt');
     $b = new UserWatchesSiteRepositoryBuilder();
     foreach ($b->fetchAll() as $userWatchesSite) {
         $user = $userRepo->loadByID($userWatchesSite->getUserAccountId());
         $site = $siteRepo->loadById($userWatchesSite->getSiteId());
         $siteRepo->loadLegacyFeaturesOnSite($site);
         // to avoid flooding user we only send one group email per run
         $anyGroupNotificationsSent = false;
         $this->logVerbose(" User " . $user->getEmail() . " Site " . $site->getTitle());
         if ($site->getIsClosedBySysAdmin()) {
             $this->logVerbose(" ... site is closed");
             // Technically UserWatchesSiteRepositoryBuilder() should only return getIsWatching() == true but lets double check
         } else {
             if ($userWatchesSite->getIsWatching()) {
                 $groupRepoBuilder = new GroupRepositoryBuilder();
                 $groupRepoBuilder->setSite($site);
                 $groupRepoBuilder->setIncludeDeleted(false);
                 foreach ($groupRepoBuilder->fetchAll() as $group) {
                     if (!$anyGroupNotificationsSent) {
                         $this->logVerbose(" ... searching group " . $group->getSlug() . " for data");
                         $lastEvent = $eventRepo->loadLastNonDeletedNonImportedByStartTimeInGroupId($group->getId());
                         $data = $userWatchesSite->getGroupPromptEmailData($site, $group, $lastEvent);
                         if ($data['moreEventsNeeded']) {
                             $this->logVerbose(" ... found data ");
                             ///// Notification Class
                             $userNotification = $userNotificationType->getNewNotification($user, $site);
                             $userNotification->setGroup($group);
                             ////// Save Notification Class
                             $userNotificationRepo->create($userNotification);
                             ////// Send Email
                             if ($userNotification->getIsEmail()) {
                                 $userWatchesSiteStop = $userWatchesSiteStopRepository->getForUserAndSite($user, $site);
                                 configureAppForSite($site);
                                 configureAppForUser($user);
                                 $userAccountGeneralSecurityKey = $userAccountGeneralSecurityKeyRepository->getForUser($user);
                                 $unsubscribeURL = $CONFIG->getWebIndexDomainSecure() . '/you/emails/' . $user->getId() . '/' . $userAccountGeneralSecurityKey->getAccessKey();
                                 $lastEventsBuilder = new EventRepositoryBuilder();
                                 $lastEventsBuilder->setSite($site);
                                 $lastEventsBuilder->setGroup($group);
                                 $lastEventsBuilder->setOrderByStartAt(true);
                                 $lastEventsBuilder->setIncludeDeleted(false);
                                 $lastEventsBuilder->setIncludeImported(false);
                                 $lastEventsBuilder->setLimit($CONFIG->userWatchesSiteGroupPromptEmailShowEvents);
                                 $lastEvents = $lastEventsBuilder->fetchAll();
                                 $message = \Swift_Message::newInstance();
                                 $message->setSubject("Any news about " . $group->getTitle() . "?");
                                 $message->setFrom(array($CONFIG->emailFrom => $CONFIG->emailFromName));
                                 $message->setTo($user->getEmail());
                                 $messageText = $this->app['twig']->render('email/userWatchesSiteGroupPromptEmail.txt.twig', array('user' => $user, 'group' => $group, 'lastEvents' => $lastEvents, 'stopCode' => $userWatchesSiteStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey(), 'unsubscribeURL' => $unsubscribeURL));
                                 if ($CONFIG->isDebug) {
                                     file_put_contents('/tmp/userWatchesSiteGroupPromptEmail.txt', $messageText);
                                 }
                                 $message->setBody($messageText);
                                 $messageHTML = $this->app['twig']->render('email/userWatchesSiteGroupPromptEmail.html.twig', array('user' => $user, 'group' => $group, 'lastEvents' => $lastEvents, 'stopCode' => $userWatchesSiteStop->getAccessKey(), 'generalSecurityCode' => $userAccountGeneralSecurityKey->getAccessKey(), 'unsubscribeURL' => $unsubscribeURL));
                                 if ($CONFIG->isDebug) {
                                     file_put_contents('/tmp/userWatchesSiteGroupPromptEmail.html', $messageHTML);
                                 }
                                 $message->addPart($messageHTML, 'text/html');
                                 $headers = $message->getHeaders();
                                 $headers->addTextHeader('List-Unsubscribe', $unsubscribeURL);
                                 $this->logVerbose(" ... sending");
                                 if (!$CONFIG->isDebug) {
                                     $this->app['mailer']->send($message);
                                 }
                                 $userNotificationRepo->markEmailed($userNotification);
                             }
                             $userWatchesSiteRepository->markGroupPromptEmailSent($userWatchesSite, $group, $data['checkTime']);
                             $anyGroupNotificationsSent = true;
                         }
                     }
                 }
             }
         }
     }
     return array('result' => 'ok');
 }