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 ''; }
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(); }
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; }
/** * 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; }
/** * 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; }
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; }
/** * DateFormat. * * Params can be: * format The date format we wish to convert to (optional) (default='Y-m-d'). * datetime The datetime we wish to convert. * assign The smarty variable we wish to assign the result to (optional). * * @param array $params All attributes passed to this function from the template. * @param Zikula_View $view Reference to the Zikula_View object. * * @return string */ function smarty_function_dateformat($params, Zikula_View $view) { if (!isset($params['datetime'])) { $params['datetime'] = null; } if (!isset($params['format']) || empty($params['format'])) { $params['format'] = null; } $res = DateUtil::getDatetime($params['datetime'], $params['format']); if (isset($params['assign']) && $params['assign']) { $view->assign($params['assign'], $res); } else { return $res; } }
/** * Search plugin main function **/ public function search($args) { if (!SecurityUtil::checkPermission('News::', '::', ACCESS_READ)) { return true; } ModUtil::dbInfoLoad('Search'); $tables = DBUtil::getTables(); $newsColumn = $tables['news_column']; $where = Search_Api_User::construct_where($args, array($newsColumn['title'], $newsColumn['hometext'], $newsColumn['bodytext']), $newsColumn['language']); // Only search in published articles that are currently visible $where .= " AND ({$newsColumn['published_status']} = '0')"; $date = DateUtil::getDatetime(); $where .= " AND ('$date' >= {$newsColumn['from']} AND ({$newsColumn['to']} IS NULL OR '$date' <= {$newsColumn['to']}))"; $sessionId = session_id(); ModUtil::loadApi('News', 'user'); $permChecker = new News_ResultChecker($this->getVar('enablecategorization'), $this->getVar('enablecategorybasedpermissions')); $articles = DBUtil::selectObjectArrayFilter('news', $where, null, null, null, '', $permChecker, null); foreach ($articles as $article) { $item = array( 'title' => $article['title'], 'text' => $article['hometext'], 'extra' => $article['sid'], 'created' => $article['from'], 'module' => 'News', 'session' => $sessionId ); $insertResult = DBUtil::insertObject($item, 'search_result'); if (!$insertResult) { return LogUtil::registerError($this->__('Error! Could not load any articles.')); } } return true; }
public function reset($args) { // Security check if (!SecurityUtil::checkPermission('IWstats::', '::', ACCESS_DELETE)) { throw new Zikula_Exception_Forbidden(); } // delete records from database $delete = DateUtil::getDatetime(time() - $args['deleteFromDays'] * 24 * 60 * 60); // get the last record in summary table $table = DBUtil::getTables(); $c = $table['IWstats_column']; $where = "$c[datetime] < '$delete'"; DBUtil::deleteWhere('IWstats', $where); // Return the id of the newly created item to the calling process return true; }
public function createUser($user){ if ($user) { $user['zk']['approved_date'] = DateUtil::getDatetime(); $user['zk']['user_regdate'] = DateUtil::getDatetime(); $user['zk']['approved_by'] = 2; DBUtil::insertObject($user['zk'], 'users', 'uid'); $insertUserId = $user['zk']['uid']; $user['iw']['uid'] = $insertUserId; $user['iw']['suid'] = $insertUserId; DBUtil::insertObject($user['iw'], 'IWusers', 'suid'); //Assignem els grups indicats en el formulari foreach ($user['gr'] as $grup) { $item = array('gid' => $grup, 'uid' => $user['zk']['uid']); DBUtil::insertObject($item, 'group_membership'); } return $insertUserId; }else { return false; } }
/** * Get all admin messages items that match the criteria * * @author Mark West, Jorn Wildt * @param bool args['activeonly'] only show active items * @return bool true/false on success/failure */ function Admin_Messages_searchapi_search($args) { $dom = ZLanguage::getModuleDomain('Admin_Messages'); // Security check if (!SecurityUtil::checkPermission('Admin_Messages::', '::', ACCESS_READ)) { return true; } // get the db and table info ModUtil::dbInfoLoad('Search'); $pntable = DBUtil::getTables(); $messagestable = $pntable['message']; $messagescolumn = $pntable['message_column']; $searchTable =& $pntable['search_result']; $searchColumn =& $pntable['search_result_column']; // form the where clause $where = ''; if (!ModUtil::getVar('Admin_Messages', 'allowsearchinactive') || isset($args['activeonly']) && (bool) $args['activeonly']) { $where .= " {$messagescolumn['active']} = 1 AND "; } $where .= " ({$messagescolumn['date']}+{$messagescolumn['expire']} > '" . time() . "' OR {$messagescolumn['expire']} = 0) AND"; $where .= search_construct_where($args, array($messagescolumn['title'], $messagescolumn['content']), $messagescolumn['language']); $sessionId = session_id(); $sql = "\nSELECT\n {$messagescolumn['mid']} as mid,\n {$messagescolumn['title']} as title,\n {$messagescolumn['content']} as text,\n {$messagescolumn['date']} as date\nFROM {$messagestable}\nWHERE {$where}"; $result = DBUtil::executeSQL($sql); if (!$result) { return LogUtil::registerError(__('Error! Could not load data.')); } $insertSql = "INSERT INTO {$searchTable}\n ({$searchColumn['title']},\n {$searchColumn['text']},\n {$searchColumn['module']},\n {$searchColumn['created']},\n {$searchColumn['session']})\nVALUES "; // Process the result set and insert into search result table for (; !$result->EOF; $result->MoveNext()) { $message = $result->GetRowAssoc(2); if (SecurityUtil::checkPermission('Admin_Messages::', "{$message['title']}::{$message['mid']}", ACCESS_READ)) { $sql = $insertSql . '(' . '\'' . DataUtil::formatForStore($message['title']) . '\', ' . '\'' . DataUtil::formatForStore($message['text']) . '\', ' . '\'' . 'Admin_Messages' . '\', ' . '\'' . DataUtil::formatForStore(DateUtil::getDatetime($message['date'])) . '\', ' . '\'' . DataUtil::formatForStore($sessionId) . '\')'; $insertResult = DBUtil::executeSQL($sql); if (!$insertResult) { return LogUtil::registerError(__('Error! Could not load data.', $dom)); } } } return true; }
/** * Converts the $obj[allDayStart] to the current timezone. * * @param array &$obj Event. * * @return void */ public static function convertAlldayStartToLocalTime(&$obj) { if ($obj['allDay'] == 0) { if (strpos($obj['allDayStart'], ' ') !== false) { // calc local start time $time = substr($obj['allDayStart'], 0, strpos($obj['allDayStart'], ' ')); $timezone = (int) substr($obj['allDayStart'], strpos($obj['allDayStart'], ' ') + 1); $timezoneCurr = (int) (UserUtil::getVar('tzoffset') !== false ? UserUtil::getVar('tzoffset') : System::getVar('timezone_offset')); $zoneOffset = $timezone * -1 + $timezoneCurr; list($hour, $min) = explode(':', $time); list($zone_hour, $zone_minDez) = explode('.', $zoneOffset); $hour += $zone_hour; $min += $zone_minDez * 60; // convert e.g. 0.75 to 45 // more than 60 minutes than add an hour and reduce the minutes if ($min >= 60) { $hour++; $min = $min - 60; } if ($hour < 0) { $obj['allDayStartLocalDateCorrection'] = -1; $hour = 24 + $hour; // fix minus value } else { if ($hour > 24) { $obj['allDayStartLocalDateCorrection'] = +1; $hour = $hour - 24; // fix to big value } } $obj['allDayStartLocal'] = ($hour < 10 ? '0' : '') . $hour . ':' . ($min < 10 ? '0' : '') . $min; } else { $obj['allDayStartLocal'] = $obj['allDayStart']; } // format it $obj['allDayStartLocalFormated'] = DateUtil::getDatetime(strtotime($obj['startDate'] . ' ' . $obj['allDayStartLocal'] . ':00'), 'timebrief'); // Add timezone to the time //$obj['allDayStartLocalFormated'] = $obj['allDayStartLocalFormated'].' '.DateUtil::strftime('%Z'); } }
/** * Set the standard PN architecture fields to sane values for an object update. * * @param array &$obj The object we need to set the standard fields on. * @param boolean $preserveValues Whether or not to preserve value fields which have a valid value set (optional) (default=false). * * @return void */ public static function setStandardFieldsOnObjectUpdate(&$obj, $preserveValues = false) { if (!is_array($obj)) { throw new \Exception(__f('%s called on a non-object', 'ObjectUtil::setStandardFieldsOnObjectUpdate')); return; } $obj['lu_date'] = isset($obj['lu_date']) && $obj['lu_date'] && $preserveValues ? $obj['lu_date'] : DateUtil::getDatetime(); $obj['lu_uid'] = isset($obj['lu_uid']) && $obj['lu_uid'] && $preserveValues ? $obj['lu_uid'] : UserUtil::getVar('uid'); if (is_null($obj['lu_uid'])) { $obj['lu_uid'] = 0; } return; }
public function getForumsNews($args) { $result = array(); $dateTimeFrom = $args['dateTimeFrom']; $dateTimeTo = $args['dateTimeTo']; //Checking IWforums module $modinfo = ModUtil::getInfo(ModUtil::getIdFromName('IWforums')); if ($modinfo['state'] != 3) return $result; if ($modinfo['version'] >= '3.1.0') { $result = ModUtil::apiFunc('IWforums', 'user', 'getAllUnreadedMessages', array('dateTimeFrom' => $dateTimeFrom, 'dateTimeTo' => $dateTimeTo)); } else { $messages = array(); if (!is_null($dateTimeFrom)) { $pntable = DBUtil::getTables(); $f = $pntable['IWforums_definition_column']; $t = $pntable['IWforums_temes_column']; $m = $pntable['IWforums_msg_column']; // Get all the messages posted after $dateTimeFrom in subscribibles forums $sql = "SELECT F.$f[fid] AS fid, M.$m[ftid] AS ftid, M.$m[fmid] AS fmid, M.$m[titol] AS msgTitle, M.$m[usuari] AS user, M.$m[data] AS date, M.$m[llegit] AS readers, T.$t[titol] AS topic, T.$t[order], "; $sql .= "F.$f[nom_forum] AS forum, F.subscriptionMode, F.subscribers, F.noSubscribers, F.$f[grup] AS grup, F.$f[mod] AS moderators "; $sql .= "FROM `IWforums_msg` AS M, `IWforums_temes` AS T, `IWforums_definition` AS F "; $sql .= "WHERE M.$m[ftid] = T.$t[ftid] AND T.$t[fid] = F.$f[fid] AND F.$f[actiu] = 1 AND M.$m[data] >= ".$dateTimeFrom." AND M.$m[data] < ".$dateTimeTo." AND F.subscriptionMode > 0 "; $sql .= "ORDER BY F.$f[fid], T.$t[order], M.$m[data]"; $query = DBUtil::executeSQL($sql); $messages = DBUtil::marshallObjects($query); foreach ($messages as $key => $message) { // Extract forum moderators $moderators = explode('$$', substr($message['moderators'], 0, strlen($message['moderators']) -1)); unset($moderators[0]); //Extract message readers $readers = explode('$$', substr($message['readers'], 0, strlen($message['readers']) -1)); unset($readers[0]); // Extract grups $auxGroups = explode('$$', substr($message['grup'], 0, strlen($message['grup']) -1)); unset($auxGroups[0]); $groups = array(); foreach ($auxGroups as $ag){ $g = explode ('|', $ag); $groups[] = $g[0]; } // Construct a unique list with the users that have read access to a forum $members = array(); foreach ($groups as $group){ // Get group members $users = UserUtil::getUsersForGroup($group); foreach ($users as $user){ // Avoid duplicated users if (!in_array($user, $members)) $members[$user] = $user; } } // Add moderators foreach ($moderators as $moderator){ if (!in_array($moderator, $members)) $members[$moderator] = $moderator; } // Remove readers foreach ($readers as $reader) { if (in_array($reader, $members)) unset($members[$reader]); } $messages[$key]['receivers'] = $members; } // At this point, every message has a list of receivers // Let's construct an array with the associated information to send $information = array(); foreach ($messages as $message){ if (isset($message['receivers'])) { foreach($message['receivers'] as $receiver){ $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue'); $information[$receiver][$message['fid']]['nom_forum'] = $message['forum']; $information[$receiver][$message['fid']]['subscriptionMode'] = $message['subscriptionMode']; $information[$receiver][$message['fid']]['fid'] = $message['fid']; $information[$receiver][$message['fid']]['topics'][$message['ftid']]['titol'] = $message['topic']; $information[$receiver][$message['fid']]['topics'][$message['ftid']]['messages'][$message['fmid']]['title'] = $message['msgTitle']; $information[$receiver][$message['fid']]['topics'][$message['ftid']]['messages'][$message['fmid']]['author'] = ModUtil::func('IWmain', 'user', 'getUserInfo', array('sv' => $sv, 'info' => 'ncc', 'uid' => $message['user'])); $information[$receiver][$message['fid']]['topics'][$message['ftid']]['messages'][$message['fmid']]['date'] = strtolower(DateUtil::getDatetime($message['date'], 'datetimelong', true)); } } } foreach ($information as $key => $userReport){ $view = Zikula_View::getInstance($this->name, false); $view->assign('info', $userReport); $result[$key]['IWforums'] = $view->fetch('reports/IWforums_user_report.tpl'); } } } return $result; }
/** * */ public static function actualPostings($userid) { if (UserUtil::isLoggedIn() == true) { // we get a repository for users $userrepository = MUBoard_Util_Model::getUserRepository(); $where = 'tbl.userid = \'' . DataUtil::formatForStore($userid) . '\''; $user = $userrepository->selectWhere($where); // we get the datetime of the last visit of muboard $lastVisit = $user[0]['lastVisit']; // we get the timestamp $lastVisit = $lastVisit->getTimestamp(); // we format for $lastVisit = date('Y-m-d H:i:s', $lastVisit); $date = DateUtil::getDatetime(); // we get a repository for postings $postingrepository = MUBoard_Util_Model::getPostingRepository(); $where = 'tbl.createdDate > \'' . $lastVisit . '\''; $postings = $postingrepository->selectWhere($where); $forumids = array(); $postingids = array(); foreach ($postings as $posting) { // get forum id $forum = $posting->getForum(); $forumid = $forum->getId(); if (!in_array($forumid, $forumids)) { $forumids[] = $forumid; } // get posting id $parent = $posting->getParent(); if (!is_null($parent)) { $parentid = $parent->getId(); if ($parentid != NULL) { if (!in_array($parentid, $postingids)) { $postingids[] = $parentid; } } } else { $id = $posting->getId(); if (!in_array($id, $postingids)) { $postingids[] = $id; } } } //SessionUtil::setVar('muboardforumids', $forumids); SessionUtil::setVar('muboardpostingids', $postingids); } }
public function calculate($start, $end, array &$obj, TimeIt_Recurrence_Output $out) { $time = $start; $diff = DateUtil::getDatetimeDiff($obj['startDate'], $time); // weekly? if ($obj['repeatSpec'] == "week") { $weeks = (int) date('W', strtotime($start)) - (int) date('W', strtotime($obj['startDate'])); $weeks = (int) floor($weeks / $obj['repeatFrec']); if ($weeks < 0) { $weeks = 0; } $date = DateUtil::getDatetime(strtotime('+' . $weeks * $obj['repeatFrec'] . ' week', strtotime($obj['startDate'])), DATEONLYFORMAT_FIXED); while ($date <= $end && $date <= $obj['endDate']) { // in requested range? if ($date >= $start && $date <= $end && $date >= $obj['startDate']) { $temp = getDate(strtotime($date)); $temp = mktime(0, 0, 0, $temp['mon'], $temp['mday'], $temp['year']); $out->insert($temp, $obj); } // next occurence $weeks++; $date = DateUtil::getDatetime(strtotime('+' . $weeks * $obj['repeatFrec'] . ' week', strtotime($obj['startDate'])), DATEONLYFORMAT_FIXED); } // monthly? } else { if ($obj['repeatSpec'] == "month") { // calc start $years = (int) date('Y', strtotime($end)) - (int) date('Y', strtotime($obj['startDate'])); $months = $years * 12; $monthsTemp = (int) date('n', strtotime($start)) - (int) date('n', strtotime($obj['startDate'])); $months = $months + $monthsTemp; $months = (int) floor($months / $obj['repeatFrec']); $date = DateUtil::getDatetime(strtotime('+' . $months * $obj['repeatFrec'] . ' month', strtotime($obj['startDate'])), DATEONLYFORMAT_FIXED); //print_r($monthsTemp);exit(); while ($date <= $end && $date <= $obj['endDate']) { // in requested range? if ($date >= $start && $date <= $end && $date >= $obj['startDate']) { $temp = getDate(strtotime($date)); $temp = mktime(0, 0, 0, $temp['mon'], $temp['mday'], $temp['year']); $out->insert($temp, $obj); } // next occurence $months++; $date = DateUtil::getDatetime(strtotime('+' . $months * $obj['repeatFrec'] . ' month', strtotime($obj['startDate'])), DATEONLYFORMAT_FIXED); } // yearly } else { if ($obj['repeatSpec'] == "year") { $years_start = (int) date('Y', strtotime($obj['startDate'])); $years_ende = (int) date('Y', strtotime($obj['endDate'])); for ($year = $years_start; $year <= $years_ende; $year += $obj['repeatFrec']) { // calc timestamp $temp = getDate(strtotime($obj['startDate'])); $temp = mktime(0, 0, 0, $temp['mon'], $temp['mday'], $year); $date = DateUtil::getDatetime($temp, DATEONLYFORMAT_FIXED); // in requested range? if ($date >= $start && $date <= $end && $date >= $obj['startDate']) { $out->insert($temp, $obj); } } // daily } else { $repeats = (int) floor($diff['d'] / $obj['repeatFrec']); $repeats--; if ($repeats < 0) { $daysToLastUnusedRepeat = (int) -$obj['repeatFrec']; /* } else if($repeats == 0) { $daysToLastUnusedRepeat = 0 - $obj['repeatFrec'];*/ } else { $daysToLastUnusedRepeat = $repeats * $obj['repeatFrec']; } $timestamp = strtotime($obj['startDate']); $timestampEnd = strtotime($end); $counter = $obj['repeatFrec']; while (true) { $temp = mktime(0, 0, 0, date('n', $timestamp), date('j', $timestamp) + $daysToLastUnusedRepeat + $counter, date('Y', $timestamp)); $counter += $obj['repeatFrec']; // end reached? if ($temp > strtotime($obj['endDate']) || $temp > $timestampEnd) { break; } $out->insert($temp, $obj); } } } } }
public function addPageVersion($args) { if (!$this->getVar('enableVersioning')) { return true; } $pageId = $args['pageId']; $action = $args['action']; $page = ModUtil::apiFunc('Content', 'Page', 'getPage', array('id' => $pageId, 'editing' => true, 'filter' => array('checkActive' => false), 'enableEscape' => false, 'translate' => false, 'includeContent' => true)); if ($page === false) { return false; } // Clear some of the redundant plugin data foreach (array_keys($page['content']) as $i) { foreach (array_keys($page['content'][$i]) as $j) { $c =& $page['content'][$i][$j]; $c['plugin']->destroyView(); unset($c['plugin']); unset($c['output']); unset($c['translated']); } } $page['layoutData']['plugin']->destroyView(); $pageTranslations = ModUtil::apiFunc('Content', 'Page', 'getTranslations', array('pageId' => $pageId)); if ($pageTranslations === false) { return false; } $contentTranslations = ModUtil::apiFunc('Content', 'Content', 'getTranslations', array('pageId' => $pageId)); if ($contentTranslations === false) { return false; } $version = array('page' => $page, 'pageTranslations' => $pageTranslations, 'contentTranslations' => $contentTranslations); $versionData = serialize($version); $userId = UserUtil::getVar('uid'); $nextRevisionNo = $this->contentGetNextRevisionNumber($pageId); $historyData = array('data' => $versionData, 'pageId' => $pageId, 'revisionNo' => $nextRevisionNo, 'action' => $action, 'date' => DateUtil::getDatetime(), 'ipno' => $_SERVER['REMOTE_ADDR'], 'userId' => $userId); DBUtil::insertObject($historyData, 'content_history'); return true; }
/** * Create a new block. * * @param string $block ['title'] the title of the block. * @param string $block ['description'] the description of the block. * @param int $block ['mid'] the module ID of the block. * @param string $block ['language'] the language of the block. * @param int $block ['bkey'] the key of the block. * * @return mixed block Id on success, false on failure. */ public function create($args) { // Argument check if (!isset($args['title']) || !isset($args['description']) || !isset($args['mid']) || !isset($args['language']) || !isset($args['collapsable']) || !isset($args['defaultstate']) || !isset($args['bkey'])) { return LogUtil::registerArgsError(); } // Security check if (!System::isInstalling() && !SecurityUtil::checkPermission('Blocks::', "{$args['bkey']}:{$args['title']}:", ACCESS_ADD)) { return LogUtil::registerPermissionError(); } // optional arguments if (!isset($args['content']) || !is_string($args['content'])) { $args['content'] = ''; } $block = array('title' => $args['title'], 'description' => $args['description'], 'language' => $args['language'], 'collapsable' => $args['collapsable'], 'mid' => $args['mid'], 'defaultstate' => $args['defaultstate'], 'bkey' => $args['bkey'], 'content' => $args['content']); $block['url'] = ''; $block['filter'] = ''; $block['active'] = 1; $block['refresh'] = 3600; $block['last_update'] = DateUtil::getDatetime(); $block['active'] = 1; $res = DBUtil::insertObject($block, 'blocks', 'bid'); if (!$res) { return LogUtil::registerError($this->__('Error! Could not create the new item.')); } // empty block positions for this block if (isset($args['positions'])) { // add new block positions $blockplacments = array(); foreach ($args['positions'] as $position) { $blockplacments[] = array('bid' => $block['bid'], 'pid' => $position); } $res = DBUtil::insertObjectArray($blockplacments, 'block_placements'); if (!$res) { return LogUtil::registerError($this->__('Error! Could not create the new item.')); } } return $block['bid']; }
/** * Create a new comment * * This function creates a new comment and returns its ID. * Access checking is done. * * @param $args['mod'] Name of the module to create comments for * @param $args['objectid'] ID of the item to create comments for * @param $args['areaid'] hook areaID of the item to create comments for * @param $args['comment'] The comment itself * @param $args['subject'] The subject of the comment * @param $args['replyto'] The reference ID * @param $args['uid'] The user ID (optional) * @param $args['owneruid'] The user ID whoose content was commented(optional) * @param $args['useurl'] The url that should be used for storing in db and email to admin * @param $args['type'] The type of comment (optional) currently trackback, pingback are only allowed values * @return integer ID of new comment on success, false on failure */ public function create($args = array()) { if (!isset($args['mod']) || !isset($args['objectid']) || !isset($args['comment']) || !isset($args['owneruid'])) { return LogUtil::registerArgsError(); } if (!isset($args['type']) || !is_string($args['type']) || !in_array($args['type'], array('trackback', 'pingback'))) { $args['type'] = ''; } // Security check if (!SecurityUtil::checkPermission("EZComments::$args[type]", "$args[mod]:$args[objectid]:", ACCESS_COMMENT)) { return LogUtil::registerPermissionError(); } $owneruid = (int)$args['owneruid']; // Sometimes the displayurl for the redirect is another url then the url, // that should be sent via email. if (isset($args['useurl']) && !empty($args['useurl'])) { $url = $args['useurl'] = str_replace('&', '&', $args['useurl']); } else { $baseURL = System::getBaseUrl(); $url = isset($args['redirect']) ? $baseURL . str_replace($baseURL, '', $args['redirect']) : System::serverGetVar('HTTP_REFERER'); } $loggedin = UserUtil::isLoggedIn(); // ContactList ignore check. If the user is ignored by the // content owner the user will not be able to post any comment... if ($loggedin && $owneruid > 0 && ModUtil::available('ContactList') && ModUtil::apiFunc('ContactList', 'user', 'isIgnored', array('iuid' => UserUtil::getVar('uid'), 'uid' => $owneruid))) { return LogUtil::registerError($this->__('Error! The user ignores you.')); } // check unregistered user included name (if required) $args['anonname'] = isset($args['anonname']) ? trim($args['anonname']) : ''; if (!$loggedin) { $args['uid'] = 0; if ($this->getVar('anonusersrequirename') && empty($args['anonname'])) { return LogUtil::registerError($this->__('Error! The name field is required. Comment rejected.')); } } if (!isset($args['replyto']) || empty($args['replyto'])) { $args['replyto'] = -1; } if (!isset($args['uid']) || !is_numeric($args['uid'])) { $args['uid'] = UserUtil::getVar('uid'); } if (!isset($args['date'])) { $args['date'] = DateUtil::getDatetime(); } else { $args['date'] = DataUtil::formatForStore($args['date']); } // get the users ip $ipaddr = ''; if ($this->getVar('logip')) { $ipaddr = System::serverGetVar('REMOTE_ADDR'); } // check we should moderate the comments $status = array(0); // always moderate trackback or pingback comments if (in_array($args['type'], array('trackback', 'pingback'))) { $status[] = 1; } elseif ($this->getVar('moderation')) { // check if we should moderate all comments if ($this->getVar('alwaysmoderate')) { $status[] = 1; } else { $checkvars = array($args['subject'], $args['comment'], $args['anonname'], $args['anonmail'], $args['anonwebsite']); foreach ($checkvars as $checkvar) { $status[] = $this->checkcomment($checkvar); } } $status[] = $this->checksubmitter(); } // Akismet if (ModUtil::available('Akismet') && $this->getVar('Akismet')) { if (ModUtil::apiFunc('Akismet', 'user', 'isspam', array('author' => $loggedin ? UserUtil::getVar('uname') : $args['anonname'], 'authoremail' => $loggedin ? UserUtil::getVar('email') : (isset($args['anonmail']) ? $args['anonmail'] : ''), 'authorurl' => $loggedin ? UserUtil::getVar('url') : (isset($args['anonwebsite']) ? $args['anonwebsite'] : ''), 'content' => $args['comment'], 'permalink' => $url))) { $status[] = $this->getVar('akismetstatus'); } } // check for a blacklisted return if (in_array(2, $status)) { return LogUtil::registerError($this->__('Error! Your comment contains unacceptable content and has been rejected.')); } // check for a moderated return $maxstatus = in_array(1, $status) ? 1 : 0; // build new object $newcomment = array( 'modname' => $args['mod'], 'objectid' => $args['objectid'], 'areaid' => $args['areaid'], 'url' => $url, 'date' => $args['date'], 'uid' => $args['uid'], 'owneruid' => $owneruid, 'subject' => $args['subject'], 'comment' => $args['comment'], 'type' => $args['type'], 'replyto' => $args['replyto'], 'anonname' => $args['anonname'], 'anonmail' => $args['anonmail'], 'anonwebsite' => $args['anonwebsite'], 'status' => $maxstatus, 'ipaddr' => $ipaddr ); if (!($newcomment = DBUtil::insertObject($newcomment, 'EZComments'))) { return LogUtil::registerError($this->__('Error! Creation attempt failed.')); } // clear respective cache ModUtil::apiFunc('EZComments', 'user', 'clearItemCache', $newcomment); // set an approriate status/errormsg switch ($maxstatus) { case 0: LogUtil::registerStatus($this->__('Done! Your comment has been successfully added.')); break; case 1: LogUtil::registerStatus($this->__('Done! Your comment was held for moderation and will be reviewed shortly.')); break; } $toaddress = $adminEmail = System::getVar('adminmail'); $toname = $siteName = System::getVar('sitename'); if ($owneruid > 1) { $owner = array(); $owner['email'] = UserUtil::getVar('email', $owneruid); $owner['uname'] = UserUtil::getVar('uname', $owneruid); if (!empty($owner['email']) && !empty($owner['uname'])) { $toaddress = $owner['email']; $toname = $owner['uname']; } } // generate output $renderer = Zikula_View::getInstance('EZComments'); // prepare user line for emails if ($args['uid'] > 0) { $newcomment['userline'] = UserUtil::getVar('uname', $args['uid']); } else { $newcomment['userline'] = "$args[anonname]"; } $needsModeration = ($maxstatus > 0) ? true : false; // Inform the content owner or the admin about a new comment if (!$needsModeration && $this->getVar('MailToAdmin')) { $renderer->assign('comment', $newcomment); $renderer->assign('modifyurl', ModUtil::url('EZComments', 'user', 'modify', array('id' => $newcomment['id']), null, null, true)); ModUtil::apiFunc('Mailer', 'user', 'sendmessage', array('toaddress' => $toaddress, 'toname' => $toname, 'fromaddress' => $adminEmail, 'fromname' => $siteName, 'subject' => $this->__('A new comment was entered'), 'body' => $renderer->fetch('ezcomments_mail_newcomment.tpl'))); } if ($needsModeration && $this->getVar('moderationmail')) { $renderer->assign('comment', $newcomment); ModUtil::apiFunc('Mailer', 'user', 'sendmessage', array('toaddress' => $adminEmail, 'toname' => $siteName, 'fromaddress' => $adminEmail, 'fromname' => $siteName, 'subject' => $this->__('Moderation required for a new comment'), 'body' => $renderer->fetch('ezcomments_mail_modcomment.tpl'))); } return $newcomment['id']; }
/** * Updates the standard fields before updating a record. * * @param Doctrine_Event $event Event. * * @return void */ public function preUpdate(Doctrine_Event $event) { $event->getInvoker()->lu_date = DateUtil::getDatetime(); $event->getInvoker()->lu_uid = $this->_uid; }
/** * Smarty function to display an editable dynamic user data field. * * Example * {duditemdisplay propattribute='avatar'} * * Example * {duditemdisplay propattribute='realname' uid=$uid} * * Example * {duditemdisplay item=$item} * * Parameters passed in the $params array: * --------------------------------------- * string item The Profile DUD item. * string userinfo The userinfo information [if not set uid must be specified]. * string uid User ID to display the field value for (-1 = do not load). * string proplabel Property label to display (optional overrides the preformated dud item $item). * string propattribute Property attribute to display. * string default Default content for an empty DUD. * boolean showlabel Show the label? default = true. * * @param array $params All attributes passed to this function from the template. * @param object &$smarty Reference to the Zikula_View/Smarty object. * * @return string|boolean The results of the module function; empty string if the Profile module is not available; false if error. */ function smarty_function_duditemdisplay($params, &$smarty) { extract($params); unset($params); if (!ModUtil::available('Profile')) { return ''; } if (!isset($item)) { if (isset($proplabel)) { $item = ModUtil::apiFunc('Profile', 'user', 'get', array('proplabel' => $proplabel)); } else if (isset($propattribute)) { $item = ModUtil::apiFunc('Profile', 'user', 'get', array('propattribute' => $propattribute)); } else { return false; } } if (!isset($item) || empty ($item)) { return false; } $dom = ZLanguage::getModuleDomain('Profile'); // check for a template set if (!isset($tplset)) { $tplset = 'profile_duddisplay'; } // a default value if the user data is empty if (!isset($default)) { $default = ''; } if (!isset($uid)) { $uid = UserUtil::getVar('uid'); } if (!isset($userinfo)) { $userinfo = UserUtil::getVars($uid); } // get the value of this field from the userinfo array if (isset($userinfo['__ATTRIBUTES__'][$item['prop_attribute_name']])) { $uservalue = $userinfo['__ATTRIBUTES__'][$item['prop_attribute_name']]; } elseif (isset($userinfo[$item['prop_attribute_name']])) { // user's temp view for non-approved users needs this $uservalue = $userinfo[$item['prop_attribute_name']]; } else { // can be a non-marked checkbox in the user temp data $uservalue = ''; } // try to get the DUD output if it's Third Party if ($item['prop_dtype'] != 1) { $output = ModUtil::apiFunc($item['prop_modname'], 'dud', 'edit', array('item' => $item, 'userinfo' => $userinfo, 'uservalue' => $uservalue, 'default' => $default)); if ($output) { return $output; } } // build the output $output = ''; $render = Zikula_View::getInstance('Profile', false, null, true); $render->assign('item', $item); $render->assign('userinfo', $userinfo); $render->assign('uservalue', $uservalue); // detects the template to use $template = $tplset.'_'.$item['prop_id'].'.tpl'; if (!$render->template_exists($template)) { $template = $tplset.'_generic.tpl'; } $output = ''; // checks the different attributes and types // avatar if ($item['prop_attribute_name'] == 'avatar') { $baseurl = System::getBaseUrl(); $avatarpath = ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_AVATAR_IMAGE_PATH, Users_Constant::DEFAULT_AVATAR_IMAGE_PATH); if (empty($uservalue)) { $uservalue = 'blank.png'; } $output = "<img alt=\"\" src=\"{$baseurl}{$avatarpath}/{$uservalue}\" />"; } elseif ($item['prop_attribute_name'] == 'tzoffset') { // timezone if (empty($uservalue)) { $uservalue = UserUtil::getVar('tzoffset') ? UserUtil::getVar('tzoffset') : System::getVar('timezone_offset'); } $output = DateUtil::getTimezoneText($uservalue); if (!$output) { return ''; } } elseif ($item['prop_displaytype'] == 2) { // checkbox $default = array('No', 'Yes'); $output = array_splice(explode('@@', $item['prop_listoptions']), 1); if (!is_array($output) || count($output) < 2) { $output = $default; } $output = isset($output[(int)$uservalue]) && !empty($output[(int)$uservalue]) ? __($output[(int)$uservalue], $dom) : __($default[(int)$uservalue], $dom); } elseif ($item['prop_displaytype'] == 3) { // radio $options = ModUtil::apiFunc('Profile', 'dud', 'getoptions', array('item' => $item)); // process the user value and get the translated label $output = isset($options[$uservalue]) ? $options[$uservalue] : $default; } elseif ($item['prop_displaytype'] == 4) { // select $options = ModUtil::apiFunc('Profile', 'dud', 'getoptions', array('item' => $item)); // process the user values and get the translated label $uservalue = @unserialize($uservalue); $output = array(); foreach ((array)$uservalue as $id) { if (isset($options[$id])) { $output[] = $options[$id]; } } } elseif (!empty($uservalue) && $item['prop_displaytype'] == 5) { // date $format = ModUtil::apiFunc('Profile', 'dud', 'getoptions', array('item' => $item)); //! This is from the core domain (datebrief) $format = !empty($format) ? $format : __('%b %d, %Y'); $output = DateUtil::getDatetime(strtotime($uservalue), $format); } elseif ($item['prop_displaytype'] == 7) { // multicheckbox $options = ModUtil::apiFunc('Profile', 'dud', 'getoptions', array('item' => $item)); // process the user values and get the translated label $uservalue = @unserialize($uservalue); $output = array(); foreach ((array)$uservalue as $id) { if (isset($options[$id])) { $output[] = $options[$id]; } } } elseif ($item['prop_attribute_name'] == 'url') { // url if (!empty($uservalue) && $uservalue != 'http://') { //! string to describe the user's site $output = '<a href="'.DataUtil::formatForDisplay($uservalue).'" title="'.__f("%s's site", $userinfo['uname'], $dom).'" rel="nofollow">'.DataUtil::formatForDisplay($uservalue).'</a>'; } } elseif (empty($uservalue)) { // process the generics $output = $default; } elseif (DataUtil::is_serialized($uservalue) || is_array($uservalue)) { // serialized data $uservalue = !is_array($uservalue) ? unserialize($uservalue) : $uservalue; $output = array(); foreach ((array)$uservalue as $option) { $output[] = __($option, $dom); } } else { // a string $output .= __($uservalue, $dom); } // omit this field if is empty after the process if (empty($output)) { return ''; } return $render->assign('output', is_array($output) ? $output : array($output)) ->fetch($template); }
/** * Return a random date between $startDate and $endDate. * * @param string $startDate The lower date bound. * @param string $endDate The high date bound. * @param string $format The date format to use. * * @return The resulting random date string. */ public static function getDate($startDate, $endDate, $format = DATEFORMAT_FIXED) { $t1 = strtotime($startDate); $t2 = strtotime($endDate); $diff = $t2 - $t1; $inc = self::getInteger(0, $diff); $tRand = $t1 + $inc; return DateUtil::getDatetime($tRand, $format); }
/** * Process results from IDS scan. * * @param IDS_Init $init PHPIDS init object reference. * @param IDS_Report $result The result object from PHPIDS. * * @return void */ private function _processIdsResult(IDS_Init $init, IDS_Report $result) { // $result contains any suspicious fields enriched with additional info // Note: it is moreover possible to dump this information by simply doing //"echo $result", calling the IDS_Report::$this->__toString() method implicitely. $requestImpact = $result->getImpact(); if ($requestImpact < 1) { // nothing to do return; } // update total session impact to track an attackers activity for some time $sessionImpact = SessionUtil::getVar('idsImpact', 0) + $requestImpact; SessionUtil::setVar('idsImpact', $sessionImpact); // let's see which impact mode we are using $idsImpactMode = System::getVar('idsimpactmode', 1); $idsImpactFactor = 1; if ($idsImpactMode == 1) { $idsImpactFactor = 1; } elseif ($idsImpactMode == 2) { $idsImpactFactor = 10; } elseif ($idsImpactMode == 3) { $idsImpactFactor = 5; } // determine our impact threshold values $impactThresholdOne = System::getVar('idsimpactthresholdone', 1) * $idsImpactFactor; $impactThresholdTwo = System::getVar('idsimpactthresholdtwo', 10) * $idsImpactFactor; $impactThresholdThree = System::getVar('idsimpactthresholdthree', 25) * $idsImpactFactor; $impactThresholdFour = System::getVar('idsimpactthresholdfour', 75) * $idsImpactFactor; $usedImpact = ($idsImpactMode == 1) ? $requestImpact : $sessionImpact; // react according to given impact if ($usedImpact > $impactThresholdOne) { // db logging // determine IP address of current user $_REMOTE_ADDR = System::serverGetVar('REMOTE_ADDR'); $_HTTP_X_FORWARDED_FOR = System::serverGetVar('HTTP_X_FORWARDED_FOR'); $ipAddress = ($_HTTP_X_FORWARDED_FOR) ? $_HTTP_X_FORWARDED_FOR : $_REMOTE_ADDR; $currentPage = System::getCurrentUri(); $currentUid = UserUtil::getVar('uid'); $intrusionItems = array(); foreach ($result as $event) { $eventName = $event->getName(); $malVar = explode(".", $eventName, 2); $filters = array(); foreach ($event as $filter) { array_push($filters, array( 'id' => $filter->getId(), 'description' => $filter->getDescription(), 'impact' => $filter->getImpact(), 'tags' => $filter->getTags(), 'rule' => $filter->getRule())); } $tagVal = $malVar[1]; $newIntrusionItem = array( 'name' => array($eventName), 'tag' => $tagVal, 'value' => $event->getValue(), 'page' => $currentPage, 'uid' => $currentUid, 'ip' => $ipAddress, 'impact' => $result->getImpact(), 'filters' => serialize($filters), 'date' => DateUtil::getDatetime() ); if (array_key_exists($tagVal, $intrusionItems)) { $intrusionItems[$tagVal]['name'][] = $newIntrusionItem['name'][0]; } else { $intrusionItems[$tagVal] = $newIntrusionItem; } } // log details to database foreach ($intrusionItems as $tag => $intrusionItem) { $intrusionItem['name'] = implode(", ", $intrusionItem['name']); // create new ZIntrusion instance $obj = new SecurityCenter_DBObject_Intrusion(); // set data $obj->setData($intrusionItem); // save object to db $obj->save(); } } if (System::getVar('idsmail') && ($usedImpact > $impactThresholdTwo)) { // mail admin // prepare mail text $mailBody = __('The following attack has been detected by PHPIDS') . "\n\n"; $mailBody .= __f('IP: %s', $ipAddress) . "\n"; $mailBody .= __f('UserID: %s', $currentUid) . "\n"; $mailBody .= __f('Date: %s', DateUtil::strftime(__('%b %d, %Y'), (time()))) . "\n"; if ($idsImpactMode == 1) { $mailBody .= __f('Request Impact: %d', $requestImpact) . "\n"; } else { $mailBody .= __f('Session Impact: %d', $sessionImpact) . "\n"; } $mailBody .= __f('Affected tags: %s', join(' ', $result->getTags())) . "\n"; $attackedParameters = ''; foreach ($result as $event) { $attackedParameters .= $event->getName() . '=' . urlencode($event->getValue()) . ", "; } $mailBody .= __f('Affected parameters: %s', trim($attackedParameters)) . "\n"; $mailBody .= __f('Request URI: %s', urlencode($currentPage)); // prepare other mail arguments $siteName = System::getVar('sitename'); $adminmail = System::getVar('adminmail'); $mailTitle = __('Intrusion attempt detected by PHPIDS'); if (ModUtil::available('Mailer')) { $args = array(); $args['fromname'] = $siteName; $args['fromaddress'] = $adminmail; $args['toname'] = 'Site Administrator'; $args['toaddress'] = $adminmail; $args['subject'] = $mailTitle; $args['body'] = $mailBody; $rc = ModUtil::apiFunc('Mailer', 'user', 'sendmessage', $args); } else { $headers = "From: $siteName <$adminmail>\n" ."X-Priority: 1 (Highest)"; System::mail($adminmail, $mailTitle, $mailBody, $headers); } } if ($usedImpact > $impactThresholdThree) { // block request if (System::getVar('idssoftblock')) { // warn only for debugging the ruleset LogUtil::registerError(__('Malicious request code / a hacking attempt was detected. This request has NOT been blocked!')); } else { throw new Zikula_Exception_Forbidden(__('Malicious request code / a hacking attempt was detected. Thus this request has been blocked.'), null, $result); } } return; }
/** * Returns DQL code. * * @param string $field Field name. * @param string $op Operator. * @param string $value Test value. * * @return array Doctrine Query where clause and parameters. */ public function getDql($field, $op, $value) { if (array_search($op, $this->ops) === false || !$this->fieldExists($field)) { return ''; } $type = 'point'; if (preg_match('~^(year|month|week|day|hour|min):\\s*(.*)$~i', $value, $res)) { $type = strtolower($res[1]); if (strlen($res[2]) == 4) { $res[2] = "01.01." . $res[2]; } $time = strtotime($res[2]); } elseif (preg_match('~(year|month|week|day|hour|min|tomorrow)~', $value, $res)) { $type = strtolower($res[1]); $time = strtotime($value); } else { $time = strtotime($value); } $where = ''; $params = array(); $column = $this->getColumn($field); switch ($op) { case 'eq': if ($type != 'point') { list($from, $to) = $this->makePeriod($time, $type); $where = "({$column} >= ? AND {$column} < ?)"; $params[] = DateUtil::getDatetime($from); $params[] = DateUtil::getDatetime($to); } else { $where = "{$column} = ?"; $params[] = DateUtil::getDatetime($time); } break; case 'ne': if ($type != 'point') { list($from, $to) = $this->makePeriod($time, $type); $where = "({$column} < ? OR {$column} >= ?)"; $params[] = DateUtil::getDatetime($from); $params[] = DateUtil::getDatetime($to); } else { $where = "{$column} <> ?"; $params[] = DateUtil::getDatetime($time); } break; case 'gt': if ($type != 'point') { list($from, $time) = $this->makePeriod($time, $type); } $where = "{$column} > ?"; $params[] = DateUtil::getDatetime($time); break; case 'ge': $where = "{$column} >= ?"; $params[] = DateUtil::getDatetime($time); break; case 'lt': $where = "{$column} < ?"; $params[] = DateUtil::getDatetime($time); break; case 'le': if ($type != 'point') { list($from, $time) = $this->makePeriod($time, $type); } $where = "{$column} <= ?"; $params[] = DateUtil::getDatetime($time); break; } return array('where' => $where, 'params' => $params); }
public function insert($timestamp, array &$obj) { if (!in_array(DateUtil::getDatetime($timestamp, DATEONLYFORMAT_FIXED), $this->_dates)) { $this->_out->insert($timestamp, $obj); } }
/** * Display the data to the containing Content page */ public function display() { // Parameters for category related items properties like topicimage $lang = ZLanguage::getLanguageCode(); $topicProperty = ModUtil::getVar('News', 'topicproperty'); $topicField = empty($topicProperty) ? 'Main' : $topicProperty; // work out the parameters for the News api call $apiargs = array(); switch ($this->show) { case 3: // non index page articles $apiargs['displayonindex'] = 0; break; case 2: // index page articles $apiargs['displayonindex'] = 1; break; // all - doesn't need displayonindex } $apiargs['numitems'] = $this->limit; // Nr of articles to obtain $apiargs['status'] = (int) $this->status; // Published status // Handle the sorting order switch ($this->orderoptions) { case 2: $apiargs['order'] = 'weight'; break; case 3: $apiargs['order'] = 'random'; break; case 1: $apiargs['order'] = 'counter'; break; case 0: default: // Use News module setting, so don't set apiargs[order] } $enablecategorization = ModUtil::getVar('News', 'enablecategorization'); // Make a category filter only if categorization is enabled in News module if ($enablecategorization && $this->categories != null) { // Get the registrered categories for the News module $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('News', 'news'); $apiargs['catregistry'] = $catregistry; $apiargs['category'] = $this->categories; } // Limit the shown articles in days using DateUtil if ((int) $this->dayslimit > 0 && $vars['order'] == 0) { $apiargs['from'] = DateUtil::getDatetime_NextDay(-$this->dayslimit); $apiargs['to'] = DateUtil::getDatetime(); } // Apply datefiltering $apiargs['filterbydate'] = true; // call the News api and get the requested articles with the above arguments $items = ModUtil::apiFunc('News', 'user', 'getall', $apiargs); // UserUtil is not automatically loaded, so load it now if needed and set anonymous if ($this->dispuname) { $anonymous = System::getVar('anonymous'); } // check for an empty return if (!empty($items)) { // loop through the items and prepare for display foreach (array_keys($items) as $k) { // Get specific information from the article. It was a choice not to use the pnuserapi functions // GetArticleInfo, GetArticleLinks and getArticlesPreformat because of speed etc. // --- Check for Topic related properties like topicimage, topicsearchurl etc. if ($enablecategorization && !empty($items[$k]['__CATEGORIES__']) && isset($items[$k]['__CATEGORIES__'][$topicField])) { $items[$k]['topicid'] = $items[$k]['__CATEGORIES__'][$topicField]['id']; $items[$k]['topicname'] = isset($items[$k]['__CATEGORIES__'][$topicField]['display_name'][$lang]) ? $items[$k]['__CATEGORIES__'][$topicField]['display_name'][$lang] : $items[$k]['__CATEGORIES__'][$topicField]['name']; // set the topic image if topic_image category property exists $items[$k]['topicimage'] = (isset($items[$k]['__CATEGORIES__'][$topicField]['__ATTRIBUTES__']) && isset($items[$k]['__CATEGORIES__'][$topicField]['__ATTRIBUTES__']['topic_image'])) ? $items[$k]['__CATEGORIES__'][$topicField]['__ATTRIBUTES__']['topic_image'] : ''; // set the topic description if exists $items[$k]['topictext'] = isset($items[$k]['__CATEGORIES__'][$topicField]['display_desc'][$lang]) ? $items[$k]['__CATEGORIES__'][$topicField]['display_desc'][$lang] : ''; // set the path of the topic $items[$k]['topicpath'] = isset($items[$k]['__CATEGORIES__'][$topicField]['path_relative']) ? $items[$k]['__CATEGORIES__'][$topicField]['path_relative'] : ''; // set the url to search for this topic if (System::getVar('shorturls', false)) { $items[$k]['topicsearchurl'] = DataUtil::formatForDisplay(ModUtil::url('News', 'user', 'view', array('prop' => $topicField, 'cat' => $items[$k]['topicpath']))); } else { $items[$k]['topicsearchurl'] = DataUtil::formatForDisplay(ModUtil::url('News', 'user', 'view', array('prop' => $topicField, 'cat' => $items[$k]['topicid']))); } } else { $items[$k]['topicid'] = null; $items[$k]['topicname'] = ''; $items[$k]['topicimage'] = ''; $items[$k]['topictext'] = ''; $items[$k]['topicpath'] = ''; $items[$k]['topicsearchurl'] = ''; } // Optional new image if the difference in days from the publishing date and now < the specified limit $items[$k]['dispnewimage'] = ($this->dispnewimage && DateUtil::getDatetimeDiff_AsField($items[$k]['from'], DateUtil::getDatetime(), 3) < (int) $this->newimagelimit); // Wrap the title if needed $items[$k]['titlewrapped'] = false; if ((int) $this->maxtitlelength > 0 && strlen($items[$k]['title']) > (int) $this->maxtitlelength) { // wrap the title $items[$k]['title'] = substr($items[$k]['title'], 0, (int) $this->maxtitlelength); $items[$k]['titlewrapped'] = true; //$items[$k]['title'] .= $this->titlewraptext; } // Get the user information from the author id if ($this->dispuname) { if ($items[$k]['cr_uid'] == 0) { $items[$k]['uname'] = $anonymous; $items[$k]['aid_name'] = $anonymous; } else { $user = UserUtil::getVars($items[$k]['cr_uid']); $items[$k]['uname'] = $user['uname']; $items[$k]['aid_name'] = $user['uname']; } } // Get the optional commentcount if EZComments is available if ($this->dispcomments && ModUtil::available('EZComments')) { $items[$k]['comments'] = ModUtil::apiFunc('EZComments', 'user', 'countitems', array('mod' => 'News', 'objectid' => $items[$k]['sid'], 'status' => 0)); } // Optional display of the hometext (frontpage teaser) if ($this->disphometext) { if ($this->maxhometextlength > 0 && strlen(strip_tags($items[$k]['hometext'])) > (int) $this->maxhometextlength) { $items[$k]['hometextwrapped'] = true; } } $items[$k]['readperm'] = (SecurityUtil::checkPermission('News::', "$items[$k][cr_uid]::$items[$k][sid]", ACCESS_READ)); } if ($this->dispuname || $this->dispdate || $this->dispreads || $this->dispcomments) { $this->view->assign('dispinfo', true); $this->view->assign('dispuname', $this->dispuname); $this->view->assign('dispdate', $this->dispdate); $this->view->assign('dispreads', $this->dispreads); $this->view->assign('dispcomments', $this->dispcomments); $this->view->assign('dispsplitchar', $this->dispsplitchar); } else { $this->view->assign('dispinfo', false); } if ($this->dispnewimage) { $this->view->assign('newimageset', $this->newimageset); $this->view->assign('newimagesrc', $this->newimagesrc); } $this->view->assign('disphometext', $this->disphometext); if ($this->disphometext) { $this->view->assign('hometextwraptext', $this->hometextwraptext); $this->view->assign('maxhometextlength', $this->maxhometextlength); } $this->view->assign('titlewraptext', $this->titlewraptext); } $this->view->assign('News', ModUtil::getVar('News')); $this->view->assign('dateformat', $this->dateformat); $this->view->assign('linktosubmit', $this->linktosubmit); $this->view->assign('stories', $items); $this->view->assign('title', $this->title); $this->view->assign('displayStoryImage', $this->displayStoryImage); $this->view->assign('useshorturls', System::getVar('shorturls', false)); return $this->view->fetch($this->getTemplate()); }
public function getLocks($args) { $lockName = $args['lockName']; $sessionId = array_key_exists('sessionId', $args) ? $args['sessionId'] : session_id(); $this->_pageLockRequireAccess(); $dbtable = DBUtil::getTables(); $pageLockColumn =& $dbtable['pagelock_column']; $now = time(); $where = "{$pageLockColumn['expiresDate']} < '" . DateUtil::getDatetime($now) . "'"; DBUtil::deleteWhere('pagelock', $where); $where = "{$pageLockColumn['name']} = '" . DataUtil::formatForStore($lockName) . "' AND {$pageLockColumn['lockedBySessionId']} != '" . DataUtil::formatForStore($sessionId) . "'"; $locks = DBUtil::selectObjectArray('pagelock', $where); $this->_pageLockReleaseAccess(); return $locks; }
/** * Formats an event. * * @param array $args Event. * * @return array * @throws InvalidArgumentException In case of invalid parameters. */ function getEventPreformat($args) { if (!isset($args['obj']) || empty($args['obj'])) { throw new InvalidArgumentException('$obj arg not set'); } $obj =& $args['obj']; //process text format if (substr($obj['text'], 0, 11) == "#plaintext#") { $obj['text'] = substr_replace($obj['text'], "", 0, 11); $obj['text'] = nl2br($obj['text']); } // hooks if (!isset($args['noHooks']) || $args['noHooks'] == false) { $obj['text'] = ModUtil::callHooks('item', 'transform', '', array($obj['text'])); $obj['text'] = $obj['text'][0]; } // repeats if ($obj['repeatType'] == 2) { $temp = explode(' ', $obj['repeatSpec']); $obj['repeat21'] = $temp[0]; $obj['repeat22'] = $temp[1]; } // split duration $obj['allDayDur'] = explode(',', $obj['allDayDur']); TimeIt_Util::convertAlldayStartToLocalTime($obj); // set username $obj['cr_name'] = UserUtil::getVar('uname', (int) $obj['cr_uid']); $obj['cr_datetime'] = DateUtil::getDatetime(strtotime($obj['cr_date']), "datetimebrief"); // set group name if ($obj['group'] == 'all') { $obj['group_name'] = 'all'; } else { $groupNames = array(); foreach (explode(',', $obj['group']) as $grpId) { $groupObj = UserUtil::getPNGroup((int) $grpId); $groupNames[] = $groupObj['name']; } $obj['group_name'] = $groupNames; } return $obj; }
/** * Render event handler. * * @param Zikula_Form_View $view Reference to Zikula_Form_View object. * * @return string The rendered output */ public function render(Zikula_Form_View $view) { static $firstTime = true; $i18n = ZI18n::getInstance(); if (!empty($this->defaultValue) && !$view->isPostBack()) { $d = strtolower($this->defaultValue); $now = getdate(); $date = null; if ($d == 'now') { $date = time(); } elseif ($d == 'today') { $date = mktime(0, 0, 0, $now['mon'], $now['mday'], $now['year']); } elseif ($d == 'monthstart') { $date = mktime(0, 0, 0, $now['mon'], 1, $now['year']); } elseif ($d == 'monthend') { $daysInMonth = date('t'); $date = mktime(0, 0, 0, $now['mon'], $daysInMonth, $now['year']); } elseif ($d == 'yearstart') { $date = mktime(0, 0, 0, 1, 1, $now['year']); } elseif ($d == 'yearend') { $date = mktime(0, 0, 0, 12, 31, $now['year']); } elseif ($d == 'custom') { $date = strtotime($this->initDate); } if ($date != null) { $this->text = DateUtil::getDatetime($date, $this->ifFormat, false); } else { $this->text = __('Unknown date'); } } if ($view->isPostBack() && !empty($this->text)) { $date = strtotime($this->text); $this->text = DateUtil::getDatetime($date, $this->ifFormat, false); } if ($firstTime) { $lang = ZLanguage::transformFS(ZLanguage::getLanguageCode()); // map of the jscalendar supported languages $map = array('ca' => 'ca_ES', 'cz' => 'cs_CZ', 'da' => 'da_DK', 'de' => 'de_DE', 'el' => 'el_GR', 'en-us' => 'en_US', 'es' => 'es_ES', 'fi' => 'fi_FI', 'fr' => 'fr_FR', 'he' => 'he_IL', 'hr' => 'hr_HR', 'hu' => 'hu_HU', 'it' => 'it_IT', 'ja' => 'ja_JP', 'ko' => 'ko_KR', 'lt' => 'lt_LT', 'lv' => 'lv_LV', 'nl' => 'nl_NL', 'no' => 'no_NO', 'pl' => 'pl_PL', 'pt' => 'pt_BR', 'ro' => 'ro_RO', 'ru' => 'ru_RU', 'si' => 'si_SL', 'sk' => 'sk_SK', 'sv' => 'sv_SE', 'tr' => 'tr_TR'); if (isset($map[$lang])) { $lang = $map[$lang]; } $headers[] = 'javascript/jscalendar/calendar.js'; if (file_exists("javascript/jscalendar/lang/calendar-{$lang}.utf8.js")) { $headers[] = "javascript/jscalendar/lang/calendar-{$lang}.utf8.js"; } $headers[] = 'javascript/jscalendar/calendar-setup.js'; PageUtil::addVar('stylesheet', 'javascript/jscalendar/calendar-win2k-cold-2.css'); PageUtil::addVar('javascript', $headers); } $firstTime = false; $result = ''; if ($this->useSelectionMode) { $hiddenInputField = str_replace(array('type="text"', ' *'), array('type="hidden"', ''), parent::render($view)); $result .= '<div>' . $hiddenInputField . '<span id="' . $this->id . 'cal" style="background-color: #ff8; cursor: default" onmouseover="this.style.backgroundColor=\'#ff0\';" onmouseout="this.style.backgroundColor=\'#ff8\';">'; if ($this->text) { $result .= DataUtil::formatForDisplay(DateUtil::getDatetime(DateUtil::parseUIDate($this->text, $this->ifFormat), $this->daFormat)); } else { $result .= __('Select date'); } $result .= '</span></div>'; if ($this->mandatory && $this->mandatorysym) { $result .= '<span class="z-form-mandatory-flag">*</span>'; } } else { $result .= '<span class="z-form-date" style="white-space: nowrap">'; $result .= parent::render($view); $txt = __('Select date'); $result .= " <img id=\"{$this->id}_img\" src=\"javascript/jscalendar/img.gif\" style=\"vertical-align: middle\" class=\"clickable\" alt=\"{$txt}\" /></span>"; } // build jsCalendar script options $result .= "<script type=\"text/javascript\">\n // <![CDATA[\n Calendar.setup(\n {\n inputField : \"{$this->id}\","; if ($this->includeTime) { $this->initDate = str_replace('-', ',', $this->initDate); $result .= "\n ifFormat : \"" . $this->ifFormat . "\",\n showsTime : true,\n timeFormat : \"" . $i18n->locale->getTimeformat() . "\",\n singleClick : false,"; } else { $result .= "\n ifFormat : \"" . $this->ifFormat . "\","; } if ($this->useSelectionMode) { $result .= "\n displayArea : \"{$this->id}cal\",\n daFormat : \"{$this->daFormat}\",\n align : \"Bl\",\n singleClick : true,"; } else { $result .= "\n button : \"{$this->id}_img\","; } $result .= "\n firstDay: " . $i18n->locale->getFirstweekday() . "\n }\n );\n // ]]>\n </script>"; return $result; }
/** * display article archives * * @author Andreas Krapohl * @author Mark West * @return string HTML string */ public function archives($args) { // Get parameters from whatever input we need $year = (int)FormUtil::getPassedValue('year', null, 'REQUEST'); $month = (int)FormUtil::getPassedValue('month', null, 'REQUEST'); $day = '31'; $this->throwForbiddenUnless(SecurityUtil::checkPermission('News::', '::', ACCESS_OVERVIEW), LogUtil::getErrorMsgPermission()); // Dates validation $currentdate = explode(',', DateUtil::getDatetime('', '%Y,%m,%d')); if (!empty($year) || !empty($month)) { if ((empty($year) || empty($month)) || ($year > (int)$currentdate[0] || ($year == (int)$currentdate[0] && $month > (int)$currentdate[1]))) { $this->redirect(ModUtil::url('News', 'user', 'archives')); } elseif ($year == (int)$currentdate[0] && $month == (int)$currentdate[1]) { $day = (int)$currentdate[2]; } } // Load localized month names $monthnames = explode(' ', $this->__('January February March April May June July August September October November December')); // Create output object // For caching reasons you must pass a cache ID $cacheid = '_'.$year.'|'.$month; // to prevent colision year with article id $this->view->setCacheId($cacheid); $template = 'user/archives.tpl'; if ($this->view->is_cached($template)) { return $this->view->fetch($template); } // output vars $archivemonths = array(); $archiveyears = array(); if (!empty($year) && !empty($month)) { $items = ModUtil::apiFunc('News', 'user', 'getall', array('order' => 'from', 'from' => "$year-$month-01 00:00:00", 'to' => "$year-$month-$day 23:59:59", 'status' => 0)); $this->view->assign('year', $year); $this->view->assign('month', $monthnames[$month - 1]); } else { // get all matching news articles $monthsyears = ModUtil::apiFunc('News', 'user', 'getMonthsWithNews'); foreach ($monthsyears as $monthyear) { $month = DateUtil::getDatetime_Field($monthyear, 2); $year = DateUtil::getDatetime_Field($monthyear, 1); $dates[$year][] = $month; } foreach ($dates as $year => $years) { foreach ($years as $month) { //$linktext = $monthnames[$month-1]." $year"; $linktext = $monthnames[$month - 1]; $nrofarticles = ModUtil::apiFunc('News', 'user', 'countitems', array('from' => "$year-$month-01 00:00:00", 'to' => "$year-$month-$day 23:59:59", 'status' => 0)); $archivemonths[$year][$month] = array('url' => ModUtil::url('News', 'user', 'archives', array('month' => $month, 'year' => $year)), 'title' => $linktext, 'nrofarticles' => $nrofarticles); } } $items = false; } $this->view->assign('archivemonths', $archivemonths); $this->view->assign('archiveitems', $items); $this->view->assign('enablecategorization', $this->getVar('enablecategorization')); // Return the output that has been generated by this function return $this->view->fetch($template); }