Get points from retention policy

@param string $rp
@param string $metric
@param array $tags
@param string $granularity
@param string $startDt
@param string $endDt
@param string $timezone
@return array
771165
public function getRpPoints($rp, $metric, $tags, $granularity, $startDt = null, $endDt = null, $timezone = 'utc') {
        
        if (null == $rp || null == $metric) {
            return [];
        }
        
        $where = [];
        
        $query = $this->db->getQueryBuilder()
                ->retentionPolicy($rp)
                ->sum('value')
                ->from($metric);

        if (isset($endDt)) {
            $where[] = "time <= '" . $endDt . "'";
        }
        
        if (isset($startDt)) {
            $where[] = "time >= '" . $startDt . "'";
        }
        
        foreach ($tags as $key => $val) {
            $where[] = "$key = '" . $val . "'";
        }

        $query->where($where);
        
        $groupBy = "time(1d) tz('" . $timezone . "')";
        if ($granularity == self::GRANULARITY_HOURLY) {
            //timeoffset doesn't work hourly
            $groupBy = "time(1h) tz('" . $timezone . "')";
        } else if ($granularity == self::GRANULARITY_DAILY) {
            $groupBy = "time(1d) tz('" . $timezone . "')";
        } else if ($granularity == self::GRANULARITY_WEEKLY) {
            $groupBy = "time(1w) tz('" . $timezone . "')";
        }
        $query->groupBy($groupBy);

        return $query->getResultSet()->getPoints();
    }
947751
private static function getAtts(FormTag $tag, $validation_error, $class)
    {
        $atts = [];

        $atts['size'] = $tag->get_size_option('40');
        $atts['maxlength'] = $tag->get_maxlength_option();
        $atts['minlength'] = $tag->get_minlength_option();

        if ($atts['maxlength'] && $atts['minlength'] && $atts['maxlength'] < $atts['minlength']) {
            unset($atts['maxlength'], $atts['minlength']);
        }

        $atts['class'] = $tag->get_class_option($class);
        $atts['id'] = $tag->get_id_option();
        $atts['tabindex'] = $tag->get_option('tabindex', 'int', true);

        if ($tag->has_option('readonly')) {
            $atts['readonly'] = 'readonly';
        }

        if ($tag->is_required()) {
            $atts['aria-required'] = 'true';
            $atts['required'] = 'true';
        }

        $atts['aria-invalid'] = $validation_error ? 'true' : 'false';

        $values = $tag->getValues();
        $value = (string) reset($values);

        if ($tag->has_option('placeholder') || $tag->has_option('watermark')) {
            $atts['placeholder'] = $value;
            $value = '';
        }

        $value = $tag->get_default_option($value);

        $value = wpcf7_get_hangover($tag->getName(), $value);

        $atts['value'] = $value;

        if (wpcf7_support_html5()) {
            $atts['type'] = $tag->getBaseType();
        } else {
            $atts['type'] = 'text';
        }

        $atts['name'] = $tag->getName();

        return wpcf7_format_atts($atts);
    }
511351
public function getStartTimes($starttime = 0, $endtime = 0, $tz = null) {
		if (!Util::isValidTimezone($tz)) {
			$tz = Util::getClientTimezone();
		}

		if (!$this->isRecurring()) {
			return array($this->getStartTimestamp());
		}

		$start_times = array();

		$test_day = ($this->getStartTimestamp() > $starttime) ? $this->getStartTimestamp() : $starttime;

		// iterate through each day of our range and see if this event shows up on any of those days
		while ($test_day < $endtime) {

			$shows = false;

			$offset_on_test_day = Util::getOffset($test_day, Util::UTC, $this->getTimezone());

			// next increment
			$next_test_day = $test_day + Util::SECONDS_IN_A_DAY;

			// event has no more occurrences after this day
			if ($this->repeat_end_timestamp && $this->repeat_end_timestamp < $test_day) {
				break;
			}

			switch ($this->repeat_frequency) {
				case Util::FREQUENCY_DAILY:
					$shows = true;
					break;

				case Util::FREQUENCY_WEEKDAY:
					$repeat_weekly_days = array(Util::SATURDAY, Util::SUNDAY);
					foreach ($repeat_weekly_days as $key => $day) {
						$repeat_weekly_days[$key] = Util::getDayOfWeek(strtotime($day, $test_day) - $offset_on_test_day);
					}
					$D = Util::getDayOfWeek($test_day);
					$shows = !in_array($D, $repeat_weekly_days);
					break;

				case Util::FREQUENCY_WEEKDAY_ODD:
					$repeat_weekly_days = array(Util::MONDAY, Util::WEDNESDAY, Util::FRIDAY);
					foreach ($repeat_weekly_days as $key => $day) {
						$repeat_weekly_days[$key] = Util::getDayOfWeek(strtotime($day, $test_day) - $offset_on_test_day);
					}
					$D = Util::getDayOfWeek($test_day);
					$shows = in_array($D, $repeat_weekly_days);
					break;

				case Util::FREQUENCY_WEEKDAY_EVEN:
					$repeat_weekly_days = array(Util::TUESDAY, Util::THURSDAY);
					foreach ($repeat_weekly_days as $key => $day) {
						$repeat_weekly_days[$key] = Util::getDayOfWeek(strtotime($day, $test_day) - $offset_on_test_day);
					}
					$D = Util::getDayOfWeek($test_day);
					$shows = in_array($D, $repeat_weekly_days);
					break;

				case Util::FREQUENCY_WEEKLY:
					$repeat_weekly_days = $this->repeat_weekly_days;
					if (!$repeat_weekly_days) {
						$repeat_weekly_days = Util::getDayOfWeek($this->getStartTimestamp());
					}
					if (!is_array($repeat_weekly_days)) {
						$repeat_weekly_days = array($repeat_weekly_days);
					}
					$D = Util::getDayOfWeek($test_day);
					foreach ($repeat_weekly_days as $key => $day) {
						// Monday in Sydney can still be Sunday at UTC
						$repeat_weekly_days[$key] = Util::getDayOfWeek(strtotime($day, $test_day) - $offset_on_test_day);
					}
					$shows = in_array($D, $repeat_weekly_days);
					break;

				case Util::FREQUENCY_MONTHLY:
					if ($this->repeat_monthly_by == Util::REPEAT_MONTHLY_BY_DAY_OF_WEEK) {
						$shows = Util::isOnSameWeekDayOfMonth($test_day, $this->getStartTimestamp());
						if ($shows) {
							// we can skip 4 weeks
							$next_test_day = strtotime('+28 days', $test_day);
						}
					} else {
						$shows = Util::isOnSameDayOfMonth($test_day, $this->getStartTimestamp());
						if ($shows) {
							// we can skip a month
							$next_test_day = strtotime('+1 month', $test_day);
						}
					}
					break;

				case Util::FREQUENCY_YEARLY:
					$shows = Util::isOnSameDayOfYear($test_day, $this->getStartTimestamp());
					if ($shows) {
						// we can skip a year
						$next_test_day = strtotime('+1 year', $test_day);
					}
					break;
			}

			if ($shows) {
				$occurrence = (int) Util::getTimeOfDay($this->getStartTimestamp(), $test_day);
				if ($occurrence >= $starttime && $occurrence <= $endtime) {
					// events may show on a start or end day, but not fall in the time range
					array_push($start_times, $occurrence);
				}
			}

			$test_day = $next_test_day;
		}

		$cancelled = $this->cancelled_instance;
		if (!$cancelled) {
			$cancelled = array();
		}
		if (!is_array($cancelled)) {
			$cancelled = array($cancelled);
		}

		return array_diff($start_times, $cancelled);
	}
1333116
public function remember($cacheGroup, array $params = [], $tags = null, \Closure $closure = null)
    {
        $data = $this->get($cacheGroup, $params, $tags);

        // Exactly null should be only case we do not accept currently cached data
        if (!is_null($data)) {
            return $data;
        }

        if ($closure) {
            $callbackData = call_user_func($closure);

            if ($callbackData) {
                $this->put($cacheGroup, $params, $callbackData, $tags);
            }

            return $callbackData;
        }
    }
1113441
public static function GivePoints($UserID, $Points, $Source = 'Other', $Timestamp = FALSE) {
      if (!$Timestamp)
         $Timestamp = time();
      
      if (is_array($Source)) {
         $CategoryID = GetValue('CategoryID', $Source, 0);
         $Source = $Source[0];
      } else {
         $CategoryID = 0;
      }
      
      if ($CategoryID > 0) {
         $CategoryIDs = array($CategoryID, 0);
      } else {
         $CategoryIDs = array($CategoryID);
      }
      
      foreach ($CategoryIDs as $ID) {
         // Increment source points for the user.
         self::_GivePoints($UserID, $Points, 'a', $Source, $ID);

         // Increment total points for the user.
         self::_GivePoints($UserID, $Points, 'w', 'Total', $ID, $Timestamp);
         self::_GivePoints($UserID, $Points, 'm', 'Total', $ID, $Timestamp);
         self::_GivePoints($UserID, $Points, 'a', 'Total', $ID, $Timestamp);

         // Increment global daily points.
         self::_GivePoints(0, $Points, 'd', 'Total', $ID, $Timestamp);
      }
      
      // Grab the user's total points.
      $Points = Gdn::SQL()->GetWhere('UserPoints', array('UserID' => $UserID, 'SlotType' => 'a', 'Source' => 'Total', 'CategoryID' => 0))->Value('Points');
      
//      Gdn::Controller()->InformMessage('Points: '.$Points);
      Gdn::UserModel()->SetField($UserID, 'Points', $Points);
      
      // Fire a give points event.
      Gdn::UserModel()->EventArguments['UserID'] = $UserID;
      Gdn::UserModel()->EventArguments['CategoryID'] = $CategoryID;
      Gdn::UserModel()->EventArguments['Points'] = $Points;
      Gdn::UserModel()->FireEvent('GivePoints');
   }
109318
public static function getPoints(array $points, $tag = null)
    {
        $set = [];

        foreach ($points as $point) {
            $collector = $point->getData();

            if ($tag && $collector['tag'] != $tag) {
                continue;
            }

            $set[$point->getName()] = $point;
        }

        return $set;
    }
1238982
protected function get($endpoint, $params = [])
    {
        if (array_key_exists('reply_markup', $params)) {
            $params['reply_markup'] = (string)$params['reply_markup'];
        }

        return $this->sendRequest(
            'GET',
            $endpoint,
            $params
        );
    }
969728
public function cachePoints($metricId, $num = 1000, $page = 1)
    {
        // If cache already exists return it
        if ($this->cached != null) {
            return $this->cached;
        }

        $this->cached = $this->client->call(
            'GET',
            "metrics/$metricId/points",
            [
                'query' => [
                    'per_page' => $num,
                    'current_page' => $page,
                ],
            ]
        );

        return $this->cached;
    }
918703
public function approvalRecords(int $startTime, int $endTime, int $nextNumber = null)
    {
        $params = [
            'starttime' => $startTime,
            'endtime' => $endTime,
            'next_spnum' => $nextNumber,
        ];

        return $this->httpPostJson('cgi-bin/corp/getapprovaldata', $params);
    }
1049120
public static RetentionPolicy getRetentionPolicy(Class<? extends Annotation> annotationType) {
		final Retention retention = annotationType.getAnnotation(Retention.class);
		if (null == retention) {
			return RetentionPolicy.CLASS;
		}
		return retention.value();
	}
321344
static void checkMetricAndTags(final String metric,
      final Map<String, String> tags) {
    if (tags.size() <= 0) {
      throw new IllegalArgumentException("Need at least one tag (metric="
          + metric + ", tags=" + tags + ')');
    } else if (tags.size() > Const.MAX_NUM_TAGS()) {
      throw new IllegalArgumentException("Too many tags: " + tags.size()
          + " maximum allowed: " + Const.MAX_NUM_TAGS() + ", tags: " + tags);
    }

    Tags.validateString("metric name", metric);
    for (final Map.Entry<String, String> tag : tags.entrySet()) {
      Tags.validateString("tag name with value [" + tag.getValue() + "]", 
          tag.getKey());
      Tags.validateString("tag value with key [" + tag.getKey() + "]", 
          tag.getValue());
    }
  }
533029
public function links($adzone_id, $start_time, $end_time) {
        $res = $this->getSearch()
            ->parameters(compact('adzone_id', 'start_time', 'end_time'))->text();
        return $res['results']['results'];
    }
1355283
public function syncTags(HoldsTags $holder)
    {
        $holderRelations = [];

        if (!$holder instanceof AppliesToResource) {
            throw new InvalidArgumentException('Holders have to be instanceof AppliesToResource for GlobalTaggingRepository');
        }

        $this->assureExistingTags($holder);

        $settedIds = $this->collectIds($holder->getTags());
        $storedIds = $this->collectIds($this->tagsByForeignId([$holder->getId()], $holder->resourceName(), true));

        list($attach, $unchanged, $detach) = $this->sortByDifference($storedIds, $settedIds);

        if ($detach) {
            $query = $this->newPivotQuery()
                          ->where($this->resourceNameKey, $holder->resourceName())
                          ->where($this->foreignIdKey, $holder->getKey())
                          ->whereIn($this->tagIdKey, $detach)
                          ->delete();
        }

        if ($attach) {
            $query = $this->newPivotQuery();
            $records = [];
            foreach ($attach as $attachId) {
                $records[] = $this->createPivotValues($holder, $attachId);
            }

            $query->insert($records);
        }
        return $this;
    }
137071
private function getCountriesCountFromSessions(Carbon $start, Carbon $end)
    {
        return $this->getVisitorsFilteredByDateRange($start, $end)
            ->transform(function (Visitor $visitor) {
                return $visitor->hasGeoip()
                    ? [
                        'code'  => $visitor->geoip->iso_code,
                        'geoip' => $visitor->geoip,
                    ]
                    : [
                        'code'  => 'undefined',
                        'geoip' => null,
                    ];
            })
            ->groupBy('code')
            ->transform(function (Collection $items, $key) {
                return ($key === 'undefined')
                    ? [
                        'code'  => null,
                        'name'  => trans('tracker::generals.undefined'),
                        'count' => $items->count(),
                    ]
                    : [
                        'code'  => $key,
                        'name'  => $items->first()['geoip']->country,
                        'count' => $items->count(),
                    ];
            });
    }
1320662
private function fixTimeForGranularity($points, $granularity) {
        if ($granularity != $this->mapper::GRANULARITY_DAILY) {
            return $points;
        }
        foreach ($points as &$value) {
            $date = substr($value['time'],0, 10); // get date (2017-08-29)
            $offset = substr($value['time'], -6); // get timezone offset (+02:00, -04:00)
            $value['time'] = $date . "T00:00:00" . $offset;
        }
        return $points;
    }
1124112
protected static function _GivePoints($UserID, $Points, $SlotType, $Source = 'Total', $CategoryID = 0, $Timestamp = FALSE) {
      $TimeSlot = gmdate('Y-m-d', Gdn_Statistics::TimeSlotStamp($SlotType, $Timestamp));
      
      $Px = Gdn::Database()->DatabasePrefix;
      $Sql = "insert {$Px}UserPoints (UserID, SlotType, TimeSlot, Source, CategoryID, Points)
         values (:UserID, :SlotType, :TimeSlot, :Source, :CategoryID, :Points)
         on duplicate key update Points = Points + :Points1";
      
      Gdn::Database()->Query($Sql, array(
          ':UserID' => $UserID, 
          ':Points' => $Points, 
          ':SlotType' => $SlotType, 
          ':Source' => $Source,
          ':CategoryID' => $CategoryID,
          ':TimeSlot' => $TimeSlot, 
          ':Points1' => $Points));
   }
474052
private function getReferersCountFromSessionActivities($start, $end)
    {
        return $this->getVisitsFilteredByDateRange($start, $end)
            ->transform(function (VisitorActivity $visit) {
                return [
                    'name' => $visit->hasReferer()
                        ? $visit->referer->domain->name
                        : trans('tracker::generals.undefined'),
                ];
            })
            ->groupBy('name')
            ->transform(function (Collection $items, $key) {
                return [
                    'name'  => $key,
                    'count' => $items->count(),
                ];
            })
            ->sortByDesc('count');
    }