function getNumberOfPostsThisMonth()
 {
     $today = new Timestamp();
     $monthTimestamp = $today->getYear() . $today->getMonth();
     $query = "SELECT COUNT(*) AS total FROM " . $this->getPrefix() . "articles" . " WHERE date LIKE '{$monthTimestamp}%' AND status = 1";
     return $this->getTotalFromQuery($query);
 }
 /**
  * Carries out the specified action
  */
 function perform()
 {
     // fetch our data
     $this->_albumName = Textfilter::filterAllHTML($this->_request->getValue("albumName"));
     $this->_albumDescription = Textfilter::filterAllHTML($this->_request->getValue("albumDescription"));
     $this->_parentId = $this->_request->getValue("parentId");
     $showAlbum = $this->_request->getValue("showAlbum") ? 1 : 0;
     // create the album
     $albums = new GalleryAlbums();
     $t = new Timestamp();
     $album = new GalleryAlbum($this->_blogInfo->getId(), $this->_albumName, $this->_albumDescription, GALLERY_RESOURCE_PREVIEW_AVAILABLE, $this->_parentId, $t->getTimestamp(), array(), $showAlbum);
     $this->notifyEvent(EVENT_PRE_ALBUM_ADD, array("album" => &$album));
     // and add it to the database
     $result = $albums->addAlbum($album);
     $this->_view = new AdminResourcesListView($this->_blogInfo, array("albumId" => $this->_parentId));
     if ($result) {
         $this->_view->setSuccessMessage($this->_locale->pr("album_added_ok", $album->getName()));
         $this->notifyEvent(EVENT_POST_ALBUM_ADD, array("album" => &$album));
         // clear the cache if everything went fine
         CacheControl::resetBlogCache($this->_blogInfo->getId(), false);
     } else {
         $this->_view->setErrorMessage($this->_locale->tr("error_adding_album"));
     }
     $this->setCommonData();
     // better to return true if everything fine
     return true;
 }
 /**
  * generates an archive link given a date. 
  *
  * @param date A Timestamp object
  * @return A valid archive link
  */
 function getArchiveLink($date)
 {
     $archiveLinkFormat = $this->_config->getValue('archive_link_format');
     $ownerInfo = $this->_blogInfo->getOwnerInfo();
     // this is quite a dirty one but it works...
     $newDate = $date;
     if (strlen($date) == 6) {
         $newDate = $date . "00000000";
     }
     if (strlen($date) == 8) {
         $newDate = $date . "000000";
     }
     $t = new Timestamp($newDate);
     $params = array("{year}" => $t->getYear(), "{month}" => $t->getMonth(), "{blogname}" => $this->_blogInfo->getMangledBlog(), "{blogowner}" => $ownerInfo->getUsername(), "{blogid}" => $this->_blogInfo->getId());
     if (strlen($date) == 6) {
         $params["{day}"] = "";
     } else {
         $day = $t->getDay();
         if ($day < 10) {
             $day = "0" . $day;
         }
         $params["{day}"] = $day;
     }
     $archiveLink = $this->getBaseUrl() . $this->_replaceTags($archiveLinkFormat, $params);
     return $archiveLink;
 }
 /**
  * Loads the blog info and show it
  */
 function perform()
 {
     $this->_blogId = $this->_request->getValue("blogId");
     $this->_view = new SummaryCachedView("blogprofile", array("summary" => "BlogProfile", "blogId" => $this->_blogId, "locale" => $this->_locale->getLocaleCode()));
     if ($this->_view->isCached()) {
         // nothing to do, the view is cached
         return true;
     }
     // load some information about the user
     $blogs = new Blogs();
     $blogInfo = $blogs->getBlogInfo($this->_blogId, true);
     // if there was no blog or the status was incorrect, let's not show it!
     if (!$blogInfo || $blogInfo->getStatus() != BLOG_STATUS_ACTIVE) {
         $this->_view = new SummaryView("error");
         $this->_view->setValue("message", $this->_locale->tr("error_incorrect_blog_id"));
         return false;
     }
     // fetch the blog latest posts
     $posts = array();
     $articles = new Articles();
     $t = new Timestamp();
     $posts = $articles->getBlogArticles($blogInfo->getId(), -1, SUMMARY_DEFAULT_RECENT_BLOG_POSTS, 0, POST_STATUS_PUBLISHED, 0, $t->getTimestamp());
     $this->_view->setValue("blog", $blogInfo);
     $this->_view->setValue("blogposts", $posts);
     $this->setCommonData();
     return true;
 }
 function perform()
 {
     // fetch the data
     $this->_ip1 = $this->_request->getValue("ip1");
     $this->_ip2 = $this->_request->getValue("ip2");
     $this->_ip3 = $this->_request->getValue("ip3");
     $this->_ip4 = $this->_request->getValue("ip4");
     $this->_hostIp = $this->_ip1 . "." . $this->_ip2 . "." . $this->_ip3 . "." . $this->_ip4;
     $this->_mask = $this->_request->getValue("mask");
     $this->_blockType = $this->_request->getValue("blockType");
     $this->_reason = $this->_request->getValue("reason");
     // create the dao object and add the info to the db
     $blockedHosts = new BlockedHosts();
     $t = new Timestamp();
     $blockedHost = new BlockedHost($this->_hostIp, $this->_mask, $this->_reason, $t->getTimestamp(), GLOBALLY_BLOCKED_HOST, $this->_blockType, BLOCK_BLACKLIST);
     $this->notifyEvent(EVENT_PRE_BLOCK_HOST_ADD, array("host" => &$blockedHost));
     $result = $blockedHosts->add($blockedHost);
     // and give some feedback to the user
     if (!$result) {
         $this->_view = new AdminNewBlockedHostView($this->_blogInfo);
         $this->_view->setErrorMessage($this->_locale->tr("error_adding_blocked_host"));
         $this->setCommonData();
         return false;
     }
     $this->notifyEvent(EVENT_POST_BLOCK_HOST_ADD, array("host" => &$blockedHost));
     $this->_view = new AdminBlockedHostsView($this->_blogInfo);
     $this->_view->setSuccessMessage($this->_locale->tr("blocked_host_updated_ok"));
     $this->setCommonData();
     // clear the cache
     CacheControl::resetBlogCache($this->_blogInfo->getId());
     return true;
 }
 /**
  * Performs the action.
  */
 function perform()
 {
     // fetch the articles for the given blog
     $articles = new Articles();
     $blogSettings = $this->_blogInfo->getSettings();
     $localeCode = $blogSettings->getValue("locale");
     // fetch the default profile as chosen by the administrator
     $defaultProfile = $this->_config->getValue("default_rss_profile");
     if ($defaultProfile == "" || $defaultProfile == null) {
         $defaultProfile = DEFAULT_PROFILE;
     }
     // fetch the profile
     // if the profile specified by the user is not valid, then we will
     // use the default profile as configured
     $profile = $this->_request->getValue("profile");
     if ($profile == "") {
         $profile = $defaultProfile;
     }
     // fetch the category, or set it to '0' otherwise, which will mean
     // fetch all the most recent posts from any category
     $categoryId = $this->_request->getValue("categoryId");
     if (!is_numeric($categoryId)) {
         $categoryId = 0;
     }
     // check if the template is available
     $this->_view = new RssView($this->_blogInfo, $profile, array("profile" => $profile, "categoryId" => $categoryId));
     // do nothing if the view was already cached
     if ($this->_view->isCached()) {
         return true;
     }
     // create an instance of a locale object
     $locale = Locales::getLocale($localeCode);
     // fetch the posts, though we are going to fetch the same amount in both branches
     $amount = $blogSettings->getValue("recent_posts_max", 15);
     $t = new Timestamp();
     if ($blogSettings->getValue('show_future_posts_in_calendar')) {
         $blogArticles = $articles->getBlogArticles($this->_blogInfo->getId(), -1, $amount, $categoryId, POST_STATUS_PUBLISHED, 0);
     } else {
         $today = $t->getTimestamp();
         $blogArticles = $articles->getBlogArticles($this->_blogInfo->getId(), -1, $amount, $categoryId, POST_STATUS_PUBLISHED, 0, $today);
     }
     $pm =& PluginManager::getPluginManager();
     $pm->setBlogInfo($this->_blogInfo);
     $pm->setUserInfo($this->_userInfo);
     $result = $pm->notifyEvent(EVENT_POSTS_LOADED, array('articles' => &$blogArticles));
     $articles = array();
     foreach ($blogArticles as $article) {
         $postText = $article->getIntroText();
         $postExtendedText = $article->getExtendedText();
         $pm->notifyEvent(EVENT_TEXT_FILTER, array("text" => &$postText));
         $pm->notifyEvent(EVENT_TEXT_FILTER, array("text" => &$postExtendedText));
         $article->setIntroText($postText);
         $article->setExtendedText($postExtendedText);
         array_push($articles, $article);
     }
     $this->_view->setValue("locale", $locale);
     $this->_view->setValue("posts", $articles);
     $this->setCommonData();
     return true;
 }
Exemple #7
0
 public function testGenerate()
 {
     $result = $this->object->generate();
     $this->assertNotEmpty($result);
     $this->assertInternalType('string', $result);
     sleep(1);
     $this->assertNotEquals($result, $this->object->generate(), 'Unique value is expected');
 }
 /**
  * Creates a new FilteredContent object
  *
  * @param regExp the regular expression
  * @param blogId The blog identifier to which this rule belongs
  * @param reason Why this rule has been set-up
  * @param date When this rule was added
  * @param id Identifier of this rule
  */
 function FilteredContent($regExp, $blogId, $reason, $date = null, $id = -1)
 {
     $this->Object();
     $this->_regExp = $regExp;
     $this->_blogId = $blogId;
     $this->_reason = $reason;
     if ($date == null) {
         $t = new Timestamp();
         $this->_date = $t->getTimestamp();
     } else {
         $this->_date = $date;
     }
     $this->_id = $id;
 }
function lastArtist()
{
    $db = new DBHandler();
    $stmt = $db->query("SELECT ar.id, ar.name, ar.uploadDate, ar.uploadUser FROM artist ar order by ar.uploadDate DESC limit 5;");
    $data = "";
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $data = $data . $row[0] . "," . $row[1] . ",";
        $tstamp = new Timestamp($row[2]);
        $udate = $tstamp->format("y-m-d");
        $data = $data . $udate . "," . $row[3] . ";";
    }
    $stmt->closeCursor();
    echo $data;
}
 /**
  * Convert the raw XML into an object
  *
  * @param \SimpleXMLElement $xml
  * @return Timestamp
  */
 public static function createFromXML(\SimpleXMLElement $xml)
 {
     $timestamp = new Timestamp();
     if (isset($xml->date)) {
         if (isset($xml->timestart)) {
             $start = (string) $xml->date . ' ' . (string) $xml->timestart;
             $timestamp->setTimeStart(new \DateTime($start));
         }
         if (isset($xml->timeend)) {
             $end = (string) $xml->date . ' ' . (string) $xml->timeend;
             $timestamp->setTimeEnd(new \DateTime($end));
         }
     }
     return $timestamp;
 }
 public function testDayDifference()
 {
     $today = Date::makeToday();
     $this->dayDifferenceTest($today, $today, 0);
     $timestamp = Timestamp::makeNow();
     $this->dayDifferenceTest($timestamp, $timestamp, 0);
     $left = Date::create('2008-01-12');
     $right = Date::create('2008-01-13');
     $this->dayDifferenceTest($left, $right, 1);
     $left = Date::create('2008-01-12');
     $right = Date::create('2009-01-13');
     $this->dayDifferenceTest($left, $right, 367);
     $left = Date::create('2008-01-12');
     $right = Date::create('2008-01-11');
     $this->dayDifferenceTest($left, $right, -1);
     $left = Timestamp::create('2008-01-12 01:23:00');
     $right = Timestamp::create('2008-01-13 13:01:17');
     $this->dayDifferenceTest($left, $right, 1);
     // change time from winter to summer
     $left = Timestamp::create('2008-03-29 02:00:00');
     $right = Timestamp::create('2008-03-30 02:00:00');
     $this->dayDifferenceTest($left, $right, 1);
     $left = Timestamp::create('2008-03-29 03:00:00');
     $right = Timestamp::create('2008-03-30 03:00:00');
     $this->dayDifferenceTest($left, $right, 1);
     // unsolved giv's case
     // $left = Timestamp::create('2008-10-25 03:00:00');
     // $right = Timestamp::create('2008-10-26 02:59:00');
     // $this->dayDifferenceTest($left, $right, 0);
     return $this;
 }
 /**
  * @return Timestamp
  * 
  * Emulates PostgreSQL's date_trunc() function
  * 
  **/
 public function truncate(Date $time, $ceil = false)
 {
     $time = $time->toTimestamp();
     $function = $ceil ? 'ceil' : 'floor';
     if ($this->seconds) {
         if ($this->seconds < 1) {
             return $time->spawn();
         }
         $truncated = (int) ($function($time->toStamp() / $this->seconds) * $this->seconds);
         return Timestamp::create($truncated);
     } elseif ($this->days) {
         $epochStartTruncated = Date::create('1970-01-05');
         $truncatedDate = Date::create($time->toDate());
         if ($ceil && $truncatedDate->toStamp() < $time->toStamp()) {
             $truncatedDate->modify('+1 day');
         }
         $difference = Date::dayDifference($epochStartTruncated, $truncatedDate);
         $truncated = (int) ($function($difference / $this->days) * $this->days);
         return Timestamp::create($epochStartTruncated->spawn($truncated . ' days')->toStamp());
     } elseif ($this->months) {
         $monthsCount = $time->getYear() * 12 + ($time->getMonth() - 1);
         if ($ceil && $time->getDay() - 1 + $time->getHour() + $time->getMinute() + $time->getSecond() > 0) {
             $monthsCount += 0.1;
         }
         // delta
         $truncated = (int) ($function($monthsCount / $this->months) * $this->months);
         $months = $truncated % 12;
         $years = ($truncated - $months) / 12;
         Assert::isEqual($years, (int) $years);
         $years = (int) $years;
         $months = $months + 1;
         return Timestamp::create("{$years}-{$months}-01 00:00:00");
     }
     Assert::isUnreachable();
 }
 /**
  * Install hstore
  * /usr/share/postgresql/contrib # cat hstore.sql | psql -U pgsql -d onphp
  **/
 public function testHstore()
 {
     foreach (DBTestPool::me()->getPool() as $connector => $db) {
         DBPool::me()->setDefault($db);
         $properties = array('age' => '23', 'weight' => 80, 'comment' => null);
         $user = TestUser::create()->setCity($moscow = TestCity::create()->setName('Moscow'))->setCredentials(Credentials::create()->setNickname('fake')->setPassword(sha1('passwd')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'))->setProperties(Hstore::make($properties));
         $moscow = TestCity::dao()->add($moscow);
         $user = TestUser::dao()->add($user);
         Cache::me()->clean();
         TestUser::dao()->dropIdentityMap();
         $user = TestUser::dao()->getById('1');
         $this->assertInstanceOf('Hstore', $user->getProperties());
         $this->assertEquals($properties, $user->getProperties()->getList());
         $form = TestUser::proto()->makeForm();
         $form->get('properties')->setFormMapping(array(Primitive::string('age'), Primitive::integer('weight'), Primitive::string('comment')));
         $form->import(array('id' => $user->getId()));
         $this->assertNotNull($form->getValue('id'));
         $object = $user;
         FormUtils::object2form($object, $form);
         $this->assertInstanceOf('Hstore', $form->getValue('properties'));
         $this->assertEquals(array_filter($properties), $form->getValue('properties')->getList());
         $subform = $form->get('properties')->getInnerForm();
         $this->assertEquals($subform->getValue('age'), '23');
         $this->assertEquals($subform->getValue('weight'), 80);
         $this->assertNull($subform->getValue('comment'));
         $user = new TestUser();
         FormUtils::form2object($form, $user, false);
         $this->assertEquals($user->getProperties()->getList(), array_filter($properties));
     }
 }
Exemple #14
0
/**
 * Takes raw SDP header and use it to generate a .sdp file describing the RTP stream
 * Primary use is to tell the caller to send RTP data to $dst_ip
 *
 * @param $raw_sdp unparsed sdp header
 * @param $dst_ip ip address to tell the client to send media streams to
 * @param $port specifies lower port number to use. this +3 ports will be allocated
 * @return generated sdp header to use as response for $raw_sdp
 */
function generate_sdp($raw_sdp, $dst_ip, $port)
{
    $sdp_arr = parse_sdp($raw_sdp);
    $ts = new Timestamp();
    //Session description
    $sdp = "v=0\r\n" . "o=- " . $ts->asNTP() . " 0 IN IP4 " . $sdp_arr['ip'] . "\r\n" . "s=core_dev\r\n" . "c=IN IP4 " . $dst_ip . "\r\n" . "t=0 0\r\n";
    //Time active. "0 0" means the session is regarded as permanent
    if (!empty($sdp_arr['video'])) {
        $sdp .= generate_sdp_media_tag(SDP_VIDEO, $sdp_arr['video'], $port);
        $port += 2;
    }
    if (!empty($sdp_arr['audio'])) {
        $sdp .= generate_sdp_media_tag(SDP_AUDIO, $sdp_arr['audio'], $port);
    }
    return $sdp;
}
 /**
  * "associate" mode request
  *
  * @param $server to make association with (usually obtained from OpenIdCredentials)
  * @param $manager - dao-like association manager
  * @return OpenIdConsumerAssociation
  **/
 public function associate(HttpUrl $server, OpenIdConsumerAssociationManager $manager)
 {
     Assert::isTrue($server->isValid());
     if ($association = $manager->findByServer($server)) {
         return $association;
     }
     $dhParameters = new DiffieHellmanParameters($this->numberFactory->makeNumber(self::DIFFIE_HELLMAN_G), $this->numberFactory->makeNumber(self::DIFFIE_HELLMAN_P));
     $keyPair = DiffieHellmanKeyPair::generate($dhParameters, $this->randomSource);
     $request = HttpRequest::create()->setMethod(HttpMethod::post())->setUrl($server)->setPostVar('openid.ns', self::NAMESPACE_2_0)->setPostVar('openid.mode', 'associate')->setPostVar('openid.assoc_type', self::ASSOCIATION_TYPE)->setPostVar('openid.session_type', 'DH-SHA1')->setPostVar('openid.dh_modulus', base64_encode($dhParameters->getModulus()->toBinary()))->setPostVar('openid.dh_gen', base64_encode($dhParameters->getGen()->toBinary()))->setPostVar('openid.dh_consumer_public', base64_encode($keyPair->getPublic()->toBinary()));
     $response = $this->httpClient->setFollowLocation(true)->send($request);
     if ($response->getStatus()->getId() != HttpStatus::CODE_200) {
         throw new OpenIdException('bad response code from server');
     }
     $result = $this->parseKeyValueFormat($response->getBody());
     if (empty($result['assoc_handle'])) {
         throw new OpenIdException('can\\t live without handle');
     }
     if (!isset($result['assoc_type']) || $result['assoc_type'] !== self::ASSOCIATION_TYPE) {
         throw new OpenIdException('bad association type');
     }
     if (!isset($result['expires_in']) || !is_numeric($result['expires_in'])) {
         throw new OpenIdException('bad expires');
     }
     if (isset($result['session_type']) && $result['session_type'] == 'DH-SHA1' && isset($result['dh_server_public'])) {
         $secret = sha1($keyPair->makeSharedKey($this->numberFactory->makeFromBinary(base64_decode($result['dh_server_public'])))->toBinary(), true) ^ base64_decode($result['enc_mac_key']);
     } elseif (empty($result['session_type']) && isset($result['mac_key'])) {
         $secret = base64_decode($result['mac_key']);
     } else {
         throw new OpenIdException('no secret in answer');
     }
     return $manager->makeAndSave($result['assoc_handle'], $result['assoc_type'], $secret, Timestamp::makeNow()->modify('+ ' . $result['expires_in'] . ' seconds'), $server);
 }
 /** 
  * calculates the array to display with the months
  *
  * @private
  */
 function _getMonths()
 {
     $articles = new Articles();
     $archiveStats = $articles->getNumberPostsPerMonthAdmin($this->_blogInfo->getId());
     if (!$archiveStats) {
         return array();
     }
     $result = array();
     $t = new Timestamp();
     $curyear = (int) $t->getYear();
     $curmonth = (int) $t->getMonth();
     $archiveDateFormat = $this->_locale->tr("archive_date_format");
     if ($archiveDateFormat == "archive_date_format") {
         $archiveDateFormat = "%B %Y";
     }
     foreach ($archiveStats as $yearName => $year) {
         foreach ($year as $monthName => $month) {
             // the next bit is so disgustingly ugly that I am ashamed of it...
             // what I'm trying to do here is that the getNumberPostsPerMonthAdmin() method
             // won't return the current month if there wasn't anything posted during it but
             // we still should show the current month even if there's nothing in it, because otherwise
             // when generating page where the posts are listed, it will end up saying "Date: All"
             // but no posts at all shown (it didn't have anything to show) This is a way of
             // "introducing" a month in the array without f*****g it up. In fact, PHP *was*
             // indeed f*****g it up... it didn't just want to keep the order! Oh well, it's a very
             // long and stupid story but we need this hack, ok? :)
             if ($archiveStats[$curyear][$curmonth] == "" && !$alreadyAdded) {
                 // there goes the dirty hack :P
                 if ($yearName == $curyear && $monthName < $curmonth) {
                     $t = new Timestamp();
                     $name = $this->_locale->formatDate($t, $archiveDateFormat);
                     $monthStr = array("name" => $name, "date" => $this->_locale->formatDate($t, "%Y%m"));
                     array_push($result, $monthStr);
                     $alreadyAdded = true;
                 }
             }
             // we can use the Timestamp class to help us with this...
             $t = new Timestamp("");
             $t->setYear($yearName);
             $t->setMonth($monthName);
             $name = $this->_locale->formatDate($t, $archiveDateFormat);
             $monthStr = array("name" => $name, "date" => $this->_locale->formatDate($t, "%Y%m"));
             array_push($result, $monthStr);
         }
     }
     return $result;
 }
 /**
  * @return DateRange
  **/
 public function safeSetEnd($end)
 {
     if (!$this->getStart() || Timestamp::compare($end, $this->getStart()) > 0) {
         $this->setEnd($end);
     } elseif ($this->getStart()) {
         $this->setEnd($this->getStart());
     }
     return $this;
 }
 public function testSleeping()
 {
     $stamp = Timestamp::makeNow();
     $serializedStamp = serialize($stamp);
     $unserializedStamp = unserialize($serializedStamp);
     $this->assertEquals($stamp->getDay(), $unserializedStamp->getDay());
     $this->assertEquals($stamp->getMonth(), $unserializedStamp->getMonth());
     $this->assertEquals($stamp->getYear(), $unserializedStamp->getYear());
     $this->assertEquals($stamp->getMinute(), $unserializedStamp->getMinute());
     $this->assertEquals($stamp->getSecond(), $unserializedStamp->getSecond());
 }
Exemple #19
0
function FAS_Call($type, $name, $title, $url, $content)
{
    $context = Model_Context::getInstance();
    $pool = DBModel::getInstance();
    $blogstr = $context->getProperty('uri.host') . $context->getProperty('uri.blog');
    $DDosTimeWindowSize = 300;
    $rpc = new XMLRPC();
    $rpc->url = 'http://antispam.textcube.org/RPC/';
    if ($rpc->call('checkSpam', $blogstr, $type, $name, $title, $url, $content, $_SERVER['REMOTE_ADDR']) == false) {
        // call fail
        // Do Local spam check with "Thief-cat algorithm"
        $count = 0;
        if ($type == 2) {
            $storage = "RemoteResponses";
            $pool->reset($storage);
            $pool->setQualifier("url", "eq", $url, true);
            $pool->setQualifier("isfiltered", ">", 0);
            if ($cnt = $pool->getCount("id")) {
                $count += $cnt;
            }
        } else {
            // Comment Case
            $storage = "Comments";
            $pool->reset($storage);
            $pool->setQualifier("comment", "eq", ${$content}, true);
            $pool->setQualifier("name", "eq", $name, true);
            $pool->setQualifier("homepage", "eq", $url, true);
            $pool->setQualifier("isfiltered", ">", 0);
            if ($cnt = $pool->getCount("id")) {
                $count += $cnt;
            }
        }
        // Check IP
        $pool->reset($storage);
        $pool->setQualifier("ip", "eq", $_SERVER['REMOTE_ADDR'], true);
        $pool->setQualifier("written", ">", Timestamp::getUNIXtime() - $DDosTimeWindowSize);
        if ($cnt = $pool->getCount("id")) {
            $count += $cnt;
        }
        if ($count >= 10) {
            return false;
        }
        return true;
    }
    if (!is_null($rpc->fault)) {
        // FAS has some problem
        return true;
    }
    if ($rpc->result['result'] == true) {
        return false;
        // it's spam
    }
    return true;
}
 /**
  * Carries out the specified action
  */
 function perform()
 {
     // if we're blocking a single host, then the mask should be
     // as long as 32 bits
     $blockedHosts = new BlockedHosts();
     $t = new Timestamp();
     $blockedHost = new BlockedHost($this->_host, 32, "Host blocked from posting", $t->getTimestamp(), $this->_blogInfo->getId(), BLOCK_COMMENT_POSTING, BLOCK_BLACKLIST);
     $result = $blockedHosts->add($blockedHost);
     // if there was an error, let the user know about it...
     if (!$result) {
         $this->_view = new AdminErrorView($this->_blogInfo);
         $this->_view->setMessage("There was an error adding this host to the list of blocked hosts.");
         $this->setCommonData();
         return false;
     }
     $this->_view = new AdminMessageView($this->_blogInfo);
     $this->_view->setMessage("Host " . $this->_host . " blocked from posting comments successfully.");
     $this->setCommonData();
     // better to return true if everything fine
     return true;
 }
 public function testCount()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $this->getDBCreator()->fillDB();
         $count = TestUser::dao()->getTotalCount();
         $this->assertGreaterThan(1, $count);
         $city = TestCity::create()->setId(1);
         $newUser = TestUser::create()->setCity($city)->setCredentials(Credentials::create()->setNickname('newuser')->setPassword(sha1('newuser')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time()));
         TestUser::dao()->add($newUser);
         $newCount = TestUser::dao()->getTotalCount();
         $this->assertEquals($count + 1, $newCount);
     }
 }
Exemple #22
0
 function page($query = [], $fields = [], $sort = null, $page = 1, $pagesize = 50)
 {
     $query = $this->getQueryByTrashStatus($query);
     if ($page < 1) {
         $page = 1;
     }
     if ($pagesize < 1) {
         $pagesize = 50;
     }
     $skip = ($page - 1) * $pagesize;
     $total = parent::count($query);
     $list = parent::all($query, $fields, $sort, $pagesize, $skip);
     $pagemax = ceil($total / $pagesize);
     return [$list, compact('total', 'page', 'pagesize', 'pagemax')];
 }
Exemple #23
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     if ($this->sampleList === null) {
         $d1 = new Date(2012, 5, 21);
         $d2 = new Datetime(2012, 5, 21, 7, 30);
         $d3 = new Timestamp(2012, 5, 21, 7, 30, 9);
         $d4 = new Date(2012, 3, 7);
         $d5 = new Datetime(2012, 3, 7, 0, 0);
         $d6 = new Timestamp(2012, 3, 7, 0, 0, 0);
         $d7 = Date::now();
         $d8 = Datetime::now()->setAll(array("hour" => 8, "minute" => 6));
         $d9 = Timestamp::now()->setAll(array("hour" => 8, "minute" => 6, "second" => 4));
         $this->sampleList = array(new SimpleFormatTest_Sample("YmdHis", new SimpleFormatTest_ParseData("20120521073009", "2012052112345", $d1, $d2, $d3), new SimpleFormatTest_FormatData($d1, "20120521000000"), new SimpleFormatTest_FormatData($d2, "20120521073000"), new SimpleFormatTest_FormatData($d3, "20120521073009")), new SimpleFormatTest_Sample("Y年n月j日G時f分b秒", new SimpleFormatTest_ParseData("2012年5月21日7時30分9秒", "2012年05月21日07時30分09秒", $d1, $d2, $d3), new SimpleFormatTest_FormatData($d1, "2012年5月21日0時0分0秒"), new SimpleFormatTest_FormatData($d2, "2012年5月21日7時30分0秒"), new SimpleFormatTest_FormatData($d3, "2012年5月21日7時30分9秒")), new SimpleFormatTest_Sample("\\Y=Y \\n=n \\j=j \\H=H \\i=i \\s=s", new SimpleFormatTest_ParseData("Y=2012 n=5 j=21 H=07 i=30 s=09", "Y=2012 n=5 j=21 H=7 i=30 s=9", $d1, $d2, $d3), new SimpleFormatTest_FormatData($d1, "Y=2012 n=5 j=21 H=00 i=00 s=00"), new SimpleFormatTest_FormatData($d2, "Y=2012 n=5 j=21 H=07 i=30 s=00"), new SimpleFormatTest_FormatData($d3, "Y=2012 n=5 j=21 H=07 i=30 s=09")), new SimpleFormatTest_Sample("Y/m/d", new SimpleFormatTest_ParseData("2012/03/07", "2012-03-07", $d4, $d5, $d6), new SimpleFormatTest_FormatData($d1, "2012/05/21"), new SimpleFormatTest_FormatData($d2, "2012/05/21"), new SimpleFormatTest_FormatData($d3, "2012/05/21")), new SimpleFormatTest_Sample("Y.n.j", new SimpleFormatTest_ParseData("2012.3.7", "hogehoge", $d4, $d5, $d6), new SimpleFormatTest_FormatData($d1, "2012.5.21"), new SimpleFormatTest_FormatData($d2, "2012.5.21"), new SimpleFormatTest_FormatData($d3, "2012.5.21")), new SimpleFormatTest_Sample("H:i:s", new SimpleFormatTest_ParseData("08:06:04", "8:06:04", $d7, $d8, $d9), new SimpleFormatTest_FormatData($d1, "00:00:00"), new SimpleFormatTest_FormatData($d2, "07:30:00"), new SimpleFormatTest_FormatData($d3, "07:30:09")), new SimpleFormatTest_Sample("G時f分b秒", new SimpleFormatTest_ParseData("8時6分4秒", "8じ6分4秒", $d7, $d8, $d9), new SimpleFormatTest_FormatData($d1, "0時0分0秒"), new SimpleFormatTest_FormatData($d2, "7時30分0秒"), new SimpleFormatTest_FormatData($d3, "7時30分9秒")), new SimpleFormatTest_Sample("Y年n月j日(E)", new SimpleFormatTest_ParseData("2012年3月7日(水)", "2012年3月7日(無)", $d4, $d5, $d6), new SimpleFormatTest_FormatData($d1, "2012年5月21日(月)"), new SimpleFormatTest_FormatData($d2, "2012年5月21日(月)"), new SimpleFormatTest_FormatData($d3, "2012年5月21日(月)")));
     }
 }
 public function testIpAddressProperty()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $city = TestCity::create()->setName('Khimki');
         TestCity::dao()->add($city);
         $userWithIp = TestUser::create()->setCredentials(Credentials::create()->setNickName('postgreser')->setPassword(sha1('postgreser')))->setLastLogin(Timestamp::makeNow())->setRegistered(Timestamp::makeNow())->setCity($city)->setIp(IpAddress::create('127.0.0.1'));
         TestUser::dao()->add($userWithIp);
         $this->assertTrue($userWithIp->getId() >= 1);
         $this->assertTrue($userWithIp->getIp() instanceof IpAddress);
         $plainIp = DBPool::me()->getByDao(TestUser::dao())->queryColumn(OSQL::select()->get('ip')->from(TestUser::dao()->getTable())->where(Expression::eq('id', $userWithIp->getId())));
         $this->assertEquals($plainIp[0], $userWithIp->getIp()->toString());
         $count = Criteria::create(TestUser::dao())->add(Expression::eq('ip', IpAddress::create('127.0.0.1')))->addProjection(Projection::count('*', 'count'))->getCustom('count');
         $this->assertEquals($count, 1);
     }
 }
 public function makeItems(SimpleXMLElement $xmlFeed)
 {
     $result = array();
     if (isset($xmlFeed->channel->item)) {
         foreach ($xmlFeed->channel->item as $item) {
             $feedItem = FeedItem::create((string) $item->title)->setContent(FeedItemContent::create()->setBody((string) $item->description))->setPublished(Timestamp::create(strtotime((string) $item->pubDate)))->setLink((string) $item->link);
             if (isset($item->guid)) {
                 $feedItem->setId($item->guid);
             }
             if (isset($item->category)) {
                 $feedItem->setCategory((string) $item->category);
             }
             $result[] = $feedItem;
         }
     }
     return $result;
 }
 public function makeItems(SimpleXMLElement $xmlFeed)
 {
     $result = array();
     foreach ($xmlFeed->entry as $entry) {
         $feedItem = FeedItem::create((string) $entry->title);
         if (isset($entry->content)) {
             $feedItem->setContent($this->makeFeedItemContent($entry->content));
         }
         if (isset($entry->summary)) {
             $feedItem->setSummary($this->makeFeedItemContent($entry->summary));
         }
         if (isset($entry->id)) {
             $feedItem->setId($entry->id);
         }
         $result[] = $feedItem->setPublished(Timestamp::create(strtotime((string) $entry->updated)))->setLink((string) $entry->link);
     }
     return $result;
 }
 function render()
 {
     // fetch the categories
     $categories = new ArticleCategories();
     $blogSettings = $this->_blogInfo->getSettings();
     $categoriesOrder = $blogSettings->getValue("categories_order");
     $blogCategories = $categories->getBlogCategories($this->_blogInfo->getId(), false, $categoriesOrder);
     // get some stuff for the time stamp of the post, which is changeable now
     //$t = new Timestamp();
     $t = Timestamp::getBlogDate($this->_blogInfo);
     //$t->toUTC();
     //
     // changes to make plog store its dates with the time difference already
     // applied, instead of applying it dynamically
     //
     $config =& Config::getConfig();
     /*if( $config->getValue( "time_difference_calculation" == TIME_DIFFERENCE_CALCULATION_STATIC ) {
     		$blogSettings = $this->_blogInfo->getSettings();
     		$difference = $blogSettings->getValue( "time_offset" );
               	$t->setDate( Timestamp::getDateWithOffset( $t->getDate(), $difference ), DATE_FORMAT_TIMESTAMP );
           	}*/
     // fetch the custom fields, if any, but not including the ones that have been set to "hidden"...
     $customFields = new CustomFields();
     $blogFields = $customFields->getBlogCustomFields($this->_blogInfo->getId(), false);
     // and put everything in the template
     $locale = $this->_blogInfo->getLocale();
     $this->setValue("commentsEnabled", $blogSettings->getValue("comments_enabled"));
     $this->setValue("categories", $blogCategories);
     $this->setValue("today", $t);
     $this->setValue("months", $locale->getMonthNames());
     $this->setValue("days", $locale->getDayNamesShort());
     $this->setValue("years", Timestamp::getYears());
     $this->setValue("hours", Timestamp::getAllHours());
     $this->setValue("minutes", Timestamp::getAllMinutes());
     $this->setValue("customfields", $blogFields);
     $this->setValue("poststatus", ArticleStatus::getStatusList());
     $this->setValue("sendPings", $config->getValue("send_xmlrpc_pings_enabled_by_default", true));
     $this->setValue("xmlRpcPingEnabled", $config->getValue("xmlrpc_ping_enabled", false));
     $this->setValue("autoSaveNewDraftsTimeMillis", $config->getValue("autosave_new_drafts_time_millis"));
     $this->setValue("xmlHttpRequestSupportEnabled", $config->getValue("save_drafts_via_xmlhttprequest_enabled"));
     $this->setValue("postDateTime", $t->getDay() . "/" . $t->getMonth() . "/" . $t->getYear() . " " . $t->getHour() . ":" . $t->getMinutes());
     parent::render();
 }
Exemple #28
0
function RecentRP_getRecentCommentsView($comments, $template)
{
    global $contentContainer;
    $context = Model_Context::getInstance();
    ob_start();
    foreach ($comments as $comment) {
        $view = "{$template}";
        Utils_Misc::dress('rctrp_rep_link', $context->getProperty('uri.blog') . "/{$comment['entry']}#comment{$comment['id']}", $view);
        $contentContainer["recent_comment_{$comment['id']}"] = htmlspecialchars(Utils_Unicode::lessenAsEm(strip_tags($comment['comment']), 30));
        Utils_Misc::dress('rctrp_rep_desc', setTempTag("recent_comment_{$comment['id']}"), $view);
        Utils_Misc::dress('rctrp_rep_desc', htmlspecialchars(Utils_Unicode::lessenAsEm(strip_tags($comment['comment']), 30)), $view);
        Utils_Misc::dress('rctrp_rep_time', fireEvent('ViewRecentCommentDate', Timestamp::format3($comment['written'])), $view);
        Utils_Misc::dress('rctrp_rep_name', htmlspecialchars(Utils_Unicode::lessenAsEm(strip_tags($comment['name']), 10)) . $comment['secret'] . $comment['replier'], $view);
        print $view;
    }
    $view = ob_get_contents();
    ob_end_clean();
    return $view;
}
 public function makeItems(SimpleXMLElement $xmlFeed)
 {
     $xmlFeed->registerXPathNamespace(YandexRssFeedFormat::YANDEX_NAMESPACE_PREFIX, YandexRssFeedFormat::YANDEX_NAMESPACE_URI);
     $fullTextList = $xmlFeed->xpath('//' . YandexRssFeedFormat::YANDEX_NAMESPACE_PREFIX . ':full-text');
     $result = array();
     $i = 0;
     if (isset($xmlFeed->channel->item)) {
         foreach ($xmlFeed->channel->item as $item) {
             $feedItem = YandexRssFeedItem::create((string) $item->title)->setContent(FeedItemContent::create()->setBody((string) $item->description))->setPublished(Timestamp::create(strtotime((string) $item->pubDate)))->setFullText((string) $fullTextList[$i++])->setLink((string) $item->link);
             if (isset($item->guid)) {
                 $feedItem->setId($item->guid);
             }
             if (isset($item->category)) {
                 $feedItem->setCategory((string) $item->category);
             }
             $result[] = $feedItem;
         }
     }
     return $result;
 }
 /**
  * @return Message
  **/
 public function receive($uTimeout = null)
 {
     if (!$this->queue) {
         throw new WrongStateException('you must set the queue first');
     }
     if ($uTimeout && $this->getStream()->isEof()) {
         usleep($uTimeout);
     }
     $string = $this->getStream()->readString();
     if (!$string && $this->getStream()->isEof()) {
         return null;
     }
     $this->getQueue()->setOffset($this->getStream()->getOffset());
     $string = rtrim($string, PHP_EOL);
     $chunks = preg_split("/\t/", $string, 2);
     $time = isset($chunks[0]) ? $chunks[0] : null;
     $text = isset($chunks[1]) ? $chunks[1] : null;
     Assert::isNotNull($time);
     $result = TextMessage::create(Timestamp::create($time))->setText($text);
     return $result;
 }