예제 #1
0
파일: WxUtil.php 프로젝트: jurimengs/bangsm
 /**
  * save token to db
  */
 public static function initWxTokenToDB()
 {
     global $db;
     $url = wxTokenUrl() . "&appid=" . appid() . "&secret=" . secret();
     // 请求微信token
     //LogUtil::logs("initWxTokenToDB tokenurl====>".$url, getLogFile('/business.log'));
     $arr = RequestUtil::httpGet($url);
     $newToken = $arr['access_token'];
     //LogUtil::logs("initWxTokenToDB newToken====>".$newToken, getLogFile('/business.log'));
     // 请求微信ticket
     $newTicket = self::initTicket($newToken);
     $updatetime = DateUtil::getCurrentTime();
     // 加锁文件
     if (file_exists($lockfile)) {
         //LogUtil::logs("initWxTokenToDB ====> file in writing, only can read\r\n", getLogFile('/business.log'));
         exit;
     }
     // save or update;
     $db->exec("INSERT INTO wx_token(id, token, updatetime, ticket) \r\n\t\tvalues(1, '{$newToken}','{$updatetime}','{$newTicket}') \r\n\t\tON DUPLICATE KEY UPDATE token='{$newToken}', updatetime='{$updatetime}', ticket='{$newTicket}'");
     // 关闭锁文件
     fclose($lockTemp);
     // 删除锁文件
     unlink($lockfile);
     return $newToken;
 }
예제 #2
0
 public function getContent($args)
 {
     switch ($args['pluginid']) {
         case 1:
             //$uid = $args['uid'];
             // Get matching news stories published since last newsletter
             // No selection on categories made !!
             $items = ModUtil::apiFunc('News', 'user', 'getall',
                             array('numitems' => $this->getVar('itemsperpage'),
                                 'status' => 0,
                                 'from' => DateUtil::getDatetime($args['last']),
                                 'filterbydate' => true));
             if ($items != false) {
                 if ($args['contenttype'] == 't') {
                     $counter = 0;
                     $output.="\n";
                     foreach ($items as $item) {
                         $counter++;
                         $output .= $counter . '. ' . $item['title'] . " (" . $this->__f('by %1$s on %2$s', array($item['contributor'], DateUtil::formatDatetime($item['from'], 'datebrief'))) . ")\n";
                     }
                 } else {
                     $render = Zikula_View::getInstance('News');
                     $render->assign('readperm', SecurityUtil::checkPermission('News::', "::", ACCESS_READ));
                     $render->assign('articles', $items);
                     $output = $render->fetch('mailz/listarticles.tpl');
                 }
             } else {
                 $output = $this->__f('No News publisher articles since last newsletter on %s.', DateUtil::formatDatetime($args['last'], 'datebrief')) . "\n";
             }
             return $output;
     }
     return '';
 }
예제 #3
0
 public function handleForm($context, $action)
 {
     if ($action == "createAd") {
         if (isset($_POST['start']) && $_POST['start'] != "" && (isset($_POST['size']) && $_POST['size'] != "") && (isset($_POST['name']) && $_POST['name'] != "") && (isset($_POST['url']) && $_POST['url'] != "")) {
             $start = $_POST['start'];
             $end = $_POST['end'];
             $dayOfWeek = date("D", strtotime($start));
             $splitStart = explode("/", $start);
             $mysqlStart = $splitStart[2] . "-" . $splitStart[0] . "-" . $splitStart[1];
             $splitEnd = explode("/", $end);
             $mysqlEnd = $splitEnd[2] . "-" . $splitEnd[0] . "-" . $splitEnd[1];
             if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
                 $filename = $this->saveSampleImage($context, $_FILES['image'], SessionUtil::getUsername());
                 if ($filename != "") {
                     WebAdDao::createWebAd($_POST['name'], DateUtil::findPreviousMonday($mysqlStart), $_POST['size'], $filename, $_POST['url'], $mysqlStart, $mysqlEnd);
                 } else {
                     $context->addError("Error Uploading File, Please Try Again.");
                 }
             } else {
                 $context->addError("No File Uploaded.");
             }
         } else {
             $context->addError("Required Field Left Blank.");
         }
     } else {
         $context->addError("Incorrect Action.");
     }
 }
예제 #4
0
파일: Login.php 프로젝트: guohao214/xinya
 public function index()
 {
     $error = '';
     if (RequestUtil::isPost()) {
         $validate = new ValidateUtil();
         $validate->required('user_name');
         $validate->required('password');
         $validate->required('verify_code');
         $params = RequestUtil::postParams();
         if ($params['verify_code'] != UserUtil::getVerifyCode()) {
             $error = '验证码错误!';
         } else {
             if ($validate->run()) {
                 $userModel = new UserModel();
                 $params['password'] = $userModel->encodePassword($params['password']);
                 $where = array('user_name' => $params['user_name'], 'password' => $params['password']);
                 $user = (new CurdUtil($userModel))->readOne($where, 'user_id desc', '*, user_type+0 as type');
                 if (!$user) {
                     $error = '登录失败,账号或者密码错误,请重试!';
                 } else {
                     (new CurdUtil($userModel))->update($where, array('last_login_time' => DateUtil::now()));
                     UserUtil::saveUser($user);
                     if (UserUtil::isAdmin()) {
                         ResponseUtil::redirect(UrlUtil::createBackendUrl('project/index'));
                     } else {
                         ResponseUtil::redirect(UrlUtil::createBackendUrl('beautician/index'));
                     }
                 }
             }
         }
     }
     $this->load->view('backend/login', array('error' => $error));
 }
예제 #5
0
 public static function findPreviousMonday($mysqlDate)
 {
     $time = strtotime(DateUtil::mysqlToPhpDate($mysqlDate));
     $day = date("D", $time);
     if ($day == "Mon") {
         return date(DateUtil::MYSQLDATE_FORMAT, $time);
     } else {
         if ($day == "Tue") {
             return date(DateUtil::MYSQLDATE_FORMAT, $time - DateUtil::DAY_IN_SECONDS);
         } else {
             if ($day == "Wed") {
                 return date(DateUtil::MYSQLDATE_FORMAT, $time - 2 * DateUtil::DAY_IN_SECONDS);
             } else {
                 if ($day == "Thu") {
                     return date(DateUtil::MYSQLDATE_FORMAT, $time - 3 * DateUtil::DAY_IN_SECONDS);
                 } else {
                     if ($day == "Fri") {
                         return date(DateUtil::MYSQLDATE_FORMAT, $time - 4 * DateUtil::DAY_IN_SECONDS);
                     } else {
                         if ($day == "Sat") {
                             return date(DateUtil::MYSQLDATE_FORMAT, $time - 5 * DateUtil::DAY_IN_SECONDS);
                         } else {
                             if ($day == "Sun") {
                                 return date(DateUtil::MYSQLDATE_FORMAT, $time - 6 * DateUtil::DAY_IN_SECONDS);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
예제 #6
0
 /**
  * 将用户信息同步到数据库
  */
 public function synchronizedUserInfo($userInfo, $Event)
 {
     global $db;
     $openid = $userInfo["openid"];
     $subscribe = $userInfo["subscribe"];
     $currtime = DateUtil::getCurrentTime();
     $sql = "";
     if ($Event == "subscribe") {
         LogUtil::logs("TypeEvent synchronizedUserInfo insert=====> ", getLogFile("/business.log"));
         $nickname = $userInfo["nickname"];
         $nickname = base64_encode($nickname);
         //$nickname = str_replace("🌻", "*", $nickname);
         $sex = $userInfo["sex"];
         $headimgurl = $userInfo["headimgurl"];
         $sql = $sql . ", nickname='{$nickname}', sex='{$sex}'";
         LogUtil::logs("TypeEvent.php synchronizedUserInfo  :nickname ====>" . $nickname, getLogFile('/business.log'));
         // 关注的情况有关注和重新关注,所以使用on duplicate的方法
         $sql = "INSERT INTO `wx_user_info` (openid, nickname, sex, subscribe, subscribe_time, headimgurl) \r\n\t\t\tVALUES ('{$openid}', '{$nickname}', '{$sex}', '{$subscribe}', '{$currtime}', '{$headimgurl}') \r\n\t\t\tON DUPLICATE KEY UPDATE subscribe='{$subscribe}', nickname='{$nickname}', subscribe_time='{$currtime}', headimgurl='{$headimgurl}'";
     } else {
         // 取消关注
         LogUtil::logs("TypeEvent synchronizedUserInfo update=====> ", getLogFile("/business.log"));
         $sql = "update `wx_user_info` set subscribe_time='{$currtime}', subscribe='{$subscribe}' where openid = '{$openid}' ";
     }
     $db->exec($sql);
 }
예제 #7
0
 /** Diff two date objects. Only full units are returned */
 public static function diff(TimeInterval $interval, Date $date1, Date $date2) : int
 {
     if ($date1->getOffsetInSeconds() != $date2->getOffsetInSeconds()) {
         // Convert date2 to same timezone as date1. To work around PHP bug #45038,
         // not just take the timezone of date1, but construct a new one which will
         // have a timezone ID - which is required for this kind of computation.
         $tz = new TimeZone(timezone_name_from_abbr('', $date1->getOffsetInSeconds(), $date1->toString('I')));
         // Now, convert both dates to the same time (actually we only need to convert the
         // second one, as the first will remain in the same timezone)
         $date2 = $tz->translate($date2);
     }
     // Then cut off timezone, by setting both to GMT
     $date1 = DateUtil::setTimeZone($date1, new TimeZone('GMT'));
     $date2 = DateUtil::setTimeZone($date2, new TimeZone('GMT'));
     switch ($interval) {
         case TimeInterval::$YEAR:
             return -($date1->getYear() - $date2->getYear());
         case TimeInterval::$MONTH:
             return -(($date1->getYear() - $date2->getYear()) * 12 + ($date1->getMonth() - $date2->getMonth()));
         case TimeInterval::$DAY:
             return -(intval($date1->getTime() / 86400) - intval($date2->getTime() / 86400));
         case TimeInterval::$HOURS:
             return -(intval($date1->getTime() / 3600) - intval($date2->getTime() / 3600));
         case TimeInterval::$MINUTES:
             return -(intval($date1->getTime() / 60) - intval($date2->getTime() / 60));
         case TimeInterval::$SECONDS:
             return -($date1->getTime() - $date2->getTime());
     }
 }
 public function handleForm(Context $context, $action)
 {
     if ($action == "createReservation") {
         if (isset($_POST['equip_id']) && $_POST['equip_id'] != "" && (isset($_POST['start_date']) && $_POST['start_date'] != "") && (isset($_POST['length']) && $_POST['length'] != "")) {
             $equipId = $_POST['equip_id'];
             $equip = EquipmentDao::getEquipmentByID($equipId);
             if ($equip != null) {
                 if (SessionUtil::getUserlevel() >= $equip->minUserLevel) {
                     $startDate = $_POST['start_date'];
                     $endDate = DateUtil::incrementDate($startDate, $_POST['length']);
                     $reservations = ReservationDao::getReservationsForEquipmentByDate($equipId, $startDate, $endDate);
                     if (count($reservations) == 0) {
                         $user = UserDao::getUserByUsername(SessionUtil::getUsername());
                         $reservation = ReservationDao::createReservation($user->id, $equipId, $_POST['length'], $startDate, $endDate, $_POST['user_comment']);
                         EmailUtil::sendNewReservationNotices($user, $reservation);
                     } else {
                         $context->addError("Reservations already exist during selected dates ({$startDate} and {$endDate}).");
                     }
                 } else {
                     $context->addError("Cannot reserve equipment (User Level).");
                 }
             } else {
                 $context->addError("No such equipment.");
             }
         } else {
             $context->addError("Required Field Left Blank.");
         }
     } else {
         $context->addError("Incorrect Action.");
     }
 }
예제 #9
0
 /**
  * 设置订单为已支付
  * @param $orderNo
  * @param $openId
  * @param $wxOrderNo 微信订单号
  */
 public function payed($orderNo, $wxOrderNo)
 {
     $where = array('order_no' => $orderNo);
     $updateData = array('pay_time' => DateUtil::now(), 'order_status' => self::ORDER_PAYED, 'transaction_id' => $wxOrderNo);
     $this->db->where($where);
     $this->db->update($this->table, $updateData);
     return $this->db->affected_rows();
 }
예제 #10
0
 public function insert($timestamp, array &$obj)
 {
     $obj = new TimeIt_Model_EventDate();
     $obj->eid = $obj['id'];
     $obj->date = DateUtil::getDatetime($timestamp, DATEONLYFORMAT_FIXED);
     $obj->cid = $obj['cid'];
     $obj->save();
 }
예제 #11
0
 function getPluginData($filtAfterDate = null)
 {
     if (!$this->pluginAvailable()) {
         return array();
     }
     if (!SecurityUtil::checkPermission('ZphpBB2::', '::', ACCESS_READ, $this->userNewsletter)) {
         return array();
     }
     //ModUtil::load('ZphpBB2');
     $table_prefix = ModUtil::getVar('ZphpBB2', 'table_prefix', 'phpbb_');
     $TOPICS_TABLE = $table_prefix . "topics";
     $POSTS_TABLE = $table_prefix . "posts";
     $POSTS_TEXT_TABLE = $table_prefix . "posts_text";
     $FORUMS_TABLE = $table_prefix . "forums";
     $connection = Doctrine_Manager::getInstance()->getCurrentConnection();
     $sql = "SELECT forum_id, forum_name FROM {$FORUMS_TABLE} WHERE auth_view <= 0 AND auth_read <= 0";
     $stmt = $connection->prepare($sql);
     try {
         $stmt->execute();
     } catch (Exception $e) {
         return LogUtil::registerError(__('Error in plugin') . ' ZphpBB2: ' . $e->getMessage());
     }
     $userforums = $stmt->fetchAll(Doctrine_Core::FETCH_ASSOC);
     $allowedforums = array();
     foreach (array_keys($userforums) as $k) {
         if (SecurityUtil::checkPermission('ZphpBB2::', ":" . $userforums[$k]['forum_id'] . ":", ACCESS_READ, $this->userNewsletter)) {
             $allowedforums[] = $userforums[$k]['forum_id'];
         }
     }
     if (count($allowedforums) == 0) {
         // user is not allowed to read any forum at all
         return array();
     }
     $sql = "SELECT {$TOPICS_TABLE}.topic_title, {$TOPICS_TABLE}.topic_replies, {$TOPICS_TABLE}.topic_views, {$TOPICS_TABLE}.topic_id, \n                     {$POSTS_TABLE}.post_id, {$POSTS_TABLE}.poster_id, {$POSTS_TABLE}.post_time, \n                     {$POSTS_TEXT_TABLE}.post_subject, {$POSTS_TEXT_TABLE}.post_text, \n                     {$FORUMS_TABLE}.forum_name \n                     FROM {$TOPICS_TABLE} \n                     INNER JOIN {$POSTS_TABLE} ON {$POSTS_TABLE}.topic_id = {$TOPICS_TABLE}.topic_id \n                     INNER JOIN {$POSTS_TEXT_TABLE} ON {$POSTS_TEXT_TABLE}.post_id = {$POSTS_TABLE}.post_id \n                     INNER JOIN {$FORUMS_TABLE} ON {$FORUMS_TABLE}.forum_id = {$TOPICS_TABLE}.forum_id";
     $sql .= " WHERE {$TOPICS_TABLE}.forum_id IN (" . implode(',', $allowedforums) . ")";
     if ($filtAfterDate) {
         $sql .= " AND FROM_UNIXTIME(post_time)>='" . $filtAfterDate . "'";
     }
     $sql .= " ORDER BY post_time DESC LIMIT " . $this->nItems;
     $stmt = $connection->prepare($sql);
     try {
         $stmt->execute();
     } catch (Exception $e) {
         return LogUtil::registerError(__('Error in plugin') . ' ZphpBB2: ' . $e->getMessage());
     }
     $items = $stmt->fetchAll(Doctrine_Core::FETCH_BOTH);
     foreach (array_keys($items) as $k) {
         $items[$k]['topicurl'] = ModUtil::url('ZphpBB2', 'user', 'viewtopic', array('t' => $items[$k]['topic_id']));
         $items[$k]['posturl'] = ModUtil::url('ZphpBB2', 'user', 'viewtopic', array('p' => $items[$k]['post_id'] . '#' . $items[$k]['post_id']));
         $items[$k]['postdate'] = DateUtil::getDatetime($items[$k]['post_time']);
         $items[$k]['username'] = UserUtil::getVar('uname', $items[$k]['poster_id']);
         $items[$k]['nl_title'] = $items[$k]['topic_title'];
         $items[$k]['nl_url_title'] = System::getBaseUrl() . $items[$k]['posturl'];
         $items[$k]['nl_content'] = $items[$k]['forum_name'] . ', ' . $items[$k]['username'] . "<br />\n" . $items[$k]['post_text'];
         $items[$k]['nl_url_readmore'] = $items[$k]['nl_url_title'];
     }
     return $items;
 }
 /**
  * @see TemplatePluginModifier::execute()
  */
 public function execute($tagArgs, Template $tplObj)
 {
     if (isset($tagArgs[2])) {
         $useStrftime = $tagArgs[2] ? true : false;
     } else {
         $useStrftime = isset($tagArgs[1]) ? true : false;
     }
     return DateUtil::formatDate(isset($tagArgs[1]) ? $tagArgs[1] : null, $tagArgs[0], false, $useStrftime);
 }
예제 #13
0
/**
 * Template plugin to display timezone list.
 *
 * Example {timezoneselect selected='Timezone'}.
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   The Zikula_View.
 *
 * @see   function.timezoneselect.php::smarty_function_timezoneselect().
 *
 * @return string The results of the module function.
 */
function smarty_function_timezoneselect($params, Zikula_View $view)
{
    require_once $view->_get_plugin_filepath('function', 'html_options');
    $timezones = DateUtil::getTimezones();
    if (!isset($params['selected']) || empty($params['selected']) || !isset($timezones[$params['selected']])) {
        $params['selected'] = System::getVar('timezone_offset');
    }
    return smarty_function_html_options(array('options' => $timezones, 'selected' => $params['selected'], 'print_result' => false), $view);
}
/**
 * Smarty modifier to format datetimes in a more Human Readable form 
 * (like tomorow, 4 days from now, 6 hours ago)
 *
 * Example
 * <!--[$futuredate|dateformatHuman:'%x':'2']-->
 *
 * @author   Erik Spaan
 * @since    05/03/09
 * @param    string   $string   input datetime string
 * @param    string   $format   The format of the regular date output (default %x)
 * @param    string   $niceval  [1|2|3|4] Choose the nice value of the output (default 2)
 *                                    1 = full human readable
 *                                    2 = past date > 1 day with dateformat, otherwise human readable
 *                                    3 = within 1 day human readable, otherwise dateformat
 *                                    4 = only use the specified format
 * @return   string   the modified output
 */
function smarty_modifier_dateformatHuman($string, $format = '%x', $niceval = 2)
{
    $dom = ZLanguage::getModuleDomain('News');
    if (empty($format)) {
        $format = '%x';
    }
    // store the current datetime in a variable
    $now = DateUtil::getDatetime();
    if (empty($string)) {
        return DateUtil::formatDatetime($now, $format);
    }
    if (empty($niceval)) {
        $niceval = 2;
    }
    // now format the date with respect to the current datetime
    $res = '';
    $diff = DateUtil::getDatetimeDiff($now, $string);
    if ($diff['d'] < 0) {
        if ($niceval == 1) {
            $res = _fn('%s day ago', '%s days ago', abs($diff['d']), abs($diff['d']), $dom);
        } elseif ($niceval < 4 && $diff['d'] == -1) {
            $res = __('yesterday', $dom);
        } else {
            $res = DateUtil::formatDatetime($string, $format);
        }
    } elseif ($diff['d'] > 0) {
        if ($niceval > 2) {
            $res = DateUtil::formatDatetime($string, $format);
        } elseif ($diff['d'] == 1) {
            $res = __('tomorrow', $dom);
        } else {
            $res = _fn('%s day from now', '%s days from now', $diff['d'], $diff['d'], $dom);
        }
    } else {
        // no day difference
        if ($diff['h'] < 0) {
            $res = _fn('%s hour ago', '%s hours ago', abs($diff['h']), abs($diff['h']), $dom);
        } elseif ($diff['h'] > 0) {
            $res = _fn('%s hour from now', '%s hours from now', $diff['h'], $diff['h'], $dom);
        } else {
            // no hour difference
            if ($diff['m'] < 0) {
                $res = _fn('%s minute ago', '%s minutes ago', abs($diff['m']), abs($diff['m']), $dom);
            } elseif ($diff['m'] > 0) {
                $res = _fn('%s minute from now', '%s minutes from now', $diff['m'], $diff['m'], $dom);
            } else {
                // no min difference
                if ($diff['s'] < 0) {
                    $res = _fn('%s second ago', '%s seconds ago', abs($diff['s']), abs($diff['s']), $dom);
                } else {
                    $res = _fn('%s second from now', '%s seconds from now', $diff['s'], $diff['s'], $dom);
                }
            }
        }
    }
    return $res;
}
예제 #15
0
 public static function getAdsByDay($date)
 {
     $query = "SELECT * FROM " . Database::addPrefix('webads') . " WHERE StartingMonday = '" . DateUtil::findPreviousMonday($date) . "'";
     $result = Database::doQuery($query);
     $webads = array();
     while ($row = mysql_fetch_assoc($result)) {
         $webads[] = WebAdDao::makeAd($row);
     }
     return $webads;
 }
 /**
  * @see TemplatePluginModifier::execute()
  */
 public function execute($tagArgs, Template $tplObj)
 {
     // get timestamps
     if (!isset($tagArgs[1])) {
         $tagArgs[1] = TIME_NOW;
     }
     $start = min($tagArgs[0], $tagArgs[1]);
     $end = max($tagArgs[0], $tagArgs[1]);
     return DateUtil::diff($start, $end, 'string');
 }
예제 #17
0
 function setFromPost($prefix = '')
 {
     $this->loadFields($_POST, $prefix);
     $this->descrip = htmlspecialchars($this->descrip, ENT_QUOTES);
     $this->notes = htmlspecialchars($this->notes, ENT_QUOTES);
     //Required in addition to the processing in loadFields
     $this->location->setFromPost($prefix);
     $this->date1 = DateUtil::resolveDate($this->date1);
     $this->date2 = DateUtil::resolveDate($this->date2);
 }
예제 #18
0
파일: LogUtil.php 프로젝트: guohao214/xinya
 public static function log($mainTitle, $message, $file = 'log')
 {
     $saveFile = APPPATH . DIRECTORY_SEPARATOR . 'logs';
     $saveFile = $saveFile . DIRECTORY_SEPARATOR . $file . date('Y-m-d');
     if (!is_string($message)) {
         $message = json_encode($message);
     }
     $mainTitle = DateUtil::now() . ' ' . $mainTitle;
     file_put_contents($saveFile, $mainTitle . $message . "\n\n" . str_repeat('-', 80) . "\n", FILE_APPEND);
 }
예제 #19
0
/**
 * Zikula_View function to display the current date and time
 *
 * Example
 * {datetime}
 *
 * {datetime format='datebrief'}
 *
 * {datetime format='%b %d, %Y - %I:%M %p'}
 *
 * Format:
 * %a - abbreviated weekday name according to the current locale
 * %A = full weekday name according to the current locale
 * %b = abbreviated month name according to the current locale
 * %B = full month name according to the current locale
 * %d = day of the month as a decimal number (range 01 to 31)
 * %D = same as %m/%d/%y
 * %y = year as a decimal number without a century (range 00 to 99)
 * %Y = year as a decimal number including the century
 * %H = hour as a decimal number using a 24-hour clock (range 00 to 23)
 * %I = hour as a decimal number using a 12-hour clock (range 01 to 12)
 * %M = minute as a decimal number
 * %S = second as a decimal number
 * %p = either 'am' or 'pm' according to the given time value, or the corresponding strings for the current locale
 *
 * http://www.php.net/manual/en/function.strftime.php
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @see    function.datetime.php::smarty_function_datetime()
 * 
 * @return string
 */
function smarty_function_datetime($params, Zikula_View $view)
{
    // set some defaults
    $format = isset($params['format']) ? $params['format'] : __('%b %d, %Y - %I:%M %p');
    if (strpos($format, '%') !== false) {
        // allow the use of conversion specifiers
        return DateUtil::formatDatetime('', $format);
    }
    return DateUtil::formatDatetime('', $format);
}
예제 #20
0
 public function calcularDeveriaTerRecebido($parcelas)
 {
     $retorno = 0;
     foreach ($parcelas as $parcela) {
         $dataPrevista = $parcela->getDataPrevista();
         if (DateUtil::isDataAnteriorHoje($dataPrevista)) {
             $retorno += $parcela->getValorLiquido();
         }
     }
     return $retorno;
 }
예제 #21
0
 public function getCreditMonthEnd($month, $day)
 {
     if ((int) $day == 1) {
         return date('Y-m-t 23:59:59', strtotime("{$month}"));
     }
     if ((int) $day == 0) {
         $day = date('d', time());
     }
     $ymd = DateUtil::addMonth("{$month}-{$day}", 1, 'y-m-d');
     return date('Y-m-d 23:59:59', strtotime('-1 day', strtotime($ymd)));
 }
예제 #22
0
/**
 * Zikula_View modifier to format datestamps via strftime according to locale setting in Zikula.
 *
 * @param string $string       Input date string.
 * @param string $format       Strftime format for output.
 * @param string $default_date Default date if $string is empty.
 *
 * @uses smarty_make_timestamp()
 * 
 * @return string The modified output.
 */
function smarty_modifier_dateformat($string, $format = 'datebrief', $default_date = null)
{
    if (empty($format)) {
        $format = 'datebrief';
    }
    if (!empty($string)) {
        return DateUtil::formatDatetime($string, $format);
    } elseif (!empty($default_date)) {
        return DateUtil::formatDatetime($default_date, $format);
    }
    return '';
}
예제 #23
0
 /**
  * Convert the date to a more useful format.
  *
  * @param string $date Date string.
  *
  * @return string Converted date
  */
 protected function dateConvert($date)
 {
     if (strptime($date, "%d.%m.%Y %H:%M:%S") !== false) {
         $arr = strptime($date, "%d.%m.%Y %H:%M:%S");
         $time = \DateUtil::buildDatetime($arr['tm_year'], $arr['tm_mon'], $arr['tm_monday'], $arr['tm_hour'], $arr['tm_min'], $arr['tm_sec']);
     } elseif (is_numeric($date)) {
         $time = \DateUtil::getDatetime($date);
     } else {
         $time = str_replace('_', ' ', $date);
     }
     return $time;
 }
예제 #24
0
파일: Tool.php 프로젝트: guohao214/xinya
 /**
  * 数据库备份
  */
 public function backup()
 {
     $this->load->dbutil();
     $backup = $this->dbutil->backup();
     $this->load->helper('file');
     $filePath = MAIN_ROOT . 'backup' . DS . date('YmdHis') . '.gz';
     if (write_file($filePath, $backup)) {
         (new CurdUtil($this->backupModel))->create(array('file_path' => $filePath, 'create_time' => DateUtil::now()));
         $this->message('备份成功', 'tool/index');
     } else {
         $this->message('备份失败,请重试!');
     }
 }
예제 #25
0
 public static function getFormattedDateTime($objEvent, $blnSeparatedDateTime = true)
 {
     if ($objEvent->addTime) {
         if ($blnSeparatedDateTime) {
             $strDateTime = DateUtil::getSeparatedNumericDateTimeInterval($objEvent->startDate, $objEvent->endDate, $objEvent->startTime, $objEvent->endTime);
         } else {
             $strDateTime = DateUtil::getNumericDateInterval($objEvent->startTime, $objEvent->endTime);
         }
     } else {
         $strDateTime = DateUtil::getNumericDateInterval($objEvent->startDate, $objEvent->endDate);
     }
     return $strDateTime;
 }
예제 #26
0
 /**
  * display block
  *
  * @param array       $blockinfo     a blockinfo structure
  * @return output      the rendered bock
  */
 public function display($blockinfo)
 {
     // Security check
     if (!SecurityUtil::checkPermission('EZComments:EZCommentsblock:', "{$blockinfo['bid']}::", ACCESS_READ)) {
         return false;
     }
     if (!ModUtil::load('EZComments')) {
         return false;
     }
     // Get variables from content block
     $vars = BlockUtil::varsFromContent($blockinfo['content']);
     // Defaults
     if (!isset($vars['numentries'])) {
         $vars['numentries'] = 5;
     }
     if (!isset($vars['numdays'])) {
         $vars['numdays'] = 0;
     }
     if (!isset($vars['showdate'])) {
         $vars['showdate'] = 0;
     }
     if (!isset($vars['showusername'])) {
         $vars['showusername'] = 0;
     }
     if (!isset($vars['linkusername'])) {
         $vars['linkusername'] = 0;
     }
     $options = array('numitems' => $vars['numentries']);
     if (isset($vars['mod']) && $vars['mod'] != '*') {
         $options['mod'] = $vars['mod'];
     }
     if (!isset($vars['showpending']) || $vars['showpending'] == 0) {
         // don't show pending comments
         $options['status'] = 0;
     }
     // filter comments posted in last number of days
     if ($vars['numdays'] > 0) {
         // date for filtering in format: yyyy-mm-dd hh:mm:ss
         $options['addwhere'] = "date>='" . DateUtil::getDatetime_NextDay(-$vars['numdays']) . "'";
     }
     // get the comments
     $items = ModUtil::apiFunc('EZComments', 'user', 'getall', $options);
     // augment the info
     $comments = ModUtil::apiFunc('EZComments', 'user', 'prepareCommentsForDisplay', $items);
     $this->view->assign($vars);
     $this->view->assign('comments', $comments);
     // Populate block info and pass to theme
     $blockinfo['content'] = $this->view->fetch('ezcomments_block_ezcomments.tpl');
     return BlockUtil::themesideblock($blockinfo);
 }
예제 #27
0
function mediashare_invitationapi_createInvitationId($args)
{
    $dom = ZLanguage::getModuleDomain('mediashare');
    do {
        $key = mediashareCreateInvitationKey();
        $record = array('albumId' => (int) $args['albumId'], 'created' => DateUtil::getDatetime(), 'key' => $key, 'email' => $args['email'], 'subject' => $args['subject'], 'text' => $args['text'], 'sender' => $args['sender'], 'expires' => !empty($args['expires']) ? $args['expires'] : null);
        $result = DBUtil::insertObject($record, 'mediashare_invitation', 'id');
        if ($result == false) {
            return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('invitationapi.createInvitationId', 'Could not create the invitation.'), $dom));
        }
    } while (false);
    // FIXME: add "key exists" check
    return $key;
}
 /**
  * Constructs an instance of this class.
  */
 public function __construct()
 {
     // get current server system time for use with date() in order to ensure valid
     // and consistent date and time values all over one instance of this class
     // in case the timebase is "now" which will be the case if no multipleExec action
     // is requested by configuration.
     $this->now = TIME_NOW;
     // set the timezone which is either the one set by the WBB admin, or if it isn't set, it's GMT.
     DateUtil::formatDate();
     // set cache name.
     $this->cacheName = 'cronjobs-' . PACKAGE_ID;
     // read cache.
     $this->getCronjobsCache();
 }
예제 #29
0
 public function generateMondaySelectForm()
 {
     $select = "<form action=\"./index.php?pageid=viewAds\" method=\"POST\">\n\t\t\t<input type=\"hidden\" name=\"action\" value=\"setPageVar\">\n\t\t\t<select name=\"monday\" class=\"bluefocus\">";
     $mondays = WebAdDao::getDistinctMondays();
     foreach ($mondays as $monday) {
         if (DateUtil::findPreviousMonday($this->startingMonday) == $monday) {
             $select = $select . "<option value=\"" . $monday . "\" selected=\"selected\">" . $monday . "</option>";
         } else {
             $select = $select . "<option value=\"" . $monday . "\">" . $monday . "</option>";
         }
     }
     $select = $select . "</select> <input type=\"submit\" value=\"Go\" class=\"stdbutton bluefocus\" \\></form>";
     return $select;
 }
예제 #30
0
 public function insertPreProcess($data = null)
 {
     $data =& $this->_objData;
     // sort column
     $data['sortname'] = $data['fname'] . ' ' . $data['lname'];
     $data['sortcompany'] = $data['company'];
     // same
     $data['date'] = time();
     // convert custom date type and numeric values
     // get the custom fields
     $cus_where = "";
     $cus_sort = "cus_pos ASC";
     $cus_Array = new AddressBook_DBObject_CustomfieldArray();
     $customfields = $cus_Array->get($cus_where, $cus_sort);
     foreach ($customfields as $cus) {
         $cusfield = "custom_" . $cus['id'];
         if (!empty($data[$cusfield])) {
             if ($cus['type'] == 'date default NULL') {
                 $data[$cusfield] = DateUtil::parseUIDate($data[$cusfield]);
                 $data[$cusfield] = DateUtil::transformInternalDate($data[$cusfield]);
             }
             if ($cus['type'] == 'decimal(10,2) default NULL') {
                 $check_format = ereg_replace(",", ".", $data[$cusfield]);
                 $split_format = explode(".", $check_format);
                 $count_array = count($split_format);
                 // example 1000
                 if ($count_array == 1) {
                     if (ereg("^[+|-]{0,1}[0-9]{1,}\$", $check_format)) {
                         $num = "{$split_format['0']}";
                     }
                 }
                 // example 1000,20 or 1.000
                 if ($count_array == 2) {
                     if (ereg("^[+|-]{0,1}[0-9]{1,}.[0-9]{0,2}\$", $check_format)) {
                         $num = "{$split_format['0']}.{$split_format['1']}";
                     }
                 }
                 // example 1,000.20 or 1.000,20
                 if ($count_array == 3) {
                     if (ereg("^[+|-]{0,1}[0-9]{1,}.[0-9]{3}.[0-9]{0,2}\$", $check_format)) {
                         $num = "{$split_format['0']}{$split_format['1']}.{$split_format['2']}";
                     }
                 }
                 $data[$cusfield] = $num;
             }
         }
     }
     return $data;
 }