Fetch data

@param string $from
@param string $to
@param string $metrics
@param array $args

@return \Google_Service_Analytics_GaData|\WP_Error
357960
public function fetch($from, $to, $metrics, array $args, $view_id = null ){
		if( !$this->ga ){
			return new \WP_Error(500, __('Google Analtyisとの連携が完了していません。', 'gapiwp'));
		}
		if( is_null($view_id) ){
			$view_id = $this->view_id;
		}
		try{
			$result = $this->ga->data_ga->get('ga:'.$view_id, $from, $to, $metrics, $args);
		}catch ( \Exception $e ){
			$result = new \WP_Error($e->getCode(), $e->getMessage());
		}
		return $result;
	}
869316
public function get($id, $args = [])
    {
        $url = '';

        // Support fetching via arbitrary field.
        if (! is_numeric($id)) {
            $wpcli_args = ['--fields=ID,url', "--{$args['by']}=" . escapeshellarg($id), '--post_type=any', '--format=json', '--ignore_sticky_posts=true'];
            $result     = json_decode($this->drivers->getDriver()->wpcli('post', 'list', $wpcli_args)['stdout']);

            if (empty($result)) {
                throw new UnexpectedValueException(sprintf('[W501] Could not find post with ID %d', $id));
            }

            $id  = (int) $result[0]->ID;
            $url = $result[0]->url;
        }

        // Fetch by ID.
        $wpcli_args = buildCLIArgs(
            array(
                'field',
                'fields',
            ),
            $args
        );

        array_unshift($wpcli_args, $id, '--format=json');
        $post = $this->drivers->getDriver()->wpcli('post', 'get', $wpcli_args)['stdout'];
        $post = json_decode($post);

        if (! $post) {
            throw new UnexpectedValueException(sprintf('[W501] Could not find post with ID %d', $id));
        }

        if (! $url) {
            $wpcli_args = ['--post__in=' . $post->ID, '--fields=url', '--post_type=any', '--format=json'];
            $result     = json_decode($this->drivers->getDriver()->wpcli('post', 'list', $wpcli_args)['stdout']);
            $url        = $result[0]->url;
        }

        $post->url = $url;

        return $post;
    }
565186
public function findLimited($from, $to, $arg = null, $operator = '=', $fields = array('*'))
    {
        return $this->find($arg, $operator, $fields)->limit($from, $to);
    }
576997
public function updateData($overviews)
    {
        // helpers
        $queryHelper = $this->getContainer()->get('kunstmaan_dashboard.helper.google.analytics.query');
        $configHelper = $this->getContainer()->get('kunstmaan_dashboard.helper.google.analytics.config');
        $metrics = new MetricsCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
        $chartData = new ChartDataCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
        $goals = new GoalCommandHelper($configHelper, $queryHelper, $this->output, $this->em);
        $visitors = new UsersCommandHelper($configHelper, $queryHelper, $this->output, $this->em);

        // get data per overview
        foreach ($overviews as $overview) {
            $configHelper->init($overview->getConfig()->getId());
            /* @var AnalyticsOverview $overview */
            $this->output->writeln('Fetching data for overview "<fg=green>' . $overview->getTitle() . '</fg=green>"');

            try {
                // metric data
                $metrics->getData($overview);
                if ($overview->getSessions()) { // if there are any visits
                    // day-specific data
                    $chartData->getData($overview);

                    // get goals
                    $goals->getData($overview);

                    // visitor types
                    $visitors->getData($overview);
                } else {
                    // reset overview
                    $this->reset($overview);
                    $this->output->writeln("\t" . 'No visitors');
                }
                // persist entity back to DB
                $this->output->writeln("\t" . 'Persisting..');
                $this->em->persist($overview);
                $this->em->flush($overview);

                $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig')->setUpdated($overview->getConfig()->getId());
            } catch (\Google_ServiceException $e) {
                $error = explode(')', $e->getMessage());
                $error = $error[1];
                $this->output->writeln("\t" . '<fg=red>Invalid segment: </fg=red>' .$error);
                $this->errors += 1;
            }
        }
    }
849545
public function moveFile( $from, $to )
	{
		$this->connection->checkConnection();
		return @ftp_rename( $this->connection->getResource(), $from, $to );
	}
26847
protected static function to_webp_sources(string &$from, &$to) {
		// Validate the source.
		ref\file::path($from, true);
		if (! $from) {
			$from = '';
			return false;
		}

		// We can only convert JPEG, PNG, and GIF sources.
		$info = mime::finfo($from);
		if (! \in_array($info['mime'], array('image/jpeg', 'image/gif', 'image/png'), true)) {
			$from = '';
			return false;
		}

		// Build a destination if we need to.
		if (null !== $to) {
			ref\cast::string($to, true);

			// If this is just a file name, throw it in from's dir.
			if (false === \strpos($to, '/')) {
				$to = "{$info['dirname']}/$to";
			}
			ref\file::path($to, false);
			if ('.webp' !== \substr(\strtolower($to), -5)) {
				$to = '';
				return false;
			}
		}
		// Just swap extensions with the source.
		else {
			$to = "{$info['dirname']}/{$info['filename']}.webp";
		}

		return true;
	}
451636
public function migrateExpiredJobs($from, $to)
    {
        //$options = ['cas' => true, 'watch' => $from, 'retry' => 10];
        $attempts = 10;

        do {
            //echo $attempts.'';

            $jobs = $this->getExpiredJobs(
                $this->getConnection(), $from, $time = $this->getTime()
            );

            //var_dump($jobs);

            if (count($jobs) > 0) {
                $this->removeExpiredJobs($this->getConnection(), $from, $time);

                $this->pushExpiredJobsOntoNewQueue($this->getConnection(), $to, $jobs);
            }
            //var_dump($queue->isEmpty());

            /*if ($queue->isEmpty()) {
                $this->getConnection()->unwatch($from);
                $this->getConnection()->discard();
                return;
            }*/

            $execResponse = $this->getConnection()->exec();
            //var_dump( $execResponse);

            if ($execResponse === null) {
                continue;
            }

            break;

        } while ($attempts-- > 0);

    }
290468
public function getPartialSum( $from, $to )
	{
		for( $i=$from; $i<=$to; $i++ )
			$sum += $this->getValue( $i );
		return $sum;
	}
162415
public function getData(&$overview)
    {
        $this->output->writeln("\t" . 'Fetching goals..');

        // calculate timespan
        $timespan = $overview->getTimespan() - $overview->getStartOffset();
        if ($timespan <= 1) {
            $extra = array('dimensions' => 'ga:date,ga:hour');
            $start = 2;
        } else {
            if ($timespan <= 7) {
                $extra = array('dimensions' => 'ga:date,ga:hour');
                $start = 2;
            } else {
                if ($timespan <= 31) {
                    $extra = array('dimensions' => 'ga:week,ga:day,ga:date');
                    $start = 3;
                } else {
                    $extra = array('dimensions' => 'ga:isoYearIsoWeek');
                    $start = 1;
                }
            }
        }

        // add segment
        if ($overview->getSegment()) {
            $extra['segment'] = $overview->getSegment()->getQuery();
        }

        $goals = $this->getAllGoals();
        if (!$goals) {
            return;
        }
        $goaldata = array();

        // Create an array with for each goal an entry to create the metric parameter.
        foreach ($goals as $key => $value) {
            ++$key;
            $goaldata[] = array('position' => $key, 'name' => $value->name);
        }

        $metrics = $this->prepareMetrics();

        $rows = $this->requestGoalResults($overview, $metrics[0], $extra);
        // Execute an extra query if there are more than 10 goals to query
        if (count($metrics) > 1) {
            $rows2 = $this->requestGoalResults($overview, $metrics[1], $extra);
            $rows2size = count($rows2);
            for ($i = 0; $i < $rows2size; ++$i) {
                // Merge the results of the extra query data with the previous query data.
                $rows[$i] = array_merge($rows[$i], array_slice($rows2[$i], $start, count($rows2) - $start));
            }
        }

        // Create a result array to be parsed and create Goal objects from
        $goalCollection = array();
        $goaldatasize = count($goaldata);
        for ($i = 0; $i < $goaldatasize; ++$i) {
            $goalEntry = array();
            foreach ($rows as $row) {
                // Create a timestamp for each goal visit (this depends on the timespan of the overview: split per hour, day, week, month)
                if ($timespan <= 1) {
                    $timestamp = mktime(
                        $row[1],
                        0,
                        0,
                        substr($row[0], 4, 2),
                        substr($row[0], 6, 2),
                        substr($row[0], 0, 4)
                    );
                    $timestamp = date('Y-m-d H:00', $timestamp);
                } else {
                    if ($timespan <= 7) {
                        $timestamp = mktime(
                            $row[1],
                            0,
                            0,
                            substr($row[0], 4, 2),
                            substr($row[0], 6, 2),
                            substr($row[0], 0, 4)
                        );
                        $timestamp = date('Y-m-d H:00', $timestamp);
                    } else {
                        if ($timespan <= 31) {
                            $timestamp = mktime(
                                0,
                                0,
                                0,
                                substr($row[2], 4, 2),
                                substr($row[2], 6, 2),
                                substr($row[2], 0, 4)
                            );
                            $timestamp = date('Y-m-d H:00', $timestamp);
                        } else {
                            $timestamp = strtotime(substr($row[0], 0, 4) . 'W' . substr($row[0], 4, 2));
                            $timestamp = date('Y-m-d H:00', $timestamp);
                        }
                    }
                }
                $goalEntry[$timestamp] = $row[$i + $start];
            }
            $goalCollection['goal' . $goaldata[$i]['position']]['name'] = $goaldata[$i]['name'];
            $goalCollection['goal' . $goaldata[$i]['position']]['position'] = $goaldata[$i]['position'];
            $goalCollection['goal' . $goaldata[$i]['position']]['visits'] = $goalEntry;
        }

        // Parse the goals and append them to the overview.
        $this->parseGoals($overview, $goalCollection);
    }
937897
public function translate($string, $from, $to)
    {
        foreach ($this->translatorServices as $service) {
            try {
                return $service->translate($string, $from, $to);
            } catch (TranslatorException\NoTranslationFoundException $e) {
                // Do nothing, try again.
            } catch (TranslatorException $e) {
                $this->log('error', $e->getMessage());
            } catch (\Exception $e) {
                $this->log('alert', $e->getMessage());
            }
        }

        return;
    }
1114926
private function get_data_segment($fromThis, $indexName) {
		$retval = null;
		if(is_array($fromThis)) {
			//it's an array.
			$retval = null;
			if(isset($fromThis[$indexName])) {
				$retval = $fromThis[$indexName];
			}
		}
		elseif(is_object($fromThis)) {
			throw new InvalidArgumentException("objects are not supported");
		}
		return($retval);
	}
979951
protected function executeQuery(AnalyticsOverview $overview, $metrics)
    {
        $timestamps = $this->getTimestamps($overview);
        $extra = $this->getExtra($overview);

        // execute query
        $results = $this->query->getResultsByDate(
            $timestamps['begin'],
            $timestamps['end'],
            $metrics,
            $extra
        );

        return $results->getRows();
    }
179185
public function redirect($from, $to, $status = 302)
    {
        $handler = function ($request, ResponseInterface $response) use ($to, $status) {
            return $response->withHeader('Location', (string)$to)->withStatus($status);
        };

        return $this->get($from, $handler);
    }
24236
public function migrateExpiredJobs($from, $to)
    {
        return tap(parent::migrateExpiredJobs($from, $to), function ($jobs) use ($to) {
            $this->event($to, new JobsMigrated($jobs));
        });
    }
852032
public function afterFetch(&$args) {
        $model   = &$args[0];
        $results = &$args[1];
        $select  = &$args[2];
        // In the CMS environment, the translated data is merged into the parent data
        $isCms = $model->isCmsContext();
        if (!$isCms && !$this->_forceI18nOutput) {
            return;
        }
        $iterator = new Garp_Db_Table_Rowset_Iterator(
            $results,
            array($this, 'mergeTranslatedFields')
        );
        $iterator->walk();
    }
758114
public function createMail($to, array $args) {
		$keys = array();
		$values = array();
		foreach ($args as $key => $value) {
			$keys[] = '{' . $key . '}';
			$values[] = $value;
		}
		$subject = str_replace($keys, $values, $this->subject);
		$message = str_replace($keys, $values, $this->message);
		$mail = new Mail($this->from, $subject, $message, $to);
		$mail->setType($this->type);
		foreach ($this->attachments as $path => $name) {
			$mail->addFile($path, $name);
		}
		
		return $mail;
	}
587903
public function afterFetch(Array &$args) {
        $model = $args[0];
        $results = $args[1];
        $table = $model->getName();
        $chartService = new Garp_Service_Google_Chart();
        $ini = Garp_Config_Ini::getCached(APPLICATION_PATH.'/configs/routes.ini');
        $routes = $ini->routes->toArray();
        $view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');

        $routeFound = false;
        foreach ($routes as $r) {
            if (
                array_key_exists('route', $r) &&
                $r['route'] === '/'.$table.'/:slug'
            ) {
                $routeFound = $r;
                break;
            }
        }

        if (!$routeFound) {
            throw new Exception('There is no direct route to this object.');
        }

        // provide uniform interface, so we can always loop
        if (!$results instanceof Garp_Db_Table_Rowset) {
            $results = array($results);
        }

        foreach ($results as $row) {
            if (
                isset($row->slug) &&
                $row->slug
            ) {
                $refUrl = $view->fullUrl('/'.$table.'/'.$row->slug);
                $row->setVirtual('qrcode', $chartService->fetchQRCodeUrl($refUrl));
            }
        }

        // return the pointer to 0
        if ($results instanceof Garp_Db_Table_Rowset) {
            $results->rewind();
        } else {
        // also, return results to the original format if it was no Rowset to begin with.
            $results = $results[0];
        }
    }