Example #1
0
 public function dateto()
 {
     date_default_timezone_set('Asia/Bangkok');
     $now = new DateTime(null, new DateTimeZone('Asia/Bangkok'));
     $Y = $now->format('Y') + 543;
     return $now->format('d/m/') . $Y . $now->format(' H:i');
 }
 /**
  * Load rates by date
  *
  * @param ICurrency[] $currencies
  * @param \DateTime|null $date
  *
  * @return ICurrencyRate[]
  *
  * @throws NoRatesAvailableForDateException
  * @throws BadXMLQueryException
  */
 public function getRates($currencies, \DateTime $date = null)
 {
     $currencyCodes = [];
     foreach ($currencies as $currency) {
         $currencyCodes[] = $currency->getCode() . '=X';
     }
     if (null === $date) {
         $date = new \DateTime();
     }
     $queryData = ['q' => 'select * from yahoo.finance.historicaldata where symbol in ("' . implode('","', $currencyCodes) . '") and startDate = "' . $date->format('Y-m-d') . '" and endDate = "' . $date->format('Y-m-d') . '"', 'env' => 'store://datatables.org/alltableswithkeys'];
     $query = self::BASE_URL . '?' . http_build_query($queryData);
     $ratesXml = $this->xmlLoader->load($query);
     if (false === $ratesXml) {
         throw new BadXMLQueryException($query, $this);
     }
     if (0 === count($ratesXml->results->quote)) {
         throw new NoRatesAvailableForDateException($date, $this);
     }
     $rates = [];
     /** @var \SimpleXMLElement $rate */
     foreach ($ratesXml->results->quote as $quote) {
         $quote = (array) $quote;
         $code = (string) $quote['@attributes']['Symbol'];
         $code = str_replace('%3dX', '', $code);
         $rate = $quote['Close'];
         $rates[$code] = $this->currencyRateManager->getNewInstance($this->currencyManager->getCurrency($code), $this, $date, (double) $rate, 1);
     }
     return $rates;
 }
Example #3
0
 /**
  * 
  * function val - This function allows validate the date format and if it's true
  * return the same date if it's not throw and exception.
  * 
  * @param string $val 
  * @return string
  * @throws \SimplOn\DataValidationException
  */
 function val($val = null)
 {
     // if $val is defined and isn't null, start to verify the value
     if (isset($val) && $val) {
         $val = trim($val);
         //if $val is empty and is required then throw an exception.
         if (!$val && $this->required) {
             throw new \SimplOn\DataValidationException($this->validationDate);
         } else {
             try {
                 if (is_numeric($val)) {
                     $dateObj = new \DateTime();
                     $dateObj->setTimestamp($val);
                 } else {
                     $dateObj = new \DateTime($val);
                     // throw new \SimplOn\DataValidationException($this->isnotNumeric);
                 }
             } catch (\Exception $e) {
                 throw new \SimplOn\DataValidationException($this->validationDate);
             }
         }
         // $this->val save the date with format for database
         $this->val = $dateObj->format($this->dbFormat);
         // $this->viewVal save the the date with format to show in the view
         $this->viewVal = $dateObj->format($this->viewFormat);
     } else {
         return $this->val;
     }
 }
Example #4
0
 public function indexAction()
 {
     $em = $this->EntityPlugin()->getEntityManager();
     $auth = $this->getServiceLocator()->get('Zend\\Authentication\\AuthenticationService');
     $user = $auth->getIdentity();
     $year = $this->params()->fromRoute('year');
     $date = new \DateTime();
     if (!empty($year)) {
         $date->setDate($year, 1, 1);
     }
     $operationsSummaryIncome = $em->getRepository('HouseholdBudget\\Entity\\Operation')->getMonthlySummaryByType($user->getId(), 'income', $date->format('Y'));
     $operationsSummaryExpense = $em->getRepository('HouseholdBudget\\Entity\\Operation')->getMonthlySummaryByType($user->getId(), 'expense', $date->format('Y'));
     $highestIncome = 0;
     foreach ($operationsSummaryIncome as $income) {
         if ($highestIncome < $income['total']) {
             $highestIncome = $income['total'];
         }
     }
     $highestExpense = 0;
     foreach ($operationsSummaryExpense as $expense) {
         if ($highestExpense < $expense['total']) {
             $highestExpense = $expense['total'];
         }
     }
     echo '<pre>';
     //        echo var_dump($operationsSummaryIncome);
     //        echo var_dump($operationsSummaryExpense);
     echo '</pre>';
     return new ViewModel(array('operationsSummaryIncome' => $operationsSummaryIncome, 'operationsSummaryExpense' => $operationsSummaryExpense, 'highestValue' => $highestIncome > $highestExpense ? $highestIncome : $highestExpense, 'date' => $date));
 }
Example #5
0
 /**
  *
  */
 public function execute()
 {
     $skeleton = file_get_contents($this->config->getTemplateFilename());
     $skeleton = $this->replacePlaceholder($skeleton, '%%VERSION%%', $this->version->getVersion());
     $skeleton = $this->replacePlaceholder($skeleton, '%%DATE%%', $this->now->format('Y-m-d H:i:sO'));
     $this->writeSkeletonFile($skeleton);
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     $fields->removeByName('ConfiguredScheduleID');
     $interval = $fields->dataFieldByName('Interval')->setDescription('Number of seconds between each run. e.g 3600 is 1 hour');
     $fields->replaceField('Interval', $interval);
     $dt = new DateTime();
     $fields->replaceField('StartDate', DateField::create('StartDate')->setConfig('dateformat', 'dd/MM/yyyy')->setConfig('showcalendar', true)->setDescription('DD/MM/YYYY e.g. ' . $dt->format('d/m/y')));
     $fields->replaceField('EndDate', DateField::create('EndDate')->setConfig('dateformat', 'dd/MM/yyyy')->setConfig('showcalendar', true)->setDescription('DD/MM/YYYY e.g. ' . $dt->format('d/m/y')));
     if ($this->ID == null) {
         foreach ($fields->dataFields() as $field) {
             //delete all included fields
             $fields->removeByName($field->Name);
         }
         $rangeTypes = ClassInfo::subclassesFor('ScheduleRange');
         $fields->addFieldToTab('Root.Main', TextField::create('Title', 'Title'));
         $fields->addFieldToTab('Root.Main', DropdownField::create('ClassName', 'Range Type', $rangeTypes));
     } else {
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('ClassName', 'Type'));
     }
     if ($this->ClassName == __CLASS__) {
         $fields->removeByName('ApplicableDays');
     }
     return $fields;
 }
Example #7
0
function datimeStdFormat($relation, $DateConcept, $srcAtom, $StdFormatConcept, $formatSpec)
{
    Logger::getLogger('EXECENGINE')->debug("datimeStdFormat({$relation},{$DateConcept},{$srcAtom},{$StdFormatConcept},{$formatSpec})");
    $date = new DateTime($srcAtom);
    InsPair($relation, $DateConcept, $srcAtom, $StdFormatConcept, $date->format($formatSpec));
    Logger::getLogger('EXECENGINE')->debug("Date format {$srcAtom} changed to {$date->format($formatSpec)}");
}
Example #8
0
 public function makeDecision(DBFarmRole $dbFarmRole, Scalr_Scaling_FarmRoleMetric $farmRoleMetric, $isInvert = false)
 {
     // Get data from BW sensor
     $dbFarm = $dbFarmRole->GetFarmObject();
     $tz = $dbFarm->GetSetting(Entity\FarmSetting::TIMEZONE);
     $date = new DateTime();
     if ($tz) {
         $date->setTimezone(new DateTimeZone($tz));
     }
     $currentDate = array((int) $date->format("Hi"), $date->format("D"));
     $scaling_period = $this->db->GetRow("\n            SELECT * FROM farm_role_scaling_times\n            WHERE '{$currentDate[0]}' >= start_time\n            AND '{$currentDate[0]}' <= end_time\n            AND INSTR(days_of_week, '{$currentDate[1]}') != 0\n            AND farm_roleid = '{$dbFarmRole->ID}'\n            LIMIT 1\n        ");
     if ($scaling_period) {
         $this->logger->info("TimeScalingAlgo({$dbFarmRole->FarmID}, {$dbFarmRole->ID}) Found scaling period. Total {$scaling_period['instances_count']} instances should be running.");
         $this->instancesNumber = $scaling_period['instances_count'];
         $this->lastValue = "(" . implode(' / ', $currentDate) . ") {$scaling_period['start_time']} - {$scaling_period['end_time']} = {$scaling_period['instances_count']}";
         if ($dbFarmRole->GetRunningInstancesCount() + $dbFarmRole->GetPendingInstancesCount() < $this->instancesNumber) {
             return Scalr_Scaling_Decision::UPSCALE;
         } elseif ($dbFarmRole->GetRunningInstancesCount() + $dbFarmRole->GetPendingInstancesCount() > $this->instancesNumber) {
             return Scalr_Scaling_Decision::DOWNSCALE;
         } else {
             return Scalr_Scaling_Decision::NOOP;
         }
     } else {
         if ($dbFarmRole->GetRunningInstancesCount() > $dbFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_MIN_INSTANCES)) {
             $this->lastValue = "No period defined. Using Min instances setting.";
             return Scalr_Scaling_Decision::DOWNSCALE;
         } else {
             return Scalr_Scaling_Decision::NOOP;
         }
     }
 }
 /**
  * @param string $date
  * @return string
  */
 private function getJulianDate($date = 'now')
 {
     $dateTime = new \DateTime($date);
     $year = $dateTime->format('y');
     $day = str_pad($dateTime->format('z'), 3, 0, STR_PAD_LEFT);
     return $year . $day;
 }
function createAdminReservation($adminid, $userid, $equipid, $startdate, $length, $usercomment, $admincomment, $modstatus)
{
    $adminid = makeStringSafe($adminid);
    $userid = makeStringSafe($userid);
    $equipid = makeStringSafe($equipid);
    $startdate = makeStringSafe($startdate);
    $length = makeStringSafe($length);
    $usercomment = makeStringSafe($usercomment);
    $admincomment = makeStringSafe($admincomment);
    $modstatus = makeStringSafe($modstatus);
    $start_Date = new DateTime('' . $startdate . ' 00:00:00');
    $start_Date->modify("+" . $length . " day");
    //$interval = new DateInterval("P".$length."D");
    //$start_Date->add($interval);
    $enddate = $start_Date->format("Y-m-d");
    $tempdate = new DateTime('' . $enddate . ' 00:00:00');
    while ($tempdate->format("D") == "Sat" || $tempdate->format("D") == "Sun") {
        //$tempdate->add(new DateInterval("P1D"));
        $tempdate->modify("+1 day");
        $length = $length + 1;
    }
    $enddate = $tempdate->format("Y-m-d");
    doQuery("INSERT INTO " . getDBPrefix() . "_reservations SET user_id = '" . $userid . "', equip_id = '" . $equipid . "', start_date = '" . $startdate . "', end_date = '" . $enddate . "', length = '" . $length . "', pickup_time = '', user_comment = '" . $usercomment . "', admin_comment = '" . $admincomment . "', mod_status = '" . $modstatus . "'");
    $res = mysql_fetch_assoc(doQuery("SELECT res_id FROM " . getDBPrefix() . "_reservations ORDER BY res_id DESC LIMIT 1"));
    logAdminCreateReservation($adminid, $userid, $res['res_id']);
}
 public function getCurrent(\DateTime $now)
 {
     $date = new \DateTime();
     $date->setTimestamp(strtotime(sprintf('%s %s of %s %d', $this->getOrdinal(), $this->getDay(), $now->format('F'), $now->format('Y'))));
     $date->setTime($now->format('H'), $now->format('i'));
     return $date;
 }
Example #12
0
 /**
  * Validate a date.
  *
  * <code>
  * $date = "01-01-2020";
  *
  * $validator = new Prism\Validator\Date($date);
  *
  * if (!$validator->isValid()) {
  * ...
  * }
  *
  * </code>
  *
  * @return bool
  */
 public function isValid()
 {
     // Check for default SQL values.
     $defaultDates = array('0000-00-00', '1000-01-01');
     if (in_array($this->date, $defaultDates, true)) {
         return false;
     }
     $string = trim($this->date);
     if ($string === '') {
         return false;
     }
     if (is_numeric($string)) {
         $string = (int) $string;
         if ($string === 0) {
             return false;
         }
         $string = '@' . $string;
     }
     try {
         $date = new \DateTime($string);
     } catch (\Exception $e) {
         return false;
     }
     $month = $date->format('m');
     $day = $date->format('d');
     $year = $date->format('Y');
     if (checkdate($month, $day, $year)) {
         return true;
     } else {
         return false;
     }
 }
Example #13
0
 public function testFormatTime()
 {
     $this->assertEquals($this->_dateTime->format(self::TIME_FORMAT_SHORT), $this->_helper->formatTime());
     $this->assertEquals($this->_dateTime->format(self::DATETIME_FORMAT_SHORT), $this->_helper->formatTime(null, 'short', true));
     $zendDate = new Zend_Date($this->_dateTime->format('U'));
     $this->assertEquals($zendDate->toString(self::TIME_FORMAT_SHORT_ISO), $this->_helper->formatTime($zendDate, 'short'));
 }
Example #14
0
function getGraphData($users_UserID, $type, $start_date, $end_date)
{
    // Global variables provided by config.php for DB connection.
    global $con, $host, $user, $password, $db;
    if (mysqli_connect_errno()) {
        die('Could not connect: ' . mysqli_connect_error());
    }
    //Initialize index variable.
    $index = 0;
    $start_date = new DateTime($start_date);
    $end_date = new DateTime($end_date);
    while ($start_date <= $end_date) {
        $query = "SELECT * FROM sensors WHERE users_UserID = '" . $users_UserID . "' AND Type = '" . $type . "' AND Date >= '" . $start_date->format("Y-m-d") . ' 00:00:00' . "' AND Date <= '" . $start_date->format("Y-m-d") . ' 23:59:59' . "'";
        if ($result = mysqli_query($con, $query)) {
            $rowcount = mysqli_num_rows($result);
            if ($rowcount == 0) {
                // No Data for this date -- So fill with 0.
                $graphdata[$index] = 0;
            } else {
                while ($rows = mysqli_fetch_array($result)) {
                    // Insert Data into array.
                    $graphdata[$index] = $rows['Data'];
                }
            }
            mysqli_free_result($result);
        } else {
            die('Error:' . mysqli_error($con));
        }
        //Increment Start Date
        $start_date->modify('+1 day');
        //Increment index variable.
        $index++;
    }
    return $graphdata;
}
 public function __construct()
 {
     $this->cachedAttributes = array();
     $date = new DateTime();
     $this->cachedAttributes["mno_session"] = "7ds8f9789a7fd7x0b898bvb8vc9h0gg";
     $this->cachedAttributes["mno_session_recheck"] = $date->format(DateTime::ISO8601);
     $this->cachedAttributes["group_uid"] = "cld-1";
     $this->cachedAttributes["group_name"] = "SomeGroupName";
     $this->cachedAttributes["group_email"] = "*****@*****.**";
     $this->cachedAttributes["group_role"] = "Admin";
     $this->cachedAttributes["group_end_free_trial"] = $date->format(DateTime::ISO8601);
     $this->cachedAttributes["group_has_credit_card"] = "true";
     $this->cachedAttributes["group_currency"] = "USD";
     $this->cachedAttributes["group_timezone"] = "America/Los_Angeles";
     $this->cachedAttributes["group_country"] = "US";
     $this->cachedAttributes["group_city"] = "Los Angeles";
     $this->cachedAttributes["uid"] = "usr-1";
     $this->cachedAttributes["virtual_uid"] = "user-1.cld-1";
     $this->cachedAttributes["email"] = "*****@*****.**";
     $this->cachedAttributes["virtual_email"] = "*****@*****.**";
     $this->cachedAttributes["name"] = "John";
     $this->cachedAttributes["surname"] = "Doe";
     $this->cachedAttributes["country"] = "AU";
     $this->cachedAttributes["company_name"] = "DoeCorp";
 }
 function converterFromDBtoUser($str)
 {
     if ($str === NULL || $str === '' || $str === '0000-00-00') {
         return '';
     }
     $sp = strpos($str, ' ');
     $slash = substr_count($str, '-');
     $colon = substr_count($str, ':');
     $dtObj = false;
     if ($sp !== FALSE && $slash == 2 && $colon == 2) {
         $sep = explode(' ', $str);
         $comp = explode('-', $sep[0]);
         $dtObj = new DateTime($comp[0] . '-' . $comp[1] . '-' . $comp[2] . ' ' . $sep[1], new DateTimeZone($this->tz));
         $fmt = '%x %H:%M:%S';
     } elseif ($sp === FALSE && $slash == 2 && $colon == 0) {
         $comp = explode('-', $str);
         $dtObj = new DateTime($comp[0] . '-' . $comp[1] . '-' . $comp[2], new DateTimeZone($this->tz));
         $fmt = '%x';
     } elseif ($sp === FALSE && $slash == 0 && $colon == 2) {
         $dtObj = new DateTime($str, new DateTimeZone($this->tz));
         $fmt = '%H:%M:%S';
     }
     if ($dtObj === false) {
         return $str;
     }
     if (strftime('%Y', $dtObj->format('U')) < 1970) {
         return '';
     }
     return strftime($this->fmt == '' ? $fmt : $this->fmt, $dtObj->format('U'));
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     //$datetime = Carbon::now('Asia/Bangkok');
     $date = new DateTime();
     $date->setTimezone(new DateTimeZone('Asia/Bangkok'));
     DB::table('users')->insert(['name' => 'Pathma In', 'firstName' => 'Pathma', 'lastName' => 'Inpromma', 'cardID' => '1490300066761', 'phone' => '0909359085', 'code' => $date->format('YmdHis'), 'email' => '*****@*****.**', 'password' => bcrypt('kantavee'), 'created_at' => $date->format('Y-m-d H:i:s'), 'role' => 99]);
 }
Example #18
0
 public function sendSms($receiver, $txnId)
 {
     $receiver = self::mobileFormat($receiver);
     if ($receiver && $txnId) {
         $db = new DBHandler();
         $db->connect();
         $lead = $db->retrieveLeadByTxnId($txnId);
         $sender = "TNF100PH";
         $msg = "Congratulations! You have successfully registered to 2016 TNF 100! Check your email for your reg summary. Get your favorite TNF items using this exclusive discount coupon code: " . $lead['coupon_code'] . ". Present the code at the time of purchase. See you on April 30-May 1. Break all boundaries!";
         $sema = new SemaphoreClient();
         $response = $sema->sendSms($receiver, $sender, $msg);
         $date = new DateTime('now');
         $msgstat = (int) $response->code;
         if ((int) $response->code >= 200) {
             $network = self::getNetworkByMobile($response->to);
             $data = array("msg_type" => "online registration", "mobile" => $response->to, "network" => $network, "shortcode" => $response->from, "date_received" => $date->format('Y-m-d G:i:s'), "channel" => "TNF 100 2016 Registration", "message_id" => $response->message_id, "message" => $msg, "full_msg" => json_encode($response), "msg_status" => $response->code . ': ' . $response->status, "status" => strtoupper($response->status));
             self::saveOutbox($lead, $data, $txnId);
         } else {
             $msgstat = 0;
             $network = self::getNetworkByMobile($receiver);
             $data = array("msg_type" => "error", "mobile" => $receiver, "network" => $network, "shortcode" => $sender, "date_received" => $date->format('Y-m-d G:i:s'), "channel" => "TNF 100 2016 Registration", "message" => $msg, "full_msg" => json_encode($response), "msg_status" => $response->code . ': ' . $response->status, "status" => strtoupper($response->status));
             self::saveOutbox($lead, $data, $txnId);
         }
     }
 }
Example #19
0
 function __construct()
 {
     if (isset($_POST['recordUser'])) {
         $this->login = $_POST['login'];
         $this->name = $_POST['nombre'];
         $this->email = $_POST['email'];
         $this->firma = $_POST['firma'];
         $date = new DateTime();
         $day = $date->format("Y-m-d");
         $time = $date->format("h:i:s");
         $this->dateTime = $day . " " . $time;
         if ($this->checkInputs()) {
             parent::connect();
             if ($this->noIssetNickName()) {
                 if ($this->regUser()) {
                     $this->textConfirm = "¡El usuario se ha creado con éxito!";
                 } else {
                     $this->showMessage("No se ha podido registrar el usuario, vuelva a intentarlo más tarde.");
                 }
             } else {
                 $this->failLogin = "******";
             }
         }
     }
 }
Example #20
0
 /**
  * @see \eZ\Publish\Core\FieldType\Value
  */
 public function __toString()
 {
     if (!$this->value instanceof DateTime) {
         return "";
     }
     return $this->value->format($this->stringFormat);
 }
 /**
  * Render the supplied DateTime object as a formatted date.
  *
  * @param mixed $date either a DateTime object or a string that is accepted by DateTime constructor
  * @param string $format Format String which is taken to format the Date/Time
  * @param bool $currentDate if true, the current date is used
  * @param bool $strftime if true, the strftime is used instead of date()
  * @throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
  * @return string Formatted date
  */
 public function render($date = null, $format = '%Y-%m-%d', $currentDate = false, $strftime = true)
 {
     if ($currentDate) {
         if ($strftime) {
             return strftime($format, $GLOBALS['EXEC_TIME']);
         } else {
             return date($format, $GLOBALS['EXEC_TIME']);
         }
     }
     if ($date === null) {
         $date = $this->renderChildren();
         if ($date === null) {
             return '';
         }
     }
     if (!$date instanceof \DateTime) {
         try {
             $date = new \DateTime($date);
         } catch (\Exception $exception) {
             throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('"' . $date . '" could not be parsed by DateTime constructor.', 1241722579);
         }
     }
     if ($strftime) {
         return strftime($format, $date->format('U'));
     } else {
         return date($format, $date->format('U'));
     }
 }
Example #22
0
 public function action_create()
 {
     if (HTTP_Request::POST == $this->request->method()) {
         try {
             $date = new DateTime();
             $user = ORM::factory('User');
             $user->email = $this->request->post('email');
             $user->password = $this->request->post('password');
             $user->is_active = 1;
             $user->created_at = $date->format('Y-m-d H:i:s');
             $user->updated_at = $date->format('Y-m-d H:i:s');
             $user->save();
             // Grant user login role
             $user->add('roles', ORM::factory('Role', array('name' => 'agent')));
             // Reset values so form is not sticky
             $_POST = array();
             // Set success message
             $message = "You have added user '{$user->email}' to the database";
         } catch (ORM_Validation_Exception $e) {
             // Set failure message
             $message = 'There were errors, please see form below.';
             // Set errors using custom messages
             $errors = $e->errors('models');
         }
     }
     $this->template->content = View::factory('user/create')->bind('errors', $errors)->bind('message', $message);
 }
Example #23
0
function handlePost($app, $request)
{
    // Timestamp & reverse-timestamp
    $odt = new DateTime('now', new DateTimeZone("Europe/Amsterdam"));
    $timestamp = $odt->format("Y-m-d H:i");
    $rtimestamp = $odt->format("siHdmY");
    try {
        $uuid1 = Uuid::uuid1();
        // Make sure the media file was uploaded without error
        $file = $request->files->get('mediaFile');
        if (!$file instanceof UploadedFile || $file->getError()) {
            throw new \InvalidArgumentException('The file is not valid.');
        }
        $ofilename = $rtimestamp . '-' . $file->getFilename();
        // create a thumbnail
        $image = $app['imagine']->open($file->getPathname());
        $tfilename = $rtimestamp . '-' . $file->getFilename() . '-thumb.jpeg';
        $tfilepath = $file->getPath() . '/' . $tfilename;
        $image->resize(new Box(200, 200))->save($tfilepath);
        // Upload the original media file to S3
        $ores = $app['aws.s3']->upload($app['env.orig'], $ofilename, fopen($file->getPathname(), 'r'), 'public-read');
        // upload the thumbnail
        $tres = $app['aws.s3']->upload($app['env.trans'], $tfilename, fopen($tfilepath, 'r'), 'public-read');
        // add file metadata
        $dynamoDbResult = $app['aws.ddb']->putItem(['TableName' => $app['env.table'], 'Item' => ['owner' => ['S' => 'PHP-User'], 'uid' => ['S' => $uuid1->toString()], 'timestamp' => ['S' => $timestamp], 'description' => ['S' => (string) $request->request->get('caption')], 'name' => ['S' => $file->getClientOriginalName()], 'source' => ['S' => $ofilename], 'thumbnail' => ['S' => $tfilename]]]);
        return array('type' => 'success', 'message' => 'File uploaded.');
    } catch (Exception $e) {
        // @TODO if something fails, rollback any object uploads
        return array('type' => 'error', 'message' => "Error uploading your photo:" . $e);
    }
}
Example #24
0
 /**
  * Updates the Date and Time.
  *
  * @param \DateTime $dt
  * @param int $dateType
  * @return void
  */
 public function setDateTime(\DateTime $dt, $dateType = self::LOCALTZ)
 {
     switch ($dateType) {
         case self::LOCAL:
             $this->setValue($dt->format('Ymd\\THis'));
             $this->offsetUnset('VALUE');
             $this->offsetUnset('TZID');
             $this->offsetSet('VALUE', 'DATE-TIME');
             break;
         case self::UTC:
             $dt->setTimeZone(new \DateTimeZone('UTC'));
             $this->setValue($dt->format('Ymd\\THis\\Z'));
             $this->offsetUnset('VALUE');
             $this->offsetUnset('TZID');
             $this->offsetSet('VALUE', 'DATE-TIME');
             break;
         case self::LOCALTZ:
             $this->setValue($dt->format('Ymd\\THis'));
             $this->offsetUnset('VALUE');
             $this->offsetUnset('TZID');
             $this->offsetSet('VALUE', 'DATE-TIME');
             $this->offsetSet('TZID', $dt->getTimeZone()->getName());
             break;
         case self::DATE:
             $this->setValue($dt->format('Ymd'));
             $this->offsetUnset('VALUE');
             $this->offsetUnset('TZID');
             $this->offsetSet('VALUE', 'DATE');
             break;
         default:
             throw new \InvalidArgumentException('You must pass a valid dateType constant');
     }
     $this->dateTime = $dt;
     $this->dateType = $dateType;
 }
Example #25
0
 public function get_graph_url($name, $num_days = 40)
 {
     global $g_db;
     $select = $g_db->select()->from('stats', array('date', 'value'))->where('name = ?', $name)->order(array('date DESC'))->limit($num_days + 5);
     $values = array();
     $rows = $g_db->fetchAll($select);
     foreach ($rows as $row) {
         $values[$row['date']] = $row['value'];
     }
     $dates = array();
     $labels = array();
     $date = new DateTime();
     $one_day = new DateInterval("P1D");
     for ($i = 0; $i < $num_days; $i++) {
         $dates[] = $date->format('Y-m-d');
         if ($i % 5 == 0) {
             $labels[] = $date->format('d/m');
         }
         $date->sub($one_day);
     }
     $labels = array_reverse($labels);
     $max_value = max(array_values($values));
     $max_value += floor(0.1 * $max_value);
     $data = "";
     for ($i = 0; $i < $num_days; $i++) {
         $value = $values[$dates[$num_days - $i - 1]];
         $data .= is_null($value) ? "_" : self::encode_number_e($value, $max_value);
     }
     return "http://chart.apis.google.com/chart" . "?chxl=1:|" . implode("|", $labels) . "&chxr=0,0,{$max_value}" . "&chxt=y,x" . "&chs=460x150" . "&cht=lc" . "&chco=3D7930" . "&chd=e:{$data}" . "&chg=7.15,-1,1,0" . "&chm=B,C5D4B5BB,0,0,0";
 }
 /**
  * @param \DateTime $date
  *
  * @return bool
  */
 public function isWeekend(\DateTime $date)
 {
     if ($date instanceof \DateTime && ($date->format('N') == 6 || $date->format('N') == 7)) {
         return true;
     }
     return false;
 }
 protected function create_wp_comment($action_id, $message, DateTime $date)
 {
     $comment_date_gmt = $date->format('Y-m-d H:i:s');
     $date->setTimezone(ActionScheduler_TimezoneHelper::get_local_timezone());
     $comment_data = array('comment_post_ID' => $action_id, 'comment_date' => $date->format('Y-m-d H:i:s'), 'comment_date_gmt' => $comment_date_gmt, 'comment_author' => self::AGENT, 'comment_content' => $message, 'comment_agent' => self::AGENT, 'comment_type' => self::TYPE);
     return wp_insert_comment($comment_data);
 }
 protected function isScheduleSatisfied(\DateTime $time)
 {
     // the loop will iterate thru all elements to avoid hidden errors
     // in schedule definition; if it would return false in the instant
     // the schedule is not satisfied, errors in later schedule def parts
     // would be hidden until the preceding schedule part is satisfied;
     // therefore the optimization would be error-prone and is not used
     $satisfied = true;
     foreach (explode(' ', $this->schedule) as $index => $def) {
         switch ($index) {
             case 0:
                 $satisfied &= $this->isSchedulePartSatisfied($def, $time->format('i'));
                 break;
             case 1:
                 $satisfied &= $this->isSchedulePartSatisfied($def, $time->format('H'));
                 break;
             case 2:
                 $satisfied &= $this->isSchedulePartSatisfied($def, $time->format('j'));
                 break;
             case 3:
                 $satisfied &= $this->isSchedulePartSatisfied($def, $time->format('n'));
                 break;
             case 4:
                 $satisfied &= $this->isSchedulePartSatisfied($def, $time->format('w'));
                 break;
             default:
                 $satisfied &= false;
                 break;
         }
     }
     return $satisfied;
 }
Example #29
0
 function getEvents($feedURL, $maxItems = 10, $backfill = 0)
 {
     $eventsXML = simplexml_load_file($feedURL);
     if (!$eventsXML) {
         echo 'Visit events.uoit.ca to see all events.';
     }
     $minItems = 5;
     $itemCount = 1;
     foreach ($eventsXML->channel->item as $event) {
         if ($itemCount <= $maxItems) {
             $title = $event->title;
             $description = $event->description;
             $url = $event->link;
             $unixdate = $event->date;
             $date = new DateTime();
             $date->setTimestamp((int) $unixdate);
             $monthDisplay = $date->format('M');
             $dayDisplay = $date->format('d');
             $time = $event->time;
             $location = $event->location;
             echo "<li data-equalizer style='display:block;float:none;width:100%;padding:0;'>\n\t\t\t\t    \t<a href='" . $url . "' target='_blank'>\n\t\t\t\t        <p class='event_date' data-equalizer-watch>" . $monthDisplay . "\n\t\t\t\t            <span>" . $dayDisplay . "</span>\n\t\t\t\t        </p>\n\t\t\t\t        <p class='event_info' data-equalizer-watch>\n\t\t\t\t          <span class='event_title'>" . $title . "</span>\n\t\t\t\t          <span class='event_time'>" . $location . "\n\t\t\t\t          <br>" . $time . "</span>\n\t\t\t\t        </p>\n\t\t\t\t      </a>\n\t\t\t\t    </li>";
             $itemCount++;
         }
     }
     if ($itemCount <= 5 && $backfill == '1') {
         getEvents("http://events.uoit.ca/api/v1/rss");
     }
 }
Example #30
0
 /**
  * Builds and creates the Atom XML nodes required by this date
  *
  * The element node representing this date is created separately and
  * passed as the first parameter of this method.
  *
  * @param DOMNode $node the node representing this date.
  *
  * @return void
  */
 protected function _buildNode(DOMNode $node)
 {
     $document = $node->ownerDocument;
     $date_string = $this->_date->format('c');
     $text_node = $document->createTextNode($date_string);
     $node->appendChild($text_node);
 }