Main processing function
Generate and save operations.

@param DateTime $startDate
@param DateTime $endDate
@param DateTime $cycleDate

@throws Exception

@codeCoverageIgnore
966747
public function process(DateTime $startDate, DateTime $endDate, DateTime $cycleDate)
    {
        $this->logger->info('Control Mirakl Settings', array('miraklId' => null, "action" => "Operations creation"));
        // control mirakl settings
        $boolControl = $this->getControlMiraklSettings($this->documentTypes);
        if ($boolControl === false) {
            // log critical
            $title = $this->criticalMessageMiraklSettings;
            $message = $this->formatNotification->formatMessage($title);
            $this->logger->critical($message, array('miraklId' => null, "action" => "Operations creation"));
        } else {
            $this->logger->info(
                'Control Mirakl Settings OK',
                array('miraklId' => null, "action" => "Operations creation")
            );
        }

        $this->logger->info('Cashout Initializer', array('miraklId' => null, "action" => "Operations creation"));

        //Fetch Invoices
        $this->logger->info(
            'Fetch invoices documents from Mirakl from ' .
            $startDate->format('Y-m-d H:i') .
            ' to ' .
            $endDate->format('Y-m-d H:i')
            ,
            array('miraklId' => null, "action" => "Operations creation")
        );

        // get invoices from Mirakl API
        $invoices = $this->getInvoices($startDate, $endDate);

        $this->logger->info(
            '[OK] Fetched ' . count($invoices) . ' invoices',
            array('miraklId' => null, "action" => "Operations creation")
        );

        $this->logger->info('Process invoices', array('miraklId' => null, "action" => "Operations creation"));

        $operations = $this->processInvoices($invoices, $cycleDate);

        $this->saveOperations($operations);

    }
207749
protected function calculate_sample($sampleid, $sampleorigin, $starttime = false, $endtime = false) {

        if (!$starttime || !$endtime) {
            return null;
        }

        $select = '';
        $params = array();

        if ($user = $this->retrieve('user', $sampleid)) {
            $select .= "userid = :userid AND ";
            $params = $params + array('userid' => $user->id);
        }

        if (!$logstore = \core_analytics\manager::get_analytics_logstore()) {
            throw new \coding_exception('No available log stores');
        }

        // Filter by context to use the logstore_standard_log db table index.
        $context = $this->retrieve('context', $sampleid);
        $select .= "contextlevel = :contextlevel AND contextinstanceid = :contextinstanceid AND " .
            "crud = 'r' AND timecreated > :starttime AND timecreated <= :endtime";
        $params = $params + array('contextlevel' => $context->contextlevel,
            'contextinstanceid' => $context->instanceid, 'starttime' => $starttime, 'endtime' => $endtime);
        $nrecords = $logstore->get_events_select_count($select, $params);
        // We define a list of ranges to fit $nrecords into it
        // # Done absolutely nothing
        // # Not much really, just accessing the course once a week
        // # More than just accessing the course, some interaction
        // # Significant contribution, will depend on the course anyway.

        // We need to adapt the limits to the time range duration.
        $nweeks = $this->get_time_range_weeks_number($starttime, $endtime);

        // Careful with this, depends on the course.
        $limit = $nweeks * 3 * 10;
        $ranges = array(
            array('eq', 0),
            // 1 course access per week (3 records are easily generated).
            array('le', $nweeks * 3),
            // 3 course accesses per week doing some stuff.
            array('le', $limit),
            array('gt', $limit)
        );
        return $this->classify_value($nrecords, $ranges);
    }
164976
public function main()
    {
        // check to make sure task received all correct params
        $this->validate();

        $generatorConfig = $this->getGeneratorConfig();

        // loading model from database
        $this->log('Reading databases structure...');
        $connections = $generatorConfig->getBuildConnections();
        if (!$connections) {
            throw new Exception('You must define database connection settings in a buildtime-conf.xml file to use diff');
        }
        $manager = new PropelMigrationManager();
        $manager->setConnections($connections);
        $manager->setMigrationDir($this->getOutputDirectory());
        $manager->setMigrationTable($this->getGeneratorConfig()->getBuildProperty('migrationTable'));

        if ($manager->hasPendingMigrations()) {
            throw new Exception('Uncommitted migrations have been found ; you should either execute or delete them before rerunning the \'diff\' task');
        }

        $totalNbTables = 0;
        $ad = new AppData();
        foreach ($connections as $name => $params) {
            $this->log(sprintf('Connecting to database "%s" using DSN "%s"', $name, $params['dsn']), Project::MSG_VERBOSE);
            $pdo = $generatorConfig->getBuildPDO($name);
            $database = new Database($name);
            $platform = $generatorConfig->getConfiguredPlatform($pdo);
            if (!$platform->supportsMigrations()) {
                $this->log(sprintf('Skipping database "%s" since vendor "%s" does not support migrations', $name, $platform->getDatabaseType()));
                continue;
            }
            $database->setPlatform($platform);
            $database->setDefaultIdMethod(IDMethod::NATIVE);
            $parser = $generatorConfig->getConfiguredSchemaParser($pdo);
            $nbTables = $parser->parse($database, $this);
            $ad->addDatabase($database);
            $totalNbTables += $nbTables;
            $this->log(sprintf('%d tables found in database "%s"', $nbTables, $name), Project::MSG_VERBOSE);
        }
        if ($totalNbTables) {
            $this->log(sprintf('%d tables found in all databases.', $totalNbTables));
        } else {
            $this->log('No table found in all databases');
        }

        // loading model from XML
        $this->packageObjectModel = true;
        $appDatasFromXml = $this->getDataModels();
        $appDataFromXml = array_pop($appDatasFromXml);

        // comparing models
        $this->log('Comparing models...');
        $migrationsUp = array();
        $migrationsDown = array();
        foreach ($ad->getDatabases() as $database) {
            $name = $database->getName();
            $this->log(sprintf('Comparing database "%s"', $name), Project::MSG_VERBOSE);
            if (!$appDataFromXml->hasDatabase($name)) {
                // FIXME: tables present in database but not in XML
                continue;
            }
            $databaseDiff = PropelDatabaseComparator::computeDiff($database, $appDataFromXml->getDatabase($name), $this->isCaseInsensitive());

            if (!$databaseDiff) {
                $this->log(sprintf('Same XML and database structures for datasource "%s" - no diff to generate', $name), Project::MSG_VERBOSE);
                continue;
            }

            $this->log(sprintf('Structure of database was modified in datasource "%s": %s', $name, $databaseDiff->getDescription()));
            $platform = $generatorConfig->getConfiguredPlatform(null, $name);
            $migrationsUp[$name] = $platform->getModifyDatabaseDDL($databaseDiff);
            $migrationsDown[$name] = $platform->getModifyDatabaseDDL($databaseDiff->getReverseDiff());
        }

        if (!$migrationsUp) {
            $this->log('Same XML and database structures for all datasource - no diff to generate');

            return;
        }

        $timestamp = time();
        $migrationFileName = $manager->getMigrationFileName($timestamp);
        $migrationClassBody = $manager->getMigrationClassBody($migrationsUp, $migrationsDown, $timestamp);

        $_f = new PhingFile($this->getOutputDirectory(), $migrationFileName);
        file_put_contents($_f->getAbsolutePath(), $migrationClassBody);
        $this->log(sprintf('"%s" file successfully created in %s', $_f->getName(), $_f->getParent()));
        if ($editorCmd = $this->getEditorCmd()) {
            $this->log(sprintf('Using "%s" as text editor', $editorCmd));
            shell_exec($editorCmd . ' ' . escapeshellarg($_f->getAbsolutePath()));
        } else {
            $this->log('  Please review the generated SQL statements, and add data migration code if necessary.');
            $this->log('  Once the migration class is valid, call the "migrate" task to execute it.');
        }
    }
1154676
public function periodByStardDateByEndDateByFiscalYearAndByOrganizationId($startDate, $endDate, $fiscalYearId, $organizationId)
  {
    $Period = $this->Period->selectRaw('id, end_date, min(month) as month')
      ->where('start_date', '=', $startDate)
      ->where('end_date', '=', $endDate)
      ->where('fiscal_year_id', '=', $fiscalYearId)
      ->where('organization_id', '=', $organizationId)
      ->first();

    return $Period;
  }
382461
public function getOccurrencesBetween($startDate, $endDate, $limit = NULL)
    {

        $thisClone = clone $this;

        // Enforce consistent time zones. Date comparisons don't require them, but +P1D loop does.
        if ($tz = $thisClone->getTimeZone())
        {
            $startDate->setTimeZone($tz);
            $endDate->setTimeZone($tz);
        }

        $occurrences = [];

        if ($endDate <= $startDate)
        {
            return $occurrences;
        }

        // if existing UNTIL < startDate - we have nothing
        if (isset($thisClone->until) && $thisClone->until < $startDate)
        {
            return $occurrences;
        } // prevent unnecessary leg-work - our endDate is our new UNTIL
        elseif (!isset($thisClone->until))
        {
            $thisClone->until = $endDate;
        }

        $thisClone->generateOccurrences();
        $all_occurrences = $thisClone->occurrences;

        // nothing found in $thisClone->generateOccurrences();
        if (empty($all_occurrences))
        {
            return $occurrences;
        }

        $last_occurrence = end($all_occurrences);

        // if we've hit the rangeLimit, restart looking but start at this last_occurrence
        if ($thisClone->rangeLimit == count($all_occurrences)
            && $thisClone->startDate != $last_occurrence)
        {
            $thisClone->startDate = clone $last_occurrence;

            if (isset($thisClone->limit))
            {
                $thisClone->limit = $thisClone->limit - 200;
            }

            // clear all occurrences before our start date
            foreach ($thisClone->occurrences as $key => $occurrence)
            {
                if ($occurrence < $startDate)
                {
                    unset($thisClone->occurrences[$key]);
                }
            }

            return $thisClone->getOccurrencesBetween($startDate, $endDate, $limit);
        }

        // if our last occurrence is is before our startDate, we have nothing
        if ($last_occurrence < $startDate)
        {
            return $occurrences;
        }

        // we have something to report, so reset our array pointer
        reset($all_occurrences);

        $count = 0;

        foreach ($all_occurrences as $occurrence)
        {
            // fastforward our pointer to where it's >= startDate
            if ($occurrence < $startDate)
            {
                continue;
            }
            // if current occurence is past our endDate - we're done
            if ($occurrence > $endDate)
            {
                break;
            }
            // if we reach getOccurrencesBetween()'s limit - we're done
            if (NULL != $limit && ++$count > $limit)
            {
                break;
            }

            $occurrences[] = $occurrence;
        }

        return $occurrences;
    }
408174
public function buildQueries(\DateTime $start_date, \DateTime $end_date, $unit_ids) {
    $queries = array();

    $queries[Event::BAT_DAY] = 'SELECT * FROM ' . $this->day_table . ' WHERE ';
    $queries[Event::BAT_HOUR] = 'SELECT * FROM ' . $this->hour_table . ' WHERE ';
    $queries[Event::BAT_MINUTE] = 'SELECT * FROM ' . $this->minute_table . ' WHERE ';

    // Create a mock event which we will use to determine how to query the database
    $mock_event = new Event($start_date, $end_date, new Unit(0, 0, array()), -10);
    // We don't need a granular event even if we are retrieving granular data - since we don't
    // know what the event break-down is going to be we need to get the full range of data from
    // days, hours and minutes.
    $itemized = $mock_event->itemize(new EventItemizer($mock_event, Event::BAT_DAILY));

    $year_count = 0;

    $query_parameters = '';

    foreach ($itemized[Event::BAT_DAY] as $year => $months) {
      if ($year_count > 0) {
        // We are dealing with multiple years so add an OR
        $query_parameters .= ' OR ';
      }
      $query_parameters .= 'year IN (' . $year . ') ';
      $query_parameters .= 'AND month IN (' . implode(",", array_keys($months)) . ') ';
      if (count($unit_ids) > 0) {
        // Unit ids are defined so add this as a filter
        $query_parameters .= 'AND unit_id in (' . implode("," , $unit_ids) . ') ';
      }
      $year_count++;
    }

    // Add parameters to each query
    $queries[Event::BAT_DAY] .= $query_parameters;
    $queries[Event::BAT_HOUR] .= $query_parameters;
    $queries[Event::BAT_MINUTE] .= $query_parameters;

    // Clean up and add ordering information
    $queries[Event::BAT_DAY] .= ' ORDER BY unit_id, year, month';
    $queries[Event::BAT_HOUR] .= ' ORDER BY unit_id, year, month, day';
    $queries[Event::BAT_MINUTE] .= ' ORDER BY unit_id, year, month, day, hour';

    return $queries;
  }
220070
public function getUserSummary($beginDate = '',$endDate = ''){
        if(strtotime($beginDate) > strtotime($endDate)){
            return false;
        }
        $date = date('Y-m-d',strtotime('+6 day',strtotime($beginDate)));
        if(strtotime($endDate) > strtotime($date)){
            $endDate = $date;
        }
        $url = $this->apiUrl.'/datacube/getusersummary?access_token='.$this->getAccessToken();
        $data = '{
            "begin_date" : "'.$beginDate.'",
            "end_date" : "'.$endDate.'"
        }';
        $result = $this->curl($url,$data);
        return $this->get($result);
    }
81178
public function fire(Carbon $startDate, Carbon $endDate)
    {
        $this->start = $startDate;
        $this->end   = $endDate;

        return $this->getData();
    }
434881
public function toIcal($starttime = null, $endtime = null, $filename = 'calendar.ics') {

		if (is_null($starttime)) {
			$starttime = time();
		}
		if (is_null($endtime)) {
			$endtime = strtotime('+1 year', $starttime);
		}

		$instances = $this->getAllEventInstances($starttime, $endtime, true, 'ical');

		$config = array(
			'unique_id' => $this->guid,
			// setting these explicitly until icalcreator bug #14 is solved
			'allowEmpty' => true,
			'nl' => "\r\n",
			'format' => 'iCal',
			'delimiter' => DIRECTORY_SEPARATOR,
			'filename' => $filename, // this is last until #14 is solved
		);

		$v = new vcalendar($config);
		$v->setProperty('method', 'PUBLISH');
		$v->setProperty("X-WR-CALNAME", implode(' - ', array(elgg_get_config('sitename'), $this->getDisplayName())));
		$v->setProperty("X-WR-CALDESC", strip_tags($this->description));
		$v->setProperty("X-WR-TIMEZONE", Util::UTC);
		foreach ($instances as $instance) {

			$e = & $v->newComponent('vevent');

			$organizer = elgg_extract('organizer', $instance, array());
			unset($instance['organizer']);

			$reminders = elgg_extract('reminders', $instance, array());
			unset($instance['reminders']);

			foreach ($instance as $property => $value) {
				$e->setProperty($property, $value);
			}

			if (!empty($organizer)) {
				if (is_email_address($organizer)) {
					$e->setProperty('organizer', $organizer);
				} else {
					$e->setProperty('organizer', elgg_get_site_entity()->email, array(
						'CN' => $organizer,
					));
				}
			}

			if (!empty($reminders)) {
				foreach ($reminders as $reminder) {
					$a = & $e->newComponent('valarm');
					$a->setProperty('action', 'DISPLAY');
					$a->setProperty('trigger', "-PT{$reminder}S");
				}
			}
		}

		$v->returnCalendar();
	}
1097481
function(startDate, endDate) {
    var current = new Date(startDate);
    var end = new Date(endDate); 
    var dates = [];

    while(current <= end) {

        var m = current.getMonth() + 1;
        var d = current.getDate();
        var oneDate = [
            current.getFullYear(),
            m < 10 ? "0" + m : m,
            d < 10 ? "0" + d : d].join('-');

        dates.push(oneDate);
        current.setDate(current.getDate() + 1);
    }

    return dates;
}
1103496
public function getParticipationsByRangeDate($startDate = '', $endDate = '')
    {
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');

        $startDateTime = \DateTime::createFromFormat('d/m/Y', $startDate);
        $endDateTime = \DateTime::createFromFormat('d/m/Y', $endDate);

        if ($startDate != '' && $endDate != '') {
            $dateRange = "(e.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0' AND e.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0')";
        } elseif ($startDate == '' && $endDate != '') {
            $dateRange = "e.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0'";
        } elseif ($startDate != '' && $endDate == '') {
            $dateRange = "e.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0'";
        } else {
            $dateRange = "e.created_at IS NOT NULL";
        }

        $query = $em->createQuery('
            SELECT COUNT(e.id) FROM PlaygroundGame\Entity\Entry e
			WHERE ' . $dateRange . '
            AND e.active=0
		');
        $count = $query->getSingleScalarResult();
        return $count;
    }
724054
public static function initDatesInRange($start_date, $end_date, $daysDifference = 1){
        $dates_in_range = [];
        $begin = new DateTime($start_date);
        $end = new DateTime($end_date);
        $endModify = $end->modify( '+'.$daysDifference.' day' ); 

        $interval = new DateInterval('P'.$daysDifference.'D');
        $daterange = new DatePeriod($begin, $interval ,$endModify);

        foreach($daterange as $date){
            $dates_in_range[$date->getTimestamp()] = $date->format("Y-m-d");
        }
        return $dates_in_range;
    }
768638
public function process($connectionName, $job, WorkerOptions $options)
    {
        $startTime = microtime(true);

        try {
            parent::process($connectionName, $job, $options);
        } catch (Exception $e) {
            $this->recordJobException($e);
        } catch (Throwable $e) {
            $this->recordJobException($e);
        } finally {
            $this->recordJobEnd($startTime, $job->resolveName());
        }
    }
465188
function process(){
		LogMaster::log("DataProcessor object initialized",$_POST);
		
		$results=array();

		$ids=$this->get_ids();
		$rows_data=$this->get_post_values($ids);
		$failed=false;
		
		try{
			if ($this->connector->sql->is_global_transaction())
				$this->connector->sql->begin_transaction();
			
			for ($i=0; $i < sizeof($ids); $i++) { 
				$rid = $ids[$i];
				LogMaster::log("Row data [{$rid}]",$rows_data[$rid]);
				$status = $this->get_operation($rid);
				
				$action=new DataAction($status,$rid,$rows_data[$rid]);
				$results[]=$action;
				$this->inner_process($action);
			}
			
		} catch(Exception $e){
			LogMaster::log($e);
			$failed=true;
		}
		
		if ($this->connector->sql->is_global_transaction()){
			if (!$failed)
				for ($i=0; $i < sizeof($results); $i++)
					if ($results[$i]->get_status()=="error" || $results[$i]->get_status()=="invalid"){
						$failed=true; 
						break;
					}
			if ($failed){
				for ($i=0; $i < sizeof($results); $i++)
					$results[$i]->error();
				$this->connector->sql->rollback_transaction();
			}
			else
				$this->connector->sql->commit_transaction();
		}
		
		$this->output_as_xml($results);
	}
1164943
@PostConstruct
    public void start() throws Exception {
        lifecycleLock.writeLock().lock();
        try {
            if (!State.STOPPED.equals(state)) {
                logger.warn("Ignore start() command for {} instance", state);
                return;
            }
            logger.info("Start...");

            for (Query query : queries) {
                query.start();
            }
            for (OutputWriter outputWriter : outputWriters) {
                outputWriter.start();
            }

            collectScheduledExecutor = Executors.newScheduledThreadPool(getNumQueryThreads(), new NamedThreadFactory("jmxtrans-collect-", true));
            exportScheduledExecutor = Executors.newScheduledThreadPool(getNumExportThreads(), new NamedThreadFactory("jmxtrans-export-", true));

            logger.info("Start queries and output writers...");
            for (final Query query : getQueries()) {
                collectScheduledExecutor.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        lifecycleLock.readLock().lock();
                        try {
                            if (!State.STARTED.equals(state)) {
                                logger.debug("Ignore query.collectMetrics() command for {} instance", state);
                                return;
                            }
                            query.collectMetrics();
                        } finally {
                            lifecycleLock.readLock().unlock();
                        }
                    }

                    @Override
                    public String toString() {
                        return "Collector[" + query + "]";
                    }
                }, 0, getQueryIntervalInSeconds(), TimeUnit.SECONDS);

                // start export just after first collect
                exportScheduledExecutor.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        lifecycleLock.readLock().lock();
                        try {
                            if (!State.STARTED.equals(state)) {
                                logger.debug("Ignore query.exportCollectedMetrics() command for {} instance", state);
                                return;
                            }

                            query.exportCollectedMetrics();
                        } finally {
                            lifecycleLock.readLock().unlock();
                        }
                    }

                    @Override
                    public String toString() {
                        return "Exporter[" + query + "]";
                    }
                }, getQueryIntervalInSeconds() + 1, getExportIntervalInSeconds(), TimeUnit.SECONDS);
            }

            shutdownHook = new EmbeddedJmxTransShutdownHook();
            shutdownHook.registerToRuntime();
            state = State.STARTED;
            logger.info("EmbeddedJmxTrans started");
        } catch (RuntimeException e) {
            this.state = State.ERROR;
            if (logger.isDebugEnabled()) {
                // to troubleshoot JMX call errors or equivalent, it may be useful to log and rethrow
                logger.warn("Exception starting EmbeddedJmxTrans", e);
            }
            throw e;
        } finally {
            lifecycleLock.writeLock().unlock();
        }
    }
147961
public function mergeCells($startRow, $startColumn, $totalRows, $totalColumns)
    {
        if ($startRow == '')
            throw new Exception('Start Row not specified');
        
        if ($startColumn == '')
            throw new Exception('Start Column not specified');
        
        if ($totalRows == '')
            throw new Exception('Total Rows not specified');
        
        if ($totalColumns == '')
            throw new Exception('Total Columns not specified');
        
        //Build URI
        $strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() . '/worksheets/' . $this->worksheetName . 
                  '/cells/merge?startrow=' . $startRow . '&startcolumn=' . $startColumn .
                  '&totalrows=' . $totalRows . '&totalcolumns=' . $totalColumns;
        //Sign URI
        $signedURI = Utils::sign($strURI);
        
        //Send request and receive response
        $response = Utils::processCommand($signedURI, 'POST', '', '');
        $json = json_decode($response);
        if ($json->Code == 200) {
            $strURI = Product::$baseProductUri . '/storage/file/' . $this->getFileName();
            $signedURI = Utils::Sign($strURI);
            $responseStream = Utils::processCommand($signedURI, "GET", "", "");

            $outputPath = AsposeApp::$outPutLocation . $this->getFileName();
            Utils::saveFile($responseStream, $outputPath);
            return $outputPath;
        }    
        else
            return false;
    }
1159292
protected function availability_completed_by(\core_availability\info $info, $starttime, $endtime) {

        $dateconditions = $info->get_availability_tree()->get_all_children('\availability_date\condition');
        foreach ($dateconditions as $condition) {
            // Availability API does not allow us to check from / to dates nicely, we need to be naughty.
            $conditiondata = $condition->save();

            if ($conditiondata->d === \availability_date\condition::DIRECTION_FROM &&
                    $conditiondata->t > $endtime) {
                // Skip this activity if any 'from' date is later than the end time.
                return false;

            } else if ($conditiondata->d === \availability_date\condition::DIRECTION_UNTIL &&
                    ($conditiondata->t < $starttime || $conditiondata->t > $endtime)) {
                // Skip activity if any 'until' date is not in $starttime - $endtime range.
                return false;
            } else if ($conditiondata->d === \availability_date\condition::DIRECTION_UNTIL &&
                    $conditiondata->t < $endtime && $conditiondata->t > $starttime) {
                return true;
            }
        }

        // This can be interpreted as 'the activity was available but we don't know if its expected completion date
        // was during this period.
        return null;
    }