コード例 #1
1
ファイル: Governance.php プロジェクト: rickb838/scalr
 public function xSaveAction()
 {
     $this->request->defineParams(array('category' => array('type' => 'string'), 'name' => array('type' => 'string'), 'value' => array('type' => 'json')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $category = $this->getParam('category');
     $name = $this->getParam('name');
     $value = $this->getParam('value');
     if ($category == Scalr_Governance::CATEGORY_GENERAL && $name == Scalr_Governance::GENERAL_LEASE) {
         $enabled = (bool) $value['limits']['enableDefaultLeaseDuration'];
         unset($value['limits']['enableDefaultLeaseDuration']);
         if (!$governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $value['enabled'] == 1 && $enabled) {
             $dt = new DateTime();
             $dt->add(new DateInterval('P' . $value['limits']['defaultLifePeriod'] . 'D'));
             $farms = $this->db->GetCol('SELECT id FROM farms WHERE env_id = ? AND status = ?', array($this->getEnvironmentId(), FARM_STATUS::RUNNING));
             foreach ($farms as $farmId) {
                 $farm = DBFarm::LoadByID($farmId);
                 $farm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'));
                 $farm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, '');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_EXTEND_CNT, 0);
             }
         }
     }
     $governance->setValue($category, $name, $value);
     $this->response->success('Successfully saved');
 }
コード例 #2
1
ファイル: TaxOverride.class.php プロジェクト: shabirm/avatax
 public function __construct()
 {
     $this->TaxAmount = 0.0;
     $dateTime = new DateTime();
     $dateTime->setDate(1900, 01, 01);
     $this->TaxDate = $dateTime->format("Y-m-d");
 }
コード例 #3
1
 /**
  * @return \DateTime|null
  */
 public function getLastSyncDate()
 {
     $channel = $this->getChannel();
     $repository = $this->managerRegistry->getRepository('OroIntegrationBundle:Status');
     /**
      * @var Status $status
      */
     $status = $repository->findOneBy(['code' => Status::STATUS_COMPLETED, 'channel' => $channel, 'connector' => $this->getType()], ['date' => 'DESC']);
     $timezone = new \DateTimeZone('UTC');
     $date = new \DateTime('now', $timezone);
     $context = $this->getStepExecution()->getExecutionContext();
     $data = $context->get(ConnectorInterface::CONTEXT_CONNECTOR_DATA_KEY) ?: [];
     $context->put(ConnectorInterface::CONTEXT_CONNECTOR_DATA_KEY, array_merge($data, [self::LAST_SYNC_DATE_KEY => $date->format(\DateTime::ISO8601)]));
     if (!$status) {
         return null;
     }
     $data = $status->getData();
     if (empty($data)) {
         return null;
     }
     if (!empty($data[self::LAST_SYNC_DATE_KEY])) {
         return new \DateTime($data[self::LAST_SYNC_DATE_KEY], $timezone);
     }
     return null;
 }
コード例 #4
1
 public function deletespecials()
 {
     $products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('special_price', 'special_to_date', 'status'))->addAttributeToFilter('special_price', array('notnull' => true))->addAttributeToFilter('status', array('eq' => 1));
     $numbers = array();
     $now = new DateTime();
     $time = $now->getTimestamp();
     Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
     foreach ($products as $product) {
         if ($time <= strtotime($product->getSpecialToDate()) && $product->getSpecialToDate() != "") {
             /* Stock Set Variante
             			$stockItem = Mage::getModel('cataloginventory/stock_item')->load($product->getId(), 'product_id');
             			$stockItem->setData('is_in_stock', 0);
             			$stockItem->setTypeId( $product->getTypeId() );
             			$stockItem->setQty(0);
             			$stockItem->save();
             			*/
             /* Deaktivierungsvariante */
             $product->setStatus(2);
             $product->getResource()->saveAttribute($product, 'status');
             $numbers[] = $product->getStatus();
             /* Ende */
         } else {
         }
     }
     return $numbers;
 }
コード例 #5
1
ファイル: lib.php プロジェクト: avillarroelp/bookingrooms
function hour_module($module)
{
    global $DB, $USER;
    //in format HH:MM:SS (varchar)
    //Define lthe hours for misreservas.php
    $modules = $DB->get_record('bookingrooms_modules', array("id" => $module));
    $start = explode(":", $modules->hour_start);
    $end = explode(":", $modules->hour_end);
    $a = $start[0];
    $b = $start[1];
    $c = 00;
    //hour;minute;second
    $d = $end[0];
    $e = (int) $end[1];
    $f = 00;
    //hour;minute;second
    $minutes = str_replace(' ', '', $e);
    $ModuleStart = new DateTime();
    // Is left hour and minutes in 0 (midnigth)
    $ModuleStart->setTime($a, $b, 0);
    $ModuleEnd = new DateTime();
    // Is left hour and minutes in 0 (midnigth)
    $ModuleEnd->setTime($d, $e, 0);
    $hour = array($ModuleStart, $ModuloEnd);
    //var_dump($hour);
    return $hour;
    //returns $hour[start] y $hour[end]
}
コード例 #6
0
 public function aggregatedMethods()
 {
     $ts = 374390100;
     $dt = new \DateTime();
     $dt->setTimestamp($ts);
     return array(array('getCurrentUser', array(), new User()), array('setCurrentUser', array(new User()), null), array('hasAccess', array('module', 'function', new User()), array('limitations')), array('canUser', array('module', 'function', new User(), new Location()), false), array('beginTransaction', array(), true), array('commit', array(), true), array('rollback', array(), true), array('createDateTime', array($ts), $dt));
 }
コード例 #7
0
 public function validateDigest($digest, $nonce, $created, $secret)
 {
     // Generate created Token time difference
     $now = new \DateTime('now', new \DateTimeZone('UTC'));
     $then = new \Datetime($created, new \DateTimeZone('UTC'));
     $diff = $now->diff($then, true);
     // Check created time is not in the future
     if (strtotime($created) > time()) {
         throw new AuthenticationException("Back to the future...");
     }
     // Validate timestamp is recent within 5 minutes
     $seconds = time() - strtotime($created);
     if ($seconds > 300) {
         throw new AuthenticationException('Expired timestamp.  Seconds: ' . $seconds);
     }
     // Validate nonce is unique within 5 minutes
     if (file_exists($this->cacheDir . '/' . $nonce) && file_get_contents($this->cacheDir . '/' . $nonce) + 300 > time()) {
         throw new NonceExpiredException('Previously used nonce detected');
     }
     if (!is_dir($this->cacheDir)) {
         mkdir($this->cacheDir, 0777, true);
     }
     file_put_contents($this->cacheDir . '/' . $nonce, time());
     // Validate Secret
     $expected = base64_encode(sha1(base64_decode($nonce) . $created . $secret, true));
     // Return TRUE if our newly-calculated digest is the same as the one provided in the validateDigest() call
     return $expected === $digest;
 }
コード例 #8
0
function insert_profiles($name, $birthday, $type, $tell, $comment)
{
    //db接続を確立
    $insert_db = connect2MySQL();
    //DBに全項目のある1レコードを登録するSQL
    $insert_sql = "INSERT INTO user_t(name,birthday,tell,type,comment,newDate)" . "VALUES(:name,:birthday,:tell,:type,:comment,:newDate)";
    //現在時をdatetime型で取得
    $datetime = new DateTime();
    $date = $datetime->format('Y-m-d H:i:s');
    //クエリとして用意
    $insert_query = $insert_db->prepare($insert_sql);
    //SQL文にセッションから受け取った値&現在時をバインド
    $insert_query->bindValue(':name', $name);
    $insert_query->bindValue(':birthday', $birthday);
    $insert_query->bindValue(':tell', $tell);
    $insert_query->bindValue(':type', $type);
    $insert_query->bindValue(':comment', $comment);
    $insert_query->bindValue(':newDate', $date);
    //SQLを実行
    try {
        $insert_query->execute();
    } catch (PDOException $e) {
        //接続オブジェクトを初期化することでDB接続を切断
        $insert_db = null;
        return $e->getMessage();
    }
    $insert_db = null;
    return null;
}
コード例 #9
0
 public function fetch_data()
 {
     $this->ci =& get_instance();
     $this->ci->load->model('my_gofundme_model');
     $my_gofundme = $this->ci->my_gofundme_model->get_info();
     //calculate time interval
     $last_fetched = new DateTime($my_gofundme['last_fetched']);
     $now = new DateTime('now');
     $diff = $now->diff($last_fetched);
     $interval = ($diff->d * 24 + $diff->h) * 60 + $diff->i;
     //print_r($diff);
     //fetch if over interval minutes since last time
     if ($interval >= $my_gofundme['interval']) {
         $html = $this->getHTML(trim($my_gofundme['url']), 5);
         if ($html != false && !empty($html)) {
             preg_match('/Raised by\\s*<span>(.*)<\\/span>\\s*people/i', $html, $match);
             $my_gofundme['num_donations'] = $match[1];
             preg_match('/<\\/span>(.*)<span class="of">/i', $html, $match);
             $my_gofundme['raised'] = $match[1];
             //echo 'num_donations = ' . $my_gofundme['num_donations'] . '</br>';
             //echo 'raised = ' . $my_gofundme['raised'] . '</br>';
         }
         //calculate days to go
         $now = new DateTime('now');
         $interval = $now->diff(new DateTime($my_gofundme['end_date']));
         $my_gofundme['days_to_go'] = $interval->days;
         $this->ci->my_gofundme_model->update_info($my_gofundme);
     }
     return array('my_gofundme_url' => $my_gofundme['url'], 'num_donations' => $my_gofundme['num_donations'], 'raised' => $my_gofundme['raised'], 'goal' => $my_gofundme['goal'], 'days_to_go' => $my_gofundme['days_to_go']);
 }
コード例 #10
0
ファイル: Time.php プロジェクト: Repkit/demo-fastroute
 /**
  * Convert seconds into human readeble time
  * @param int $seconds 
  * @return string
  */
 public static function sec2time($seconds)
 {
     $sec = intval($seconds);
     $dtF = new \DateTime("@0");
     $dtT = new \DateTime("@{$sec}");
     return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
 }
コード例 #11
0
 function setFilteredResults()
 {
     $this->queryBuilder = $this->doctrine->getEntityManager()->createQueryBuilder();
     $this->queryBuilder->select('a, b')->from('HelperBundle:FeedbackMessage', 'a')->leftJoin('a.country', 'b');
     if ($this->queryParams['keyword']) {
         $this->queryBuilder->where('a.name LIKE :searchKey OR a.emailAddress LIKE :searchKey OR a.message LIKE :searchKey');
         $this->queryBuilder->setParameter('searchKey', '%' . $this->queryParams['keyword'] . '%');
     }
     if ($this->queryParams['country'] != self::FILTER_KEY_ALL) {
         $this->queryBuilder->where('a.country = :country');
         $this->queryBuilder->setParameter('country', $this->queryParams['country']);
     }
     if ($this->queryParams['dateCreated']) {
         list($year, $month, $day) = explode('-', $this->queryParams['dateCreated']);
         $dateFrom = new \DateTime();
         $dateFrom->setDate($year, $month, $day);
         $dateFrom->setTime('00', '00', '00');
         $dateTo = clone $dateFrom;
         $dateTo->setTime('23', '59', '59');
         $this->queryBuilder->andWhere('a.dateCreated >= :dateFrom AND a.dateCreated <= :dateTo');
         $this->queryBuilder->setParameter('dateFrom', $dateFrom)->setParameter('dateTo', $dateTo);
     }
     $sortBy = $this->sortBy ? $this->sortBy : 'dateCreated';
     $sort = "a.{$sortBy} " . $this->sortOrder;
     $this->queryBuilder->add('orderBy', $sort);
     $this->pagerAdapter->setQueryBuilder($this->queryBuilder);
     //echo $this->queryBuilder->getQuery()->getSQL(); exit;
     $this->filteredResult = $this->pager->getResults();
 }
コード例 #12
0
ファイル: Customkeno2.php プロジェクト: sdgdsffdsfff/Pari
 /**
 * 获取最新采集期号信息
 *
 * @return array(
               'expect' => '141106036',
               'opentime' => 1402143035
           )
 */
 public function getLatestAwardExpectInfo()
 {
     //获取开始统计日期到现在时间的天数
     $startCountDatetime = new \DateTime($this->getStartCountDate());
     $nowDatetime = new \DateTime(date('Y-m-d', $this->nowTimestamp));
     $datetimeDiff = $startCountDatetime->diff($nowDatetime);
     $diffDay = intval($datetimeDiff->format('%a'));
     //今天第一期期号
     $expect = $this->getStartCountExpect() + $diffDay * $this->getDailyOpenExpectNum();
     $opentime = 0;
     foreach ($this->getAwardTimeInfo() as $item) {
         $start = strtotime($item['start'], $this->nowTimestamp);
         $end = strtotime($item['end'], $this->nowTimestamp);
         for ($i = $start; $i <= $end; $i += $item['interval']) {
             $deviation = $this->nowTimestamp - $i;
             $minDeviation = isset($item['minDeviation']) ? $item['minDeviation'] : 0;
             $maxDeviation = isset($item['maxDeviation']) ? $item['maxDeviation'] : 30;
             if ($deviation >= $minDeviation && $deviation <= $maxDeviation) {
                 $opentime = $i;
                 break 2;
             }
             $expect++;
         }
     }
     if (!$opentime) {
         return false;
     }
     return array('expect' => $this->formatExpect($expect, $opentime), 'opentime' => $opentime);
 }
コード例 #13
0
ファイル: Utils.php プロジェクト: jhonochoa/larabel
 /**
  * Format date and time.
  * @param DateTime $date date to be formatted
  * @return string formatted date and time
  */
 public static function formatDateTime(DateTime $date = null)
 {
     if ($date === null) {
         return '';
     }
     return $date->format('m/d/Y H:i');
 }
コード例 #14
0
 public function discussionController_beforeCommentDisplay_handler($sender, $args)
 {
     // Find the previous comment.
     if (!$this->previous) {
         $this->previous = $args['Discussion'];
         if ($sender->data('Page', 1) != 1) {
             $this->previous = $sender->CommentModel->get($sender->DiscussionID, 1, $sender->Offset - 1)->firstRow();
         }
     }
     // Calculate the date difference.
     $date = new DateTime($args['Comment']->DateInserted);
     $gap = $date->diff(new DateTime($this->previous->DateInserted))->days;
     $this->previous = $args['Comment'];
     if ($gap < c('TimeGap.MinDays', 7) - 1) {
         return;
     } elseif ($gap < 30) {
         $gap = sprintf(t('%s days later'), (int) $gap);
         $class = 'Days';
     } elseif ($gap < 60) {
         $gap = t('1 month later');
         $class = 'Month';
     } elseif ($gap < 365) {
         $gap = sprintf(t('%s months later'), (int) ($gap / 30));
         $class = 'Months';
     } elseif ($gap < 720) {
         $gap = t('1 year later');
         $class = 'Year';
     } else {
         $gap = sprintf(t('%s years later'), (int) ($gap / 365));
         $class = 'Years';
     }
     echo wrap($gap, 'li', ['class' => 'TimeGap ' . $class]);
 }
コード例 #15
0
 public function db_array()
 {
     $db_array = parent::db_array();
     $date = new DateTime();
     $db_array['client_note_date'] = $date->format('Y-m-d');
     return $db_array;
 }
コード例 #16
0
ファイル: spielderstunde.modul.php プロジェクト: emteg/beamer
 private function eventVerarbeiten($record)
 {
     $result["Titel"] = $record["Titel"];
     $result["Beginn"] = date("D H:i", strtotime($record["Beginn"]));
     $now = new DateTime();
     $beginn = new DateTime($record["Beginn"]);
     $ende = new DateTime($record["Ende"]);
     if (strtotime($record["Beginn"]) > time()) {
         $result["hatAngefangen"] = false;
         $interval = $beginn->diff($now);
     } else {
         $result["hatAngefangen"] = true;
         $interval = $ende->diff($now);
     }
     $hours = $interval->h + $interval->days * 24;
     if ($hours == 0) {
         if ($result["hatAngefangen"]) {
             $result["Restzeit"] = $interval->format("jetzt");
         } else {
             $result["Restzeit"] = $interval->format("%im");
         }
     } else {
         if ($hours > 3) {
             $result["Restzeit"] = $hours . "h";
         } else {
             $result["Restzeit"] = $interval->format("%Hh %im");
         }
     }
     return $result;
 }
 public function testConvertDateTimeToString()
 {
     $converter = new DataToStringConverter('en');
     $data = new \DateTime();
     $expected = $data->format('d.m.Y H:i:s');
     $this->assertSame($expected, $converter->convertDataToString($data));
 }
コード例 #18
0
ファイル: Object.php プロジェクト: jdf221/Pheddit
 public function timestampToDateTime($timestamp)
 {
     date_default_timezone_set("UTC");
     $date = new \DateTime();
     $date->setTimestamp($timestamp);
     return $date;
 }
コード例 #19
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $database = $input->getArgument('database');
     $file = $input->getOption('file');
     $learning = $input->hasOption('learning') ? $input->getOption('learning') : false;
     $databaseConnection = $this->resolveConnection($io, $database);
     if (!$file) {
         $date = new \DateTime();
         $file = sprintf('%s/%s-%s.sql', $this->getSite()->getSiteRoot(), $databaseConnection['database'], $date->format('Y-m-d-h-i-s'));
     }
     $command = sprintf('mysqldump --user=%s --password=%s --host=%s --port=%s %s > %s', $databaseConnection['username'], $databaseConnection['password'], $databaseConnection['host'], $databaseConnection['port'], $databaseConnection['database'], $file);
     if ($learning) {
         $io->commentBlock($command);
     }
     $processBuilder = new ProcessBuilder(['–lock-all-tables']);
     $process = $processBuilder->getProcess();
     $process->setTty('true');
     $process->setCommandLine($command);
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
     $io->success(sprintf('%s %s', $this->trans('commands.database.dump.messages.success'), $file));
 }
コード例 #20
0
 public function createdAgo(\DateTime $dateTime)
 {
     $delta = time() - $dateTime->getTimestamp();
     if ($delta < 0) {
         throw new \InvalidArgumentException("createdAgo is unable to handle dates in the future");
     }
     $duration = "";
     if ($delta < 60) {
         // Seconds
         $time = $delta;
         $duration = $time . " second" . ($time === 0 || $time > 1 ? "s" : "") . " ago";
     } else {
         if ($delta < 3600) {
             // Mins
             $time = floor($delta / 60);
             $duration = $time . " minute" . ($time > 1 ? "s" : "") . " ago";
         } else {
             if ($delta < 86400) {
                 // Hours
                 $time = floor($delta / 3600);
                 $duration = $time . " hour" . ($time > 1 ? "s" : "") . " ago";
             } else {
                 // Days
                 $time = floor($delta / 86400);
                 $duration = $time . " day" . ($time > 1 ? "s" : "") . " ago";
             }
         }
     }
     return $duration;
 }
コード例 #21
0
 public function getToday()
 {
     $today = new \DateTime();
     $todaystring = $today->format('Y-m-d');
     $qb = $this->createQueryBuilder('i')->leftJoin('i.shiftTechnicians', 't')->where('t.begin = ?1')->orderBy('i.creation', 'asc')->setParameter(1, $todaystring);
     return $qb->getQuery()->getResult();
 }
コード例 #22
0
ファイル: CrawlerPresenter.php プロジェクト: ISCCTU/fitak
 public function actionToken($state)
 {
     // only poeple on the list should be generating new tokens
     if (!$this->context->token->checkAccess($_SERVER['REMOTE_ADDR'])) {
         echo "Oh sorry man, this is a private party!";
         mail($this->context->token->getEmail(), 'Notice', 'The token is maybe invalid!');
         $this->terminate();
     }
     // facebook example code...
     $stoken = $this->session->getSection('token');
     if (!isset($_GET['code'])) {
         $stoken->state = md5(uniqid(rand(), TRUE));
         //CSRF protection
         $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $this->context->token->getAppId() . "&redirect_uri=" . urlencode($this->link('//Crawler:token')) . "&scope=" . $this->context->token->getAppPermissions() . "&state=" . $stoken->state;
         echo "<script> top.location.href='" . $dialog_url . "'</script>";
         $this->terminate();
     }
     if (isset($stoken->state) && $stoken->state === $_GET['state']) {
         $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $this->context->token->getAppId() . "&redirect_uri=" . urlencode($this->link('//Crawler:token')) . "&client_secret=" . $this->context->token->getAppSecret() . "&code=" . $_GET['code'];
         $response = file_get_contents($token_url);
         $params = null;
         parse_str($response, $params);
         $date = new DateTime();
         $date->add(new DateInterval('PT' . $params["expires"] . 'S'));
         $this->context->token->saveToken($params['access_token'], $date);
         echo "Thanks for your token :)";
     } else {
         echo "The state does not match. You may be a victim of CSRF.";
     }
     $this->terminate();
 }
コード例 #23
0
 public function select_XCNVWKERSDLMC485DK($group_id, $valueOfWhich, $which)
 {
     global $wpdb;
     $table_name = 'wpfb_group_post_collection';
     $sql = "";
     if ($which == 'weekNo') {
         $datetime = new DateTime();
         $datetime->setISODate((int) $datetime->format('Y'), $valueOfWhich, 1);
         $interval = new DateInterval('P1D');
         $week = new DatePeriod($datetime, $interval, 6);
         $dayList = array();
         foreach ($week as $day) {
             $dayList[] = $day->format('Y-m-d g:i:s');
         }
         $sql = sprintf("select * from %s A where A.from_group_id= '%s' and A.message_creation_time between '{$dayList[0]}' and '{$dayList[6]}'", $table_name, $group_id);
     } else {
         if ($which == 'author') {
             $sql = sprintf("elect * from %s A where A.from_group_id= '%s' and A.from_profile_id = '%s'", $table_name, $group_id, $valueOfWhich);
         }
     }
     $databaseRows = $wpdb->get_results($sql, ARRAY_A);
     if ($wpdb->last_error) {
         throw new Exception($wpdb->last_error);
     }
     return $databaseRows;
 }
コード例 #24
0
 public function overwriteRead($return)
 {
     $objs = $return['objs'];
     foreach ($objs as $obj) {
         if (isset($obj->id_restaurant)) {
             $resto = new MasterRestaurantModel();
             $resto->getByID($obj->id_restaurant);
             $obj->id_restaurant = $resto->name;
         }
         if (isset($obj->id_bank)) {
             $bank = new BankModel();
             $bank->getByID($obj->id_bank);
             $obj->id_bank = $bank->bank_name;
         }
         if (isset($obj->start_fee)) {
             $date = new DateTime($obj->start_fee);
             $obj->start_fee = $date->format('d.m.Y');
         }
         if (isset($obj->end_fee)) {
             $dateEnd = new DateTime($obj->end_fee);
             $obj->end_fee = $dateEnd->format('d.m.Y');
         }
     }
     return $return;
 }
コード例 #25
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $em = $this->getContainer()->get('doctrine')->getManager();
     $scheduler = $this->getContainer()->get('scheduler');
     $campaignId = $input->getArgument('campaignId');
     $deliveryTime = new \DateTime($input->getArgument('deliverytime'));
     $month = $input->getArgument('month');
     $year = $input->getArgument('year');
     $date = $input->getArgument('date');
     // The date at which the job is to be run
     $dateParts = explode('-', $date);
     if (!checkdate($dateParts[1], $dateParts[2], $dateParts[0])) {
         $output->writeLn("<error>Invalid date or format. Correct format is Y-m-d</error>");
         return;
     }
     $now = new \DateTime();
     $output->writeln("<comment>Scheduling recommendations email started on {$now->format('Y-m-d H:i:s')}</comment>");
     // Get All Users
     $qb = $em->createQueryBuilder();
     $qb->add('select', 'DISTINCT u.id')->add('from', 'ClassCentralSiteBundle:User u')->join('u.userPreferences', 'up')->join('u.follows', 'uf')->andWhere('uf is NOT NULL')->andWhere("up.value = 1")->andWhere('u.isverified = 1')->andWhere("up.type=" . UserPreference::USER_PREFERENCE_PERSONALIZED_COURSE_RECOMMENDATIONS);
     $users = $qb->getQuery()->getArrayResult();
     $scheduled = 0;
     $dt = new \DateTime($date);
     $deliveryTime = $deliveryTime->format(\DateTime::RFC2822);
     foreach ($users as $user) {
         $id = $scheduler->schedule($dt, RecommendationEmailJob::RECOMMENDATION_EMAIL_JOB_TYPE, 'ClassCentral\\MOOCTrackerBundle\\Job\\RecommendationEmailJob', array('campaignId' => $campaignId, 'deliveryTime' => $deliveryTime, 'month' => $month, 'year' => $year), $user['id']);
         if ($id) {
             $scheduled++;
         }
     }
     $output->writeln("<info>{$scheduled} recommendation emails jobs scheduled</info>");
 }
コード例 #26
0
ファイル: ResultTest.php プロジェクト: nlegoff/Phraseanet
 public function testFormatYaml()
 {
     $server = ['HTTP_ACCEPT' => 'application/yaml', 'REQUEST_METHOD' => 'GET', 'SCRIPT_FILENAME' => 'my/base/path/my/request/uri/filename', 'REQUEST_URI' => 'my/base/path/my/request/uri', 'PHP_SELF' => 'my/base/path'];
     $request = new Request(["callback" => ""], [], [], [], [], $server);
     $apiResult = new Result($request);
     $response = (new Parser())->parse($apiResult->createResponse()->getContent());
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response);
     $this->assertArrayHasKey("meta", $response);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response["meta"]);
     $this->assertArrayHasKey("response", $response);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response["response"]);
     $this->assertEquals(0, count($response["response"]));
     $this->assertArrayHasKey("api_version", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["api_version"]);
     $this->assertEquals(V1::VERSION, $response["meta"]["api_version"]);
     $this->assertArrayHasKey("request", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["request"]);
     $this->assertEquals("GET my/base/path/my/request/uri", $response["meta"]["request"]);
     $this->assertArrayHasKey("response_time", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["response_time"]);
     $this->assertDateAtom($response["meta"]["response_time"]);
     $dateObj1 = \DateTime::createFromFormat(DATE_ATOM, $response["meta"]["response_time"]);
     $dateObj2 = new \DateTime();
     $this->assertLessThan(3, abs($dateObj1->format('U') - $dateObj2->format('U')), 'No more than 3sec between now and the query');
     $this->assertArrayHasKey("http_code", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $response["meta"]["http_code"]);
     $this->assertEquals(200, $response["meta"]["http_code"]);
     $this->assertArrayHasKey("error_message", $response["meta"]);
     $this->assertNull($response["meta"]["error_message"]);
     $this->assertArrayHasKey("error_details", $response["meta"]);
     $this->assertNull($response["meta"]["error_details"]);
     $this->assertArrayHasKey("charset", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["charset"]);
     $this->assertEquals("UTF-8", $response["meta"]["charset"]);
 }
コード例 #27
0
 function testInternationalTime()
 {
     $date = new DateTime('2015-09-28 05:00:00', new DateTimeZone('europe/amsterdam'));
     $twig = "{{'" . $date->format('g:i') . "'|date('g:i')}}";
     $str = Timber::compile_string($twig);
     $this->assertEquals('5:00', $str);
 }
コード例 #28
0
 /**
  * Daily social statistic collect
  * Add new access token to Queue
  *
  * @access public
  * @return void
  */
 public function run()
 {
     $types = array('twitter');
     $tokens = Access_token::inst()->where_in('type', $types)->get();
     $aac = $this->getAAC();
     $now = new \DateTime('UTC');
     foreach ($tokens as $_token) {
         $now->modify('1 minutes');
         $user = new User($_token->user_id);
         if (!$user->exists()) {
             continue;
         }
         $aac->setUser($user);
         if (!$aac->isGrantedPlan('social_activity')) {
             continue;
         }
         $args = $_token->to_array();
         foreach ($_token->social_group->get() as $profile) {
             $args['profile_id'] = $profile->id;
             //Twitter tasks
             $this->jobQueue->addJob('tasks/twitter_task/searchUsers', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
             $this->jobQueue->addJob('tasks/twitter_task/updateFollowers', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
             $this->jobQueue->addJob('tasks/twitter_task/randomRetweet', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
             $this->jobQueue->addJob('tasks/twitter_task/randomFavourite', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
             $this->jobQueue->addJob('tasks/twitter_task/sendWelcomeMessage', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
             $this->jobQueue->addJob('tasks/twitter_task/followNewFollowers', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
             $this->jobQueue->addJob('tasks/twitter_task/unfollowUnsubscribedUsers', $args, array('thread' => self::SOCIAL_THREAD, 'execute_after' => $now));
         }
     }
 }
コード例 #29
0
 public static function ISSUEDATE()
 {
     $Date = new DateTime('now');
     $randomDate = mt_rand($Date->getTimestamp(), $Date->getTimestamp() + 15000000);
     $newRanDate = date("Y-m-d", $randomDate);
     return $newRanDate;
 }
コード例 #30
-1
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $em = $this->getContainer()->get('doctrine')->getManager();
     $scheduler = $this->getContainer()->get('scheduler');
     $subject = $input->getArgument('subject');
     $template = $input->getArgument('template');
     $campaignId = $input->getArgument('campaignId');
     $deliveryTime = new \DateTime($input->getArgument('deliverytime'));
     $date = $input->getArgument('date');
     // The date at which the job is to be run
     $dateParts = explode('-', $date);
     if (!checkdate($dateParts[1], $dateParts[2], $dateParts[0])) {
         $output->writeLn("<error>Invalid date or format. Correct format is Y-m-d</error>");
         return;
     }
     $now = new \DateTime();
     $output->writeln("<comment>Scheduling announcement email started on {$now->format('Y-m-d H:i:s')}</comment>");
     // Get All Users
     $qb = $em->createQueryBuilder();
     $qb->add('select', 'u.id')->add('from', 'ClassCentralSiteBundle:User u')->join('u.userPreferences', 'up')->andWhere("up.value = 1")->andWhere("up.type=" . UserPreference::USER_PREFERENCE_FOLLOW_UP_EMAILs);
     $users = $qb->getQuery()->getArrayResult();
     $scheduled = 0;
     foreach ($users as $user) {
         $id = $scheduler->schedule(new \DateTime($date), AnnouncementEmailJob::ANNOUNCEMENT_EMAIL_JOB_TYPE, 'ClassCentral\\MOOCTrackerBundle\\Job\\AnnouncementEmailJob', array('template' => $template, 'subject' => $subject, 'campaignId' => $campaignId, 'deliveryTime' => $deliveryTime->format(\DateTime::RFC2822)), $user['id']);
         if ($id) {
             $scheduled++;
         }
     }
     $output->writeln("<info>{$scheduled} jobs scheduled</info>");
 }