Generate the occurrences for each monthly recurring event.

@param  EventInterface[]		$events
@param  \DateTime			$fromDate
@param  \DateTime			$toDate
@param  int|null				$limit
@return EventInterface[]
485426
public function generateOccurrences(Array $events, \DateTime $fromDate, \DateTime $toDate, $limit = null)
	{
		$return = array();
		$object = $this;

		$monthlyEvents = array_filter($events, function ($event) use ($object) {
			return $event->getRecurrenceType() === $object->getLabel();
		});

		foreach ($monthlyEvents as $monthlyEvent) {
			$monthlyEventTime = $monthlyEvent->getStartDate()->format('H:i:s');

			$monthlyDate = $monthlyEvent->getStartDate()->format('d');

			$start = $fromDate > $monthlyEvent->getStartDate()
				? clone($fromDate)
				: clone($monthlyEvent->getStartDate());

			$startMarker = clone($start);
			$startMarker->setDate($start->format('Y'), $start->format('m'), 1);

			$maxEndMarker = clone($startMarker);
			$maxEndMarker->modify($this->limit);

			$endMarker = $monthlyEvent->getRecurrenceUntil()
				? min($monthlyEvent->getRecurrenceUntil(), clone($toDate), $maxEndMarker)
				: min(clone($toDate), $maxEndMarker);

			$actualEndMarker = clone($endMarker);

			// The DatePeriod class does not actually include the end date so you have to increment it first
			$endMarker->modify('+1 day');

			$dateInterval = new \DateInterval('P1M');
			$datePeriod = new \DatePeriod($startMarker, $dateInterval, $endMarker);

			$limitMarker = 0;

			foreach ($datePeriod as $date) {
				if (($limit and ($limit === $limitMarker)) or ($date > $actualEndMarker)) {
					break;
				}

				if ($monthlyDate > $date->format('t')) {
					continue;
				}

				$date->setDate($date->format('Y'), $date->format('m'), sprintf('%2d', $monthlyDate));

				$newMonthlyEvent = clone($monthlyEvent);
				$newStartDate = new \DateTime($date->format('Y-m-d').' '.$monthlyEventTime);

				if ($newStartDate < $startMarker) {
					continue;
				}

				$duration = $newMonthlyEvent->getDuration();

				$newMonthlyEvent->setStartDate($newStartDate);

				$newEndDate = clone($newStartDate);
				$newEndDate->add($duration);
				
				$newMonthlyEvent->setEndDate($newEndDate);
				$newMonthlyEvent->setRecurrenceType();

				$return[] = $newMonthlyEvent;

				$limit and $limitMarker++;
			}
		}

		return $return;
	}
1298767
public static function get_calendar_events($events = array(), $options = array()) {
        global $SITE, $DB, $USER;

        // Parameter validation.
        $params = self::validate_parameters(self::get_calendar_events_parameters(), array('events' => $events, 'options' => $options));
        $funcparam = array('courses' => array(), 'groups' => array(), 'categories' => array());
        $hassystemcap = has_capability('moodle/calendar:manageentries', context_system::instance());
        $warnings = array();
        $coursecategories = array();

        // Let us find out courses and their categories that we can return events from.
        if (!$hassystemcap) {
            $courseobjs = enrol_get_my_courses();
            $courses = array_keys($courseobjs);

            $coursecategories = array_flip(array_map(function($course) {
                return $course->category;
            }, $courseobjs));

            foreach ($params['events']['courseids'] as $id) {
               try {
                    $context = context_course::instance($id);
                    self::validate_context($context);
                    $funcparam['courses'][] = $id;
                } catch (Exception $e) {
                    $warnings[] = array(
                        'item' => 'course',
                        'itemid' => $id,
                        'warningcode' => 'nopermissions',
                        'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
                    );
                }
            }
        } else {
            $courses = $params['events']['courseids'];
            $funcparam['courses'] = $courses;

            if (!empty($courses)) {
                list($wheresql, $sqlparams) = $DB->get_in_or_equal($courses);
                $wheresql = "id $wheresql";
                $coursecategories = array_flip(array_map(function($course) {
                    return $course->category;
                }, $DB->get_records_select('course', $wheresql, $sqlparams, '', 'category')));
            }
        }

        // Let us findout groups that we can return events from.
        if (!$hassystemcap) {
            $groups = groups_get_my_groups();
            $groups = array_keys($groups);
            foreach ($params['events']['groupids'] as $id) {
                if (in_array($id, $groups)) {
                    $funcparam['groups'][] = $id;
                } else {
                    $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group');
                }
            }
        } else {
            $groups = $params['events']['groupids'];
            $funcparam['groups'] = $groups;
        }

        $categories = array();
        if ($hassystemcap || !empty($courses)) {
            // Use the category id as the key in the following array. That way we do not have to remove duplicates and
            // have a faster lookup later.
            $categories = [];

            if (!empty($params['events']['categoryids'])) {
                $catobjs = \core_course_category::get_many(
                    array_merge($params['events']['categoryids'], array_keys($coursecategories)));
                foreach ($catobjs as $catobj) {
                    if (isset($coursecategories[$catobj->id]) ||
                            has_capability('moodle/category:manage', $catobj->get_context())) {
                        // If the user has access to a course in this category or can manage the category,
                        // then they can see all parent categories too.
                        $categories[$catobj->id] = true;
                        foreach ($catobj->get_parents() as $catid) {
                            $categories[$catid] = true;
                        }
                    }
                }
                $funcparam['categories'] = array_keys($categories);
            } else {
                // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
                $calcatcache = cache::make('core', 'calendar_categories');
                // Do not use cache if the user has the system capability as $coursecategories might not represent the
                // courses the user is enrolled in.
                $categories = (!$hassystemcap) ? $calcatcache->get('site') : false;
                if ($categories !== false) {
                    // The ids are stored in a list in the cache.
                    $funcparam['categories'] = $categories;
                    $categories = array_flip($categories);
                } else {
                    $categories = [];
                    foreach (\core_course_category::get_all() as $category) {
                        if (isset($coursecategories[$category->id]) ||
                                has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
                            // If the user has access to a course in this category or can manage the category,
                            // then they can see all parent categories too.
                            $categories[$category->id] = true;
                            foreach ($category->get_parents() as $catid) {
                                $categories[$catid] = true;
                            }
                        }
                    }
                    $funcparam['categories'] = array_keys($categories);
                    if (!$hassystemcap) {
                        $calcatcache->set('site', $funcparam['categories']);
                    }
                }
            }
        }

        // Do we need user events?
        if (!empty($params['options']['userevents'])) {
            $funcparam['users'] = array($USER->id);
        } else {
            $funcparam['users'] = false;
        }

        // Do we need site events?
        if (!empty($params['options']['siteevents'])) {
            $funcparam['courses'][] = $SITE->id;
        }

        // We treat 0 and null as no end.
        if (empty($params['options']['timeend'])) {
            $params['options']['timeend'] = PHP_INT_MAX;
        }

        // Event list does not check visibility and permissions, we'll check that later.
        $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
                $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
                $params['options']['ignorehidden'], $funcparam['categories']);

        // WS expects arrays.
        $events = array();

        // We need to get events asked for eventids.
        if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
            $eventlist += $eventsbyid;
        }
        foreach ($eventlist as $eventid => $eventobj) {
            $event = (array) $eventobj;
            // Description formatting.
            $calendareventobj = new calendar_event($event);
            list($event['description'], $event['format']) = $calendareventobj->format_external_text();

            if ($hassystemcap) {
                // User can see everything, no further check is needed.
                $events[$eventid] = $event;
            } else if (!empty($eventobj->modulename)) {
                $courseid = $eventobj->courseid;
                if (!$courseid) {
                    if (!$calendareventobj->context || !($context = $calendareventobj->context->get_course_context(false))) {
                        continue;
                    }
                    $courseid = $context->instanceid;
                }
                $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename);
                if (!empty($instances[$eventobj->instance]->uservisible)) {
                    $events[$eventid] = $event;
                }
            } else {
                // Can the user actually see this event?
                $eventobj = calendar_event::load($eventobj);
                if ((($eventobj->courseid == $SITE->id) && (empty($eventobj->categoryid))) ||
                            (!empty($eventobj->categoryid) && isset($categories[$eventobj->categoryid])) ||
                            (!empty($eventobj->groupid) && in_array($eventobj->groupid, $groups)) ||
                            (!empty($eventobj->courseid) && in_array($eventobj->courseid, $courses)) ||
                            ($USER->id == $eventobj->userid) ||
                            (calendar_edit_event_allowed($eventobj))) {
                    $events[$eventid] = $event;
                } else {
                    $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
                }
            }
        }
        return array('events' => $events, 'warnings' => $warnings);
    }
1202231
public static function coming_events($from = false)
    {
        $time = ($from ? strtotime($from) : mktime(0, 0, 0, date('m'), date('d'), date('Y')));
        $sql = "(StartDateTime >= '".date('Y-m-d', $time)." 00:00:00')";
        $events = PublicEvent::get()->where($sql);
        return $events;
    }
979513
public static Generator<DateTime> pastDates(@Nonnull DateTime from) {
        return new RandomJodaDateTimeGenerator(ofInstance(checkNotNull(from)), new DurationFromNow(ZERO_DURAION));
    }
736896
public function getAllEventsHook($allEvents, $calendars, $start, $end, $module)
	{
		if (!($permissions = static::checkLogin()) || !in_array('beModules', $permissions)) {
			return $allEvents;
		}

		foreach ($allEvents as $key => $days) {
			foreach ($days as $day => $events) {
				foreach ($events as $index => $event) {
					$allEvents[$key][$day][$index]['class'] =
						(empty($event['class']) ? '' : $event['class'])
						. ' rsfh-event-' . $event['id'];
				}
			}
		}

		return $allEvents;
	}
1134986
public function setCalendarEventData(array $data = [], ?EntityInterface $calendar = null): array
    {
        $result = [
            'CalendarEvents' => [],
        ];

        $result['CalendarEvents'] = $data;
        if (!empty($data['recurrence'])) {
            $recurrence = $this->setRRuleConfiguration($data['recurrence']);
            $result['CalendarEvents']['is_recurring'] = true;
            $result['CalendarEvents']['recurrence'] = $recurrence;
        }

        if (!empty($data['attendees_ids'])) {
            $result['calendar_attendees']['_ids'] = $data['attendees_ids'];
            unset($result['CalendarEvents']['attendees_ids']);
        }

        if (empty($data['title']) && $calendar instanceof EntityInterface) {
            $result['CalendarEvents']['title'] = $this->setEventTitle($data, $calendar);
        }

        return $result;
    }
561305
public static function monthListBetweenDate($startDate, $endDate)
    {
		$output = [];
		$time   = strtotime($startDate);
		$last   = date('m-Y', strtotime($endDate));

		do {
		    $month = date('m-Y', $time);
		    $total = date('t', $time);

		    $output[] = [
		        'month' => $month,
		        'total' => $total,
		    ];

		    $time = strtotime('+1 month', $time);
		} while ($month != $last);
    }
647116
public function getDateRange()
    {
        $fromDate = $this->request->getParam('from', self::DEFAULT_FROM_DATE);
        if ($fromDate !== self::DEFAULT_FROM_DATE) {
            $fromDate = base64_decode($fromDate);
        }
        $toDate = $this->request->getParam('to', self::DEFAULT_TO_DATE);
        if ($toDate !== self::DEFAULT_TO_DATE) {
            $toDate = base64_decode($toDate);
        }

        $dateRange = [
            'from' => $this->createDateFromText($fromDate),
            'to'   => $this->createDateFromText($toDate),
        ];

        return $this->sortDateRange($dateRange);
    }
1267243
public function getLikeCountByDate($from, $to = null): int
    {
        return Like::countByDate($this, $from, $to);
    }
1276793
private DateTime parseToDate(String toDate) {
        // Default to now
        return parseDate(toDate, new DateTime().withZone(DateTimeZone.UTC), false);
    }
855762
public static function getEvenementsLies($id, $date, $date2)
    {
        global $config;
        $req = "
            SELECT idEvenement
            FROM _evenementPersonne
            WHERE idPersonne = '".$id."'
        ";
        $res = $config->connexionBdd->requete($req);
        $events=array();
        while ($event = mysql_fetch_assoc($res)) {
            $events[]=$event;
        }
        $return=array();
        foreach ($events as $event) {
            $idEvent=$event["idEvenement"];
            $req = "
                SELECT dateDebut
                FROM historiqueEvenement
                WHERE idEvenement = '".$idEvent."'
                ORDER BY `idHistoriqueEvenement` DESC
            ";
            $res = $config->connexionBdd->requete($req);
            $dateEvent = mysql_fetch_object($res)->dateDebut;
            if (($dateEvent >= $date && $dateEvent < $date2) || ($date2==3000 && $dateEvent=="0000-00-00")) {
                $return[] = $idEvent;
            }
        }
        return $return;
    }
679371
function &diff( $fromData, $toData)
    {
        if ( !$this->DiffEngineInstance )
            return null;

        $differ =& $this->DiffEngineInstance;
        $diffObject = $differ->createDifferenceObject( $fromData, $toData );
        return $diffObject;
    }
36169
public function generateOccurrences(Array $events, \DateTime $fromDate, \DateTime $toDate, $limit = null)
	{
		$return = array();
		$object = $this;

		$weeklyEvents = array_filter($events, function ($event) use ($object) {
			return $event->getRecurrenceType() === $object->getLabel();
		});

		foreach ($weeklyEvents as $weeklyEvent) {
			$weeklyEventTime = $weeklyEvent->getStartDate()->format('H:i:s');

			// Retrieve the day of the week that the event takes place on
			$day = $weeklyEvent->getStartDate()->format('w');

			$startMarker = $fromDate > $weeklyEvent->getStartDate()
				? clone($fromDate)
				: clone($weeklyEvent->getStartDate());

			while ($startMarker->format('w') != $day) {
				$startMarker->modify('+1 day');
			}

			$maxEndMarker = clone($startMarker);
			$maxEndMarker->modify($this->limit);

			$endMarker = $weeklyEvent->getRecurrenceUntil()
				? min($weeklyEvent->getRecurrenceUntil(), clone($toDate), $maxEndMarker)
				: min(clone($toDate), $maxEndMarker);

			$actualEndMarker = clone($endMarker);

			// The DatePeriod class does not actually include the end date so you have to increment it first
			$endMarker->modify('+1 day');

			$dateInterval = new \DateInterval('P1W');
			$datePeriod = new \DatePeriod($startMarker, $dateInterval, $endMarker);

			$limitMarker = 0;

			foreach ($datePeriod as $date) {
				if (($limit and ($limit === $limitMarker)) or ($date > $actualEndMarker)) {
					break;
				}

				$newWeeklyEvent = clone($weeklyEvent);
				$newStartDate = new \DateTime($date->format('Y-m-d').' '.$weeklyEventTime);

				if ($newStartDate < $startMarker) {
					continue;
				}

				$duration = $newWeeklyEvent->getDuration();

				$newWeeklyEvent->setStartDate($newStartDate);
				
				$newEndDate = clone($newStartDate);
				$newEndDate->add($duration);

				$newWeeklyEvent->setEndDate($newEndDate);
				$newWeeklyEvent->setRecurrenceType();

				$return[] = $newWeeklyEvent;

				$limit and $limitMarker++;
			}
		}

		return $return;
	}
640701
public function sqlDelete(
		$from,
		$where,
		array $where_params,
		$limit = null
	) {
		$sql = $this->queryBuilder->buildDelete($from, $where, $limit);
		$query = $this->database->prepare($sql);
		$query->execute($where_params);
		$this->addQuery($query->queryString, $where_params);
		return $query->rowCount();
	}
1369176
private function constructFilter(\ECL\SymbolTable $table, $filters, $date_field, $from, $to) {
        $filters = $this->resolveFilter($table, $filters);

        // Optionally set date range filter.
        if(!is_null($date_field)) {
            $filter = ['range' => [$date_field => [
                'gte' => $from,
                'lt' => $to,
                'format' => 'epoch_second',
            ]]];
            if(count($filters) > 0) {
                $filters = ['bool' => ['filter' => [$filters, $filter]]];
            } else {
                $filters = $filter;
            }
        }

        return $filters;
    }
1221905
public function read($offset = null, $limit = 10)
    {
        if ($offset === null) {
            $offset = (((int) (($this->getLastRowId() - 1) / $limit)) * $limit) + 1;
        }

        $sql = 'SELECT * FROM ' . $this->table
            . ' WHERE id >= ?'
            . ' ORDER BY id ASC'
            . ' LIMIT ?';

        $events = [];

        $stmt = $this->connection->prepare($sql);
        $stmt->bindValue(1, $offset, Type::INTEGER);
        $stmt->bindValue(2, $limit, Type::INTEGER);
        $stmt->execute();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $events[$row['id']] = $this->fromArray($row);
        }

        return $events;
    }
863928
public static function create_calendar_events($events) {
        global $DB, $USER;

        // Parameter validation.
        $params = self::validate_parameters(self::create_calendar_events_parameters(), array('events' => $events));

        $transaction = $DB->start_delegated_transaction();
        $return = array();
        $warnings = array();

        foreach ($params['events'] as $event) {

            // Let us set some defaults.
            $event['userid'] = $USER->id;
            $event['modulename'] = '';
            $event['instance'] = 0;
            $event['subscriptionid'] = null;
            $event['uuid']= '';
            $event['format'] = external_validate_format($event['format']);
            if ($event['repeats'] > 0) {
                $event['repeat'] = 1;
            } else {
                $event['repeat'] = 0;
            }

            $eventobj = new calendar_event($event);

            // Let's check if the user is allowed to delete an event.
            if (!calendar_add_event_allowed($eventobj)) {
                $warnings [] = array('item' => $event['name'], 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to create this event');
                continue;
            }
            // Let's create the event.
            $var = $eventobj->create($event);
            $var = (array)$var->properties();
            if ($event['repeat']) {
                $children = $DB->get_records('event', array('repeatid' => $var['id']));
                foreach ($children as $child) {
                    $return[] = (array) $child;
                }
            } else {
                $return[] = $var;
            }
        }

        // Everything done smoothly, let's commit.
        $transaction->allow_commit();
        return array('events' => $return, 'warnings' => $warnings);
    }