Example #1
1
 /**
  * Truncates a string to the given length.  It will optionally preserve
  * HTML tags if $is_html is set to true.
  *
  * @param   string  $string        the string to truncate
  * @param   int     $limit         the number of characters to truncate too
  * @param   string  $continuation  the string to use to denote it was truncated
  * @param   bool    $is_html       whether the string has HTML
  * @return  string  the truncated string
  */
 public static function truncate($string, $limit, $continuation = '...', $is_html = false)
 {
     $offset = 0;
     $tags = array();
     if ($is_html) {
         // Handle special characters.
         preg_match_all('/&[a-z]+;/i', strip_tags($string), $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
         foreach ($matches as $match) {
             if ($match[0][1] >= $limit) {
                 break;
             }
             $limit += static::length($match[0][0]) - 1;
         }
         // Handle all the html tags.
         preg_match_all('/<[^>]+>([^<]*)/', $string, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
         foreach ($matches as $match) {
             if ($match[0][1] - $offset >= $limit) {
                 break;
             }
             $tag = static::sub(strtok($match[0][0], " \t\n\r\v>"), 1);
             if ($tag[0] != '/') {
                 $tags[] = $tag;
             } elseif (end($tags) == static::sub($tag, 1)) {
                 array_pop($tags);
             }
             $offset += $match[1][1] - $match[0][1];
         }
     }
     $new_string = static::sub($string, 0, $limit = min(static::length($string), $limit + $offset));
     $new_string .= static::length($string) > $limit ? $continuation : '';
     $new_string .= count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '';
     return $new_string;
 }
Example #2
1
 /**
  * @brief Accion que se encarga de manipular el proceso de guardar
  * un archivo en el servidor
  * @param array $allowedExtensions Arreglo de extensiones validas para el archivo
  * @param int $sizeLimit Tamaño maximo permitido del fichero que se sube
  */
 function upload($allowedExtensions, $sizeLimit = 10485760)
 {
     jimport('Amadeus.Util.Uploader');
     $media =& JComponentHelper::getParams('com_media');
     $postSize = $this->toBytes(ini_get('post_max_size'));
     $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
     $mediaSize = (int) $media->get('upload_maxsize');
     // Se selecciona el minimo tamaño válido para un fichero, de acuerdo
     // a los valores configurados en el php, el joomla y el componente.
     $sizeLimit = min($postSize, $uploadSize, $mediaSize, $sizeLimit);
     // Se alamacena la imagen en la ruta especificada
     $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
     $result = $uploader->handleUpload(JPATH_SITE . '/tmp/', true);
     if (!isset($result['error'])) {
         jimport('Amadeus.Util.Validation');
         $file = $uploader->getName();
         $result = AmadeusUtilValidation::isValidFile($file, $only_image);
         if (isset($result['error'])) {
             jimport('joomla.filesystem.file');
             if (!JFile::delete($file)) {
                 $result = array('error' => JText::_('DELETEERROR'));
             }
         } else {
             $this->_file = $file;
         }
     }
     return $result;
 }
Example #3
1
 /**
  * Get human readable file size, quick and dirty.
  * 
  * @todo Improve i18n support.
  *
  * @param int $bytes
  * @param string $format
  * @param int|null $decimal_places
  * @return string Human readable string with file size.
  */
 public static function humanReadableBytes($bytes, $format = "en", $decimal_places = null)
 {
     switch ($format) {
         case "sv":
             $dec_separator = ",";
             $thousands_separator = " ";
             break;
         default:
         case "en":
             $dec_separator = ".";
             $thousands_separator = ",";
             break;
     }
     $b = (int) $bytes;
     $s = array('B', 'kB', 'MB', 'GB', 'TB');
     if ($b <= 0) {
         return "0 " . $s[0];
     }
     $con = 1024;
     $e = (int) log($b, $con);
     $e = min($e, count($s) - 1);
     $v = $b / pow($con, $e);
     if ($decimal_places === null) {
         $decimal_places = max(0, 2 - (int) log($v, 10));
     }
     return number_format($v, !$e ? 0 : $decimal_places, $dec_separator, $thousands_separator) . ' ' . $s[$e];
 }
 /**
  * {@inheritdoc}
  */
 protected function transfer()
 {
     while (!$this->stopped && !$this->source->isConsumed()) {
         if ($this->source->getContentLength() && $this->source->isSeekable()) {
             // If the stream is seekable and the Content-Length known, then stream from the data source
             $body = new ReadLimitEntityBody($this->source, $this->partSize, $this->source->ftell());
         } else {
             // We need to read the data source into a temporary buffer before streaming
             $body = EntityBody::factory();
             while ($body->getContentLength() < $this->partSize && $body->write($this->source->read(max(1, min(10 * Size::KB, $this->partSize - $body->getContentLength()))))) {
             }
         }
         // @codeCoverageIgnoreStart
         if ($body->getContentLength() == 0) {
             break;
         }
         // @codeCoverageIgnoreEnd
         $params = $this->state->getUploadId()->toParams();
         $command = $this->client->getCommand('UploadPart', array_replace($params, array('PartNumber' => count($this->state) + 1, 'Body' => $body, 'ContentMD5' => (bool) $this->options['part_md5'], Ua::OPTION => Ua::MULTIPART_UPLOAD)));
         // Notify observers that the part is about to be uploaded
         $eventData = $this->getEventData();
         $eventData['command'] = $command;
         $this->dispatch(self::BEFORE_PART_UPLOAD, $eventData);
         // Allow listeners to stop the transfer if needed
         if ($this->stopped) {
             break;
         }
         $response = $command->getResponse();
         $this->state->addPart(UploadPart::fromArray(array('PartNumber' => count($this->state) + 1, 'ETag' => $response->getHeader('ETag', true), 'Size' => $body->getContentLength(), 'LastModified' => gmdate(DateFormat::RFC2822))));
         // Notify observers that the part was uploaded
         $this->dispatch(self::AFTER_PART_UPLOAD, $eventData);
     }
 }
/**
 * Smarty truncate modifier plugin
 * Type:     modifier<br>
 * Name:     truncate<br>
 * Purpose:  Truncate a string to a certain length if necessary,
 *               optionally splitting in the middle of a word, and
 *               appending the $etc string or inserting $etc into the middle.
 *
 * @link   http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
 * @author Monte Ohrt <monte at ohrt dot com>
 *
 * @param string  $string      input string
 * @param integer $length      length of truncated text
 * @param string  $etc         end string
 * @param boolean $break_words truncate at word boundary
 * @param boolean $middle      truncate in the middle of text
 *
 * @return string truncated string
 */
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
    if ($length == 0) {
        return '';
    }
    if (Smarty::$_MBSTRING) {
        if (mb_strlen($string, Smarty::$_CHARSET) > $length) {
            $length -= min($length, mb_strlen($etc, Smarty::$_CHARSET));
            if (!$break_words && !$middle) {
                $string = preg_replace('/\\s+?(\\S+)?$/' . Smarty::$_UTF8_MODIFIER, '', mb_substr($string, 0, $length + 1, Smarty::$_CHARSET));
            }
            if (!$middle) {
                return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc;
            }
            return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc . mb_substr($string, -$length / 2, $length, Smarty::$_CHARSET);
        }
        return $string;
    }
    // no MBString fallback
    if (isset($string[$length])) {
        $length -= min($length, strlen($etc));
        if (!$break_words && !$middle) {
            $string = preg_replace('/\\s+?(\\S+)?$/', '', substr($string, 0, $length + 1));
        }
        if (!$middle) {
            return substr($string, 0, $length) . $etc;
        }
        return substr($string, 0, $length / 2) . $etc . substr($string, -$length / 2);
    }
    return $string;
}
Example #6
0
 function do_main()
 {
     $notifications = (array) KTNotification::getList(array("user_id = ?", $this->oUser->getId()));
     $num_notifications = count($notifications);
     $PAGE_SIZE = 5;
     $page = (int) KTUtil::arrayGet($_REQUEST, 'page', 0);
     $page_count = ceil($num_notifications / $PAGE_SIZE);
     if ($page >= $page_count) {
         $page = $page_count - 1;
     }
     if ($page < 0) {
         $page = 0;
     }
     // slice the notification array.
     $notifications = array_slice($notifications, $page * $PAGE_SIZE, $PAGE_SIZE);
     // prepare the batch html.  easier to do this here than in the template.
     $batch = array();
     for ($i = 0; $i < $page_count; $i++) {
         if ($i == $page) {
             $batch[] = sprintf("<strong>%d</strong>", $i + 1);
         } else {
             $batch[] = sprintf('<a href="%s">%d</a>', KTUtil::addQueryStringSelf($this->meldPersistQuery(array("page" => $i), "main", true)), $i + 1);
         }
     }
     $batch_html = implode(' &middot; ', $batch);
     $count_string = sprintf(_kt("Showing Notifications %d - %d of %d"), $page * $PAGE_SIZE + 1, min(($page + 1) * $PAGE_SIZE, $num_notifications), $num_notifications);
     $this->oPage->setTitle(_kt("Items that require your attention"));
     $oTemplate =& $this->oValidator->validateTemplate("ktcore/misc/notification_overflow");
     $oTemplate->setData(array('count_string' => $count_string, 'batch_html' => $batch_html, 'notifications' => $notifications));
     return $oTemplate->render();
 }
Example #7
0
 /**
  * Uploads file to FTP server.
  * @return void
  */
 public function writeFile($local, $remote, callable $progress = NULL)
 {
     $size = max(filesize($local), 1);
     $retry = self::RETRIES;
     upload:
     $blocks = 0;
     do {
         if ($progress) {
             $progress(min($blocks * self::BLOCK_SIZE / $size, 100));
         }
         try {
             $ret = $blocks === 0 ? $this->ftp('nb_put', $remote, $local, FTP_BINARY) : $this->ftp('nb_continue');
         } catch (FtpException $e) {
             @ftp_close($this->connection);
             // intentionally @
             $this->connect();
             if (--$retry) {
                 goto upload;
             }
             throw new FtpException("Cannot upload file {$local}, number of retries exceeded. Error: {$e->getMessage()}");
         }
         $blocks++;
     } while ($ret === FTP_MOREDATA);
     if ($progress) {
         $progress(100);
     }
 }
 /**
  * Render the information header for the view
  * 
  * @param string $title
  * @param string $title
  */
 public function writeInfo($title, $subtitle, $description = false)
 {
     echo wordwrap(strtoupper($title), 100) . "\n";
     echo wordwrap($subtitle, 100) . "\n";
     echo str_repeat('-', min(100, max(strlen($title), strlen($subtitle)))) . "\n";
     echo wordwrap($description, 100) . "\n\n";
 }
 public function formatColor(\OttawaDeveloper\Tools\ColorAnalyzer\Color $color)
 {
     $colorValues = array('red' => $color->red() / 255, 'green' => $color->green() / 255, 'blue' => $color->blue() / 255);
     $minimumValue = min($colorValues);
     $maximumValue = max($colorValues);
     $luminescence = round(($minimumValue + $maximumValue) / 2, 2);
     if ($minimumValue == $maximumValue) {
         return $this->formatHslColor(0, 0, $luminescence, $color->alpha());
     }
     $colorRange = $maximumValue - $minimumValue;
     $saturation = $colorRange;
     if ($luminescence < 0.5) {
         $saturation /= $maximumValue + $minimumValue;
     } else {
         $saturation /= 2 - $colorRange;
     }
     $hue = 0;
     if ($colorValues['red'] >= $colorValues['blue'] && $colorValues['red'] >= $colorValues['green']) {
         $hue = ($colorValues['green'] - $colorValues['blue']) / $colorRange;
     } elseif ($colorValues['green'] >= $colorValues['blue'] && $colorValues['green'] >= $colorValues['red']) {
         $hue = 2 + ($colorValues['blue'] - $colorValues['red']) / $colorRange;
     } else {
         $hue = 4 + ($colorValues['red'] - $colorValues['green']) / $colorRange;
     }
     return $this->formatHslColor($hue * 60, $saturation, $luminescence, $color->alpha());
 }
 /**
  * Returns "..." in place of common prefix and "..." in
  * place of common suffix between expected and actual.
  *
  * @return string
  * @access public
  */
 public function toString()
 {
     $end = min(strlen($this->expected), strlen($this->actual));
     $i = 0;
     $j = strlen($this->expected) - 1;
     $k = strlen($this->actual) - 1;
     for (; $i < $end; $i++) {
         if ($this->expected[$i] != $this->actual[$i]) {
             break;
         }
     }
     for (; $k >= $i && $j >= $i; $k--, $j--) {
         if ($this->expected[$j] != $this->actual[$k]) {
             break;
         }
     }
     if ($j < $i && $k < $i) {
         $expected = $this->expected;
         $actual = $this->actual;
     } else {
         $expected = substr($this->expected, $i, $j + 1 - $i);
         $actual = substr($this->actual, $i, $k + 1 - $i);
         if ($i <= $end && $i > 0) {
             $expected = '...' . $expected;
             $actual = '...' . $actual;
         }
         if ($j < strlen($this->expected) - 1) {
             $expected .= '...';
         }
         if ($k < strlen($this->actual) - 1) {
             $actual .= '...';
         }
     }
     return PHPUnit2_Framework_Assert::format($expected, $actual, parent::getMessage());
 }
Example #11
0
function nuage_tags($limit = 30, $id_cat = 0)
{
    $list_tags = array();
    $count_tags = array();
    $limit_sql = $limit != 0 ? ' LIMIT ' . intval($limit) : '';
    $where_cat = $id_cat != 0 ? ' AND n_id_cat = ' . intval($id_cat) : '';
    $rqt_tags = Nw::$DB->query('SELECT c_id, c_couleur, c_nom, t_id_news, t_tag, COUNT(t_tag) AS nbr_tags, n_id_cat FROM ' . Nw::$prefix_table . 'tags
        LEFT JOIN ' . Nw::$prefix_table . 'news ON t_id_news = n_id
        LEFT JOIN ' . Nw::$prefix_table . 'categories ON c_id = n_id_cat
    WHERE n_etat = 3' . $where_cat . '
    GROUP BY t_tag ORDER BY t_tag ASC ' . $limit_sql) or Nw::$DB->trigger(__LINE__, __FILE__);
    while ($donnees = $rqt_tags->fetch_assoc()) {
        $list_tags[$donnees['t_tag']] = $donnees;
        $count_tags[$donnees['t_tag']] = $donnees['nbr_tags'];
    }
    $max_size = 200;
    $min_size = 100;
    $max_qty = 0;
    $min_qty = 0;
    if (count($count_tags) > 0) {
        $max_qty = max(array_values($count_tags));
        $min_qty = min(array_values($count_tags));
    }
    $spread = $max_qty - $min_qty;
    if (0 == $spread) {
        $spread = 1;
    }
    $step = ($max_size - $min_size) / $spread;
    foreach ($list_tags as $tags) {
        $list_tags[$tags['t_tag']]['size'] = floor($min_size + ($tags['nbr_tags'] - $min_qty) * $step);
    }
    return $list_tags;
}
 /**
  * Migrate records of a single class
  *
  * @param string $class
  * @param null|string $stage
  */
 protected function upClass($class)
 {
     if (!class_exists($class)) {
         return;
     }
     if (is_subclass_of($class, 'SiteTree')) {
         $items = SiteTree::get()->filter('ClassName', $class);
     } else {
         $items = $class::get();
     }
     if ($count = $items->count()) {
         $this->message(sprintf('Migrating %s legacy %s records.', $count, $class));
         foreach ($items as $item) {
             $cancel = $item->extend('onBeforeUp');
             if ($cancel && min($cancel) === false) {
                 continue;
             }
             /**
              * @var MigratableObject $item
              */
             $result = $item->up();
             $this->message($result);
             $item->extend('onAfterUp');
         }
     }
 }
Example #13
0
 public function execute(array $deferred, array $data, $targetRunTime, &$status)
 {
     $data = array_merge(array('position' => 0, 'batch' => 100, 'delete' => false), $data);
     $data['batch'] = max(1, $data['batch']);
     /* @var $statsModel XenForo_Model_Stats */
     $statsModel = XenForo_Model::create('XenForo_Model_Stats');
     if ($data['position'] == 0) {
         // delete old stats cache if required
         if (!empty($data['delete'])) {
             $statsModel->deleteStats();
         }
         // an appropriate date from which to start... first thread, or earliest user reg?
         $data['position'] = min(XenForo_Model::create('XenForo_Model_Thread')->getEarliestThreadDate(), XenForo_Model::create('XenForo_Model_User')->getEarliestRegistrationDate());
         // start on a 24 hour increment point
         $data['position'] = $data['position'] - $data['position'] % 86400;
     } else {
         if ($data['position'] > XenForo_Application::$time) {
             return true;
         }
     }
     $endPosition = $data['position'] + $data['batch'] * 86400;
     $statsModel->buildStatsData($data['position'], $endPosition);
     $data['position'] = $endPosition;
     $actionPhrase = new XenForo_Phrase('rebuilding');
     $typePhrase = new XenForo_Phrase('daily_statistics');
     $status = sprintf('%s... %s (%s)', $actionPhrase, $typePhrase, XenForo_Locale::date($data['position'], 'absolute'));
     return $data;
 }
Example #14
0
function getTweets($notification)
{
    $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $date = $notification['date'];
    $keywords = array("sirene", "gevaar", "ongeluk", "ambulance", "ziekenwagen", "ongeval", "gewond", "letsel", "brand", "vlam", "vuur", "brandweer", "blus", "water", "overval", "politie", "dief", "wapen", "letsel", "inbraak", "schiet", "misdrijf");
    $start_date = "since:" . date(DATE_FORMAT, $date);
    $end_date = "until:" . date(DATE_FORMAT, strtotime("+1 day", $date));
    //$search_string = $notification['town'] . " " . implode(" OR ", $keywords) . " -p2000 " . $start_date . " " . $end_date;
    $search_string = implode(" OR ", KEYWORDS_GEN) . " -p2000 -RT " . $start_date . " " . $end_date;
    $cur_min = min(100, $notification["num_tweets"]);
    $params = array('q' => $search_string, 'lang' => 'nl', 'count' => $cur_min);
    //$statuses = json_encode((array)$twitter->get("search/tweets", $params));
    $temp = (array) $twitter->get("search/tweets", $params);
    $statuses = $temp["statuses"];
    $total_num = count($statuses);
    $num_stat = count($statuses);
    $min_id = $statuses[$num_stat - 1]->id;
    while ($total_num < $notification["num_tweets"] && $num_stat >= $cur_min) {
        $cur_min = min($notification["num_tweets"] - $total_num, 100);
        $params = array('q' => $search_string, 'lang' => 'nl', 'count' => $cur_min, 'max_id' => $min_id);
        $new_temp = (array) $twitter->get("search/tweets", $params);
        $new_stat = $new_temp["statuses"];
        $num_stat = count($new_stat);
        $total_num = $total_num + $num_stat;
        $min_id = $new_stat[$num_stat - 1]->id;
        $statuses = array_merge($statuses, $new_stat);
    }
    //What do I do with the statuses?
    return json_encode($statuses);
}
Example #15
0
 function Get($rss_url, $rss_feed_id)
 {
     $output = '';
     if (!isset($this->num_results)) {
         $this->num_results = 5;
     }
     if (!isset($this->description)) {
         $this->description = FALSE;
     }
     $result = $this->Parse($rss_url);
     if ($result && $result['items_count'] == 0) {
         return null;
     } else {
         if ($result) {
             $output = "<ul class='rss_feed'>";
             for ($i = 0; $i < min($this->num_results, $result['items_count']); $i++) {
                 $output .= "<li><a href='" . $result['items'][$i]['link'] . "' target='_new'>" . $result['items'][$i]['title'] . "</a>";
                 if ($this->description) {
                     $output .= "<br />" . $result['items'][$i]['description'];
                 }
                 $output .= "</li>\n";
             }
             $output .= "</ul>\n";
         } elseif (file_exists($cache_file)) {
             touch($cache_file);
         } else {
             //create an empty file
             if ($f = @fopen($cache_file, 'w')) {
                 fclose($f);
             }
         }
     }
     return $output;
 }
Example #16
0
/**
 * Format a relative time (duration) into weeks, days, hours, minutes,
 * seconds, but unlike phabricator_format_relative_time, does so for more than
 * just the largest unit.
 *
 * @param int Duration in seconds.
 * @param int Levels to render - will render the three highest levels, ie:
 *            5 h, 37 m, 1 s
 * @return string Human-readable description.
 */
function phutil_format_relative_time_detailed($duration, $levels = 2)
{
    if ($duration == 0) {
        return 'now';
    }
    $levels = max(1, min($levels, 5));
    $remainder = 0;
    $is_negative = false;
    if ($duration < 0) {
        $is_negative = true;
        $duration = abs($duration);
    }
    $this_level = 1;
    $detailed_relative_time = phutil_format_units_generic($duration, array(60, 60, 24, 7), array('s', 'm', 'h', 'd', 'w'), $precision = 0, $remainder);
    $duration = $remainder;
    while ($remainder > 0 && $this_level < $levels) {
        $detailed_relative_time .= ', ' . phutil_format_units_generic($duration, array(60, 60, 24, 7), array('s', 'm', 'h', 'd', 'w'), $precision = 0, $remainder);
        $duration = $remainder;
        $this_level++;
    }
    if ($is_negative) {
        $detailed_relative_time .= ' ago';
    }
    return $detailed_relative_time;
}
 public function __construct()
 {
     global $cookie;
     $this->className = 'Configuration';
     $this->table = 'configuration';
     $max_upload = (int) ini_get('upload_max_filesize');
     $max_post = (int) ini_get('post_max_size');
     $upload_mb = min($max_upload, $max_post);
     $timezones = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT name FROM ' . _DB_PREFIX_ . 'timezone');
     $taxes[] = array('id' => 0, 'name' => $this->l('None'));
     foreach (Tax::getTaxes((int) $cookie->id_lang) as $tax) {
         $taxes[] = array('id' => $tax['id_tax'], 'name' => $tax['name']);
     }
     $order_process_type = array(array('value' => PS_ORDER_PROCESS_STANDARD, 'name' => $this->l('Standard (5 steps)')), array('value' => PS_ORDER_PROCESS_OPC, 'name' => $this->l('One page checkout')));
     $round_mode = array(array('value' => PS_ROUND_UP, 'name' => $this->l('superior')), array('value' => PS_ROUND_DOWN, 'name' => $this->l('inferior')), array('value' => PS_ROUND_HALF, 'name' => $this->l('classical')));
     $cms_tab = array(0 => array('id' => 0, 'name' => $this->l('None')));
     foreach (CMS::listCms($cookie->id_lang) as $cms_file) {
         $cms_tab[] = array('id' => $cms_file['id_cms'], 'name' => $cms_file['meta_title']);
     }
     $this->_fieldsGeneral = array('PS_SHOP_ENABLE' => array('title' => $this->l('Enable Shop'), 'desc' => $this->l('Activate or deactivate your shop. Deactivate your shop while you perform maintenance on it. Please note that the webservice will not be disabled'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_MAINTENANCE_IP' => array('title' => $this->l('Maintenance IP'), 'desc' => $this->l('IP addresses allowed to access the Front Office even if shop is disabled. Use a comma to separate them (e.g., 42.24.4.2,127.0.0.1,99.98.97.96)'), 'validation' => 'isGenericName', 'type' => 'maintenance_ip', 'size' => 30, 'default' => ''), 'PS_SSL_ENABLED' => array('title' => $this->l('Enable SSL'), 'desc' => $this->l('If your hosting provider allows SSL, you can activate SSL encryption (https://) for customer account identification and order processing'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'default' => '0'), 'PS_COOKIE_CHECKIP' => array('title' => $this->l('Check IP on the cookie'), 'desc' => $this->l('Check the IP address of the cookie in order to avoid your cookie being stolen'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'default' => '0'), 'PS_COOKIE_LIFETIME_FO' => array('title' => $this->l('Lifetime of the Front Office cookie'), 'desc' => $this->l('Indicate the number of hours'), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'text', 'default' => '480'), 'PS_COOKIE_LIFETIME_BO' => array('title' => $this->l('Lifetime of the Back Office cookie'), 'desc' => $this->l('Indicate the number of hours'), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'text', 'default' => '480'), 'PS_TOKEN_ENABLE' => array('title' => $this->l('Increase Front Office security'), 'desc' => $this->l('Enable or disable token on the Front Office in order to improve PrestaShop security'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'default' => '0'), 'PS_HELPBOX' => array('title' => $this->l('Back Office help boxes'), 'desc' => $this->l('Enable yellow help boxes which are displayed under form fields in the Back Office'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_ORDER_PROCESS_TYPE' => array('title' => $this->l('Order process type'), 'desc' => $this->l('You can choose the order process type as either standard (5 steps) or One Page Checkout'), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'select', 'list' => $order_process_type, 'identifier' => 'value'), 'PS_GUEST_CHECKOUT_ENABLED' => array('title' => $this->l('Enable guest checkout'), 'desc' => $this->l('Your guest can make an order without registering'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_CONDITIONS' => array('title' => $this->l('Terms of service'), 'desc' => $this->l('Require customers to accept or decline terms of service before processing the order'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', 'js' => array('on' => 'onchange="changeCMSActivationAuthorization()"', 'off' => 'onchange="changeCMSActivationAuthorization()"')), 'PS_CONDITIONS_CMS_ID' => array('title' => $this->l('Conditions of use of CMS page'), 'desc' => $this->l('Choose the Conditions of use of CMS page'), 'validation' => 'isInt', 'type' => 'select', 'list' => $cms_tab, 'identifier' => 'id', 'cast' => 'intval'), 'PS_GIFT_WRAPPING' => array('title' => $this->l('Offer gift-wrapping'), 'desc' => $this->l('Suggest gift-wrapping to customer and possibility of leaving a message'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_GIFT_WRAPPING_PRICE' => array('title' => $this->l('Gift-wrap pricing'), 'desc' => $this->l('Set a price for gift-wrapping'), 'validation' => 'isPrice', 'cast' => 'floatval', 'type' => 'price'), 'PS_GIFT_WRAPPING_TAX' => array('title' => $this->l('Gift-wrapping tax'), 'desc' => $this->l('Set a tax for gift-wrapping'), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'select', 'list' => $taxes, 'identifier' => 'id'), 'PS_ATTACHMENT_MAXIMUM_SIZE' => array('title' => $this->l('Maximum attachment size'), 'desc' => $this->l('Set the maximum size of attached files (in Megabytes ).') . ' ' . $this->l('Maximum:') . ' ' . ((int) str_replace('M', '', ini_get('post_max_size')) > (int) str_replace('M', '', ini_get('upload_max_filesize')) ? ini_get('upload_max_filesize') : ini_get('post_max_size')), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'text', 'default' => '2'), 'PS_RECYCLABLE_PACK' => array('title' => $this->l('Offer recycled packaging'), 'desc' => $this->l('Suggest recycled packaging to customer'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_CART_FOLLOWING' => array('title' => $this->l('Save cart content and re-display it at login'), 'desc' => $this->l('Recall and display contents of shopping cart following customer login'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_PRICE_ROUND_MODE' => array('title' => $this->l('Round mode'), 'desc' => $this->l('You can choose how to round prices: always round superior; always round inferior, or classic rounding'), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'select', 'list' => $round_mode, 'identifier' => 'value'), 'PRESTASTORE_LIVE' => array('title' => $this->l('Automatically check for module updates'), 'desc' => $this->l('New modules and updates are displayed on the modules page'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_HIDE_OPTIMIZATION_TIPS' => array('title' => $this->l('Hide optimization tips'), 'desc' => $this->l('Hide optimization tips on the back office homepage'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_DISPLAY_SUPPLIERS' => array('title' => $this->l('Display suppliers and manufacturers'), 'desc' => $this->l('Display manufacturers and suppliers list even if corresponding blocks are disabled'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_FORCE_SMARTY_2' => array('title' => $this->l('Use Smarty 2 instead of 3'), 'desc' => $this->l('Enable if your theme is incompatible with Smarty 3 (you should update your theme, since Smarty 2 will be unsupported from PrestaShop v1.5)'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool'), 'PS_LIMIT_UPLOAD_FILE_VALUE' => array('title' => $this->l('Limit upload file value'), 'desc' => $this->l('Define the limit upload for a downloadable product, this value has to be inferior or equal to your server\'s maximum upload file ') . sprintf('(%s MB).', $upload_mb), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'limit', 'default' => '1'), 'PS_LIMIT_UPLOAD_IMAGE_VALUE' => array('title' => $this->l('Limit upload image value'), 'desc' => $this->l('Define the limit upload for an image, this value has to be inferior or equal to your server\'s maximum upload file ') . sprintf('(%s MB).', $upload_mb), 'validation' => 'isInt', 'cast' => 'intval', 'type' => 'limit', 'default' => '1'));
     if (function_exists('date_default_timezone_set')) {
         $this->_fieldsGeneral['PS_TIMEZONE'] = array('title' => $this->l('Time Zone:'), 'validation' => 'isAnything', 'type' => 'select', 'list' => $timezones, 'identifier' => 'name');
     }
     // No HTTPS activation if you haven't already.
     if (!Tools::usingSecureMode() && !_PS_SSL_ENABLED_) {
         $this->_fieldsGeneral['PS_SSL_ENABLED']['type'] = 'disabled';
         $this->_fieldsGeneral['PS_SSL_ENABLED']['disabled'] = '<a href="https://' . Tools::getShopDomainSsl() . Tools::safeOutput($_SERVER['REQUEST_URI']) . '">' . $this->l('Please click here to use HTTPS protocol before enabling SSL.') . '</a>';
     }
     parent::__construct();
 }
 public function calculateLegCount($tprefix, $id, $father_id, $child_position, $from_id = '')
 {
     $obj_arr = $this->getConfigurationEntries($tprefix);
     $pair_price = $obj_arr["pair_price"];
     $ceiling_user = $obj_arr['pair_ceiling'];
     $tds_db = $obj_arr["tds"];
     $service_charge_db = $obj_arr["service_charge"];
     $week_start_date_db = $obj_arr["startDate"];
     $week_end_date_db = $obj_arr["endDate"];
     $payout_release = $obj_arr["payout_release"];
     if ($payout_release == "month") {
         $current_date = date("Y-m-d");
         $month_arr = $this->getCurrentMonthStartEndDates($tprefix, $current_date);
         $from_date = $month_arr["month_first_date"];
         $to_date = $month_arr["month_end_date"];
     } else {
         if ($payout_release == "week") {
             $week_arr = $this->getWeekStartEndDates($tprefix, $week_start_date_db, $week_end_date_db);
             $from_date = $week_arr["startDate"];
             $to_date = $week_arr["endDate"];
         } else {
             if ($payout_release == "daily") {
                 $from_date = date("Y-m-d") . " 00:00:00";
                 $to_date = date("Y-m-d") . " 23:59:59";
             } else {
                 $from_date = date("Y-m-d") . " 00:00:00";
                 $to_date = date("Y-m-d") . " 23:59:59";
             }
         }
     }
     $this->getAllUplineId($tprefix, $father_id, 0, $child_position);
     $total_len = count($this->upline_id_arr);
     // Pair Amount is incrementing + 1
     $pair_count = 1;
     $this->updateAllUpline($tprefix, $pair_count);
     for ($i = 0; $i < $total_len; $i++) {
         $user_id = $this->upline_id_arr["detail{$i}"]["id"];
         $left_leg = $this->upline_id_arr["detail{$i}"]["left_carry"];
         $right_leg = $this->upline_id_arr["detail{$i}"]["right_carry"];
         $user_pair = $this->getUserPair($tprefix, $user_id, $left_leg, $right_leg, $ceiling_user, $from_date, $to_date);
         if ($user_pair > 0) {
             $total_amount = $user_pair * $pair_price;
             $tds_amount = $total_amount * $tds_db / 100;
             $service_charge = $total_amount * $service_charge_db / 100;
             $amount_payable = $total_amount - ($tds_amount + $service_charge);
             $date_of_sub = date("Y-m-d H:i:s");
             $this->insertInToLegAmount($tprefix, $user_id, $left_leg, $right_leg, $user_pair, $total_amount, $amount_payable, $tds_amount, $service_charge, $date_of_sub, $from_id);
             $left_leg = $left_leg - $user_pair;
             $right_leg = $right_leg - $user_pair;
             $this->updateFTIndividualForPair($tprefix, $user_id, $left_leg, $right_leg, $user_pair);
         } else {
             $balance = min($left_leg, $right_leg);
             if ($balance > 0) {
                 $left_leg = $left_leg - $balance;
                 $right_leg = $right_leg - $balance;
                 $this->updateFTIndividualForPair($tprefix, $user_id, $left_leg, $right_leg, 0);
             }
         }
     }
 }
Example #19
0
 /**
  * @Request({"filter": "array", "page":"int"})
  * @Response("extension://page/views/admin/pages/index.razr")
  */
 public function indexAction($filter = null, $page = 0)
 {
     if ($filter) {
         $this['session']->set('page.filter', $filter);
     } else {
         $filter = $this['session']->get('page.filter', []);
     }
     $query = $this->pages->query();
     if (isset($filter['status']) && is_numeric($filter['status'])) {
         $query->where(['status' => intval($filter['status'])]);
     }
     if (isset($filter['search']) && strlen($filter['search'])) {
         $query->where(function ($query) use($filter) {
             $query->orWhere('title LIKE :search', ['search' => "%{$filter['search']}%"]);
         });
     }
     $limit = self::PAGES_PER_PAGE;
     $count = $query->count();
     $total = ceil($count / $limit);
     $page = max(0, min($total - 1, $page));
     $query->offset($page * $limit)->limit($limit)->orderBy('title');
     if ($this['request']->isXmlHttpRequest()) {
         return $this['response']->json(['table' => $this['view']->render('extension://page/views/admin/pages/table.razr', ['count' => $count, 'pages' => $query->get(), 'roles' => $this->roles->findAll()]), 'total' => $total]);
     }
     return ['head.title' => __('Pages'), 'pages' => $query->get(), 'statuses' => Page::getStatuses(), 'filter' => $filter, 'total' => $total, 'count' => $count];
 }
Example #20
0
 function index(Request $request)
 {
     /////////////////
     // Load Filter //
     /////////////////
     $filters = $this->request->only('type', 'tag', 'skip', 'take', 'group', 'with_count');
     ///////////
     // Query //
     ///////////
     if (!$filters['take']) {
         $filters['take'] = 500;
     } else {
         $filters['take'] = min($filters['take'] * 1, 500);
     }
     $filters['skip'] = $filters['skip'] * 1;
     $q = Model::name($filters['name'])->type($filters['type']);
     if ($filters['group']) {
         $q = $q->groupby('tag');
     }
     if ($filters['with_count']) {
         $count = $q->count();
     }
     $data = $q->skip($filters['skip'])->take($filters['take'])->orderBy('tag')->select(['type', 'tag'])->get();
     //////////////
     // Response //
     //////////////
     return response()->json(JSend::success(['count' => $count, 'data' => $data->toArray()])->asArray())->setCallback($this->request->input('callback'));
 }
function printHeadingImage($randomImage)
{
    global $_zp_themeroot;
    $id = getAlbumId();
    echo '<div id="randomhead">';
    if (is_null($randomImage) || checkforPassword(true)) {
        echo '<img src="' . $_zp_themeroot . '/images/zen-logo.jpg" alt="' . gettext('There were no images from which to select the random heading.') . '" />';
    } else {
        $randomAlbum = $randomImage->getAlbum();
        $randomAlt1 = $randomAlbum->getTitle();
        if ($randomAlbum->getAlbumId() != $id) {
            $randomAlbum = $randomAlbum->getParent();
            while (!is_null($randomAlbum) && $randomAlbum->getAlbumId() != $id) {
                $randomAlt1 = $randomAlbum->getTitle() . ":\n" . $randomAlt1;
                $randomAlbum = $randomAlbum->getParent();
            }
        }
        $randomImageURL = htmlspecialchars(getURL($randomImage));
        if (getOption('allow_upscale')) {
            $wide = 620;
            $high = 180;
        } else {
            $wide = min(620, $randomImage->getWidth());
            $high = min(180, $randomImage->getHeight());
        }
        echo "<a href='" . $randomImageURL . "' title='" . gettext('Random picture...') . "'><img src='" . htmlspecialchars($randomImage->getCustomImage(NULL, $wide, $high, $wide, $high, NULL, NULL, !getOption('Watermark_head_image'))) . "' width={$wide} height={$high} alt=" . '"' . htmlspecialchars($randomAlt1, ENT_QUOTES) . ":\n" . htmlspecialchars($randomImage->getTitle(), ENT_QUOTES) . '" /></a>';
    }
    echo '</div>';
}
 /**
  * Constructor.
  *
  * @param Integer $groupId     Project Id
  * @param Integer $weeksNumber Statistics duration in weeks
  *
  * @return Void
  */
 public function __construct($groupId, $weeksNumber)
 {
     $dao = new GitDao();
     // TODO: Optionally include presonal forks in repo list
     $allRepositories = $dao->getProjectRepositoryList($groupId);
     $um = UserManager::instance();
     $user = $um->getCurrentUser();
     $repoFactory = new GitRepositoryFactory($dao, ProjectManager::instance());
     foreach ($allRepositories as $repo) {
         $repository = $repoFactory->getRepositoryById($repo['repository_id']);
         if ($repository->userCanRead($user)) {
             $this->repoList[] = $repository;
         }
     }
     $this->displayChart = false;
     $this->weeksNumber = min($weeksNumber, self::MAX_WEEKSNUMBER);
     // Init some class properties according to 'weeks number' parameter
     $today = $_SERVER['REQUEST_TIME'];
     $startPeriod = strtotime("-{$this->weeksNumber} weeks");
     $weekInSeconds = self::WEEKS_IN_SECONDS;
     for ($i = $startPeriod + $weekInSeconds; $i < $today + $weekInSeconds; $i += $weekInSeconds) {
         $this->dates[] = date('M d', $i);
         $this->weekNum[] = intval(date('W', $i));
         $this->year[] = intval(date('Y', $i));
     }
 }
Example #23
0
 public function resize($width = 0, $height = 0, $scaled = true)
 {
     if (!$this->info['width'] || !$this->info['height']) {
         return;
     }
     $xpos = 0;
     $ypos = 0;
     $scale = min($width / $this->info['width'], $height / $this->info['height']);
     if ($scale == 1) {
         return;
     }
     if ($scaled) {
         $new_width = round($this->info['width'] * $scale);
         $new_height = round($this->info['height'] * $scale);
         $xpos = round(($width - $new_width) / 2);
         $ypos = round(($height - $new_height) / 2);
     } else {
         $new_width = $width;
         $new_height = $height;
     }
     $image_old = $this->image;
     $this->image = imagecreatetruecolor($width, $height);
     $this->image = $this->transparency($this, imagecreatetruecolor($width, $height));
     imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);
     imagedestroy($image_old);
     $this->info['width'] = $width;
     $this->info['height'] = $height;
 }
Example #24
0
 static function paginate($page, $limit, $count, $link)
 {
     $count = ceil($count / (double) $limit);
     $n = min(max(min($page + 5, $count), $limit), $count);
     $i = max(min(max($page - 5, 0), $n - $limit), 0);
     return include PROJECT_DIR . '/views/pagination.php';
 }
Example #25
0
 /**
  * Checks if the current login attempt is locked according to an exponential timeout.
  * There is cap on the length of the timeout however. The timeout could grow to infinity without the cap.
  * This returns how many seconds the session is locked out from attempting a login.
  *
  * @param $identity string
  * @return false | int
  */
 public function locked_out($identity)
 {
     $lockout_options = $this->options['login_lockout'];
     if (!empty($identity) and is_array($lockout_options) and (in_array('ipaddress', $lockout_options) or in_array('identity', $lockout_options))) {
         $row = $this->storage->locked_out($identity, $this->ip_transformer->insert($this->request->getClientIp()));
         if (!$row) {
             return false;
         }
         $number_of_attempts = $row->attemptNum;
         $last_attempt = $row->lastAttempt;
         //y = 1.8^(n-1) where n is number of attempts, resulting in exponential timeouts, to prevent brute force attacks
         $lockout_duration = round(pow(1.8, $number_of_attempts - 1));
         //capping the lockout time
         if ($this->options['login_lockout_cap']) {
             $lockout_duration = min($lockout_duration, $this->options['login_lockout_cap']);
         }
         //adding the lockout time to the last attempt will create the overall timeout
         $timeout = strtotime($last_attempt) + $lockout_duration;
         //if the current time is less than the timeout, then attempt is locked out
         if (time() < $timeout) {
             //return the difference in seconds
             return (int) $timeout - time();
         }
     }
     return false;
 }
 /**
  * Given a slice (subset) of an array, returns a connection object for use in
  * GraphQL.
  *
  * This function is similar to `connectionFromArray`, but is intended for use
  * cases where you know the cardinality of the connection, consider it too large
  * to materialize the entire array, and instead wish pass in a slice of the
  * total result large enough to cover the range specified in `args`.
  *
  * @return array
  */
 public static function connectionFromArraySlice(array $arraySlice, $args, $meta)
 {
     $after = self::getArrayValueSafe($args, 'after');
     $before = self::getArrayValueSafe($args, 'before');
     $first = self::getArrayValueSafe($args, 'first');
     $last = self::getArrayValueSafe($args, 'last');
     $sliceStart = self::getArrayValueSafe($meta, 'sliceStart');
     $arrayLength = self::getArrayValueSafe($meta, 'arrayLength');
     $sliceEnd = $sliceStart + count($arraySlice);
     $beforeOffset = self::getOffsetWidthDefault($before, $arrayLength);
     $afterOffset = self::getOffsetWidthDefault($after, -1);
     $startOffset = max([$sliceStart - 1, $afterOffset, -1]) + 1;
     $endOffset = min([$sliceEnd, $beforeOffset, $arrayLength]);
     if ($first !== null) {
         $endOffset = min([$endOffset, $startOffset + $first]);
     }
     if ($last !== null) {
         $startOffset = max([$startOffset, $endOffset - $last]);
     }
     $slice = array_slice($arraySlice, max($startOffset - $sliceStart, 0), count($arraySlice) - ($sliceEnd - $endOffset) - max($startOffset - $sliceStart, 0));
     $edges = array_map(function ($item, $index) use($startOffset) {
         return ['cursor' => self::offsetToCursor($startOffset + $index), 'node' => $item];
     }, $slice, array_keys($slice));
     $firstEdge = $edges ? $edges[0] : null;
     $lastEdge = $edges ? $edges[count($edges) - 1] : null;
     $lowerBound = $after ? $afterOffset + 1 : 0;
     $upperBound = $before ? $beforeOffset : $arrayLength;
     return ['edges' => $edges, 'pageInfo' => ['startCursor' => $firstEdge ? $firstEdge['cursor'] : null, 'endCursor' => $lastEdge ? $lastEdge['cursor'] : null, 'hasPreviousPage' => $last !== null ? $startOffset > $lowerBound : false, 'hasNextPage' => $first !== null ? $endOffset < $upperBound : false]];
 }
Example #27
0
function add_pagination_vars(&$page, $total, $curPage, $perPage, $append = '')
{
    $pgs = array();
    $p_min = 0;
    $p_max = $lastPage = floor($total / $perPage);
    if ($curPage == 0) {
        $p_max = min($lastPage, $curPage + 4);
    } else {
        if ($curPage == 1) {
            $p_max = min($lastPage, $curPage + 3);
        } else {
            $p_max = min($lastPage, $curPage + 2);
        }
    }
    if ($curPage == $lastPage) {
        $p_min = max(0, $curPage - 4);
    } else {
        if ($curPage == $lastPage - 1) {
            $p_min = max(0, $curPage - 3);
        } else {
            $p_min = max(0, $curPage - 2);
        }
    }
    for ($p = $p_min; $p <= $p_max; $p++) {
        $pgs[] = $p;
    }
    $page['pager'] = array('pages' => $pgs, 'first' => 0, 'current' => $curPage, 'last' => floor($total / $perPage), 'append' => $append);
}
/**
* Smarty truncate modifier plugin
* 
* Type:     modifier<br>
* Name:     truncate<br>
* Purpose:  Truncate a string to a certain length if necessary,
*             optionally splitting in the middle of a word, and
*             appending the $etc string or inserting $etc into the middle.
* 
* @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com> 
* @param string $string input string
* @param integer $length lenght of truncated text
* @param string $etc end string
* @param boolean $break_words truncate at word boundary
* @param boolean $middle truncate in the middle of text
* @return string truncated string
*/
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
    if ($length == 0) {
        return '';
    }
    if (is_callable('mb_strlen')) {
        if (mb_strlen($string) > $length) {
            $length -= min($length, mb_strlen($etc));
            if (!$break_words && !$middle) {
                $string = mb_ereg_replace('/\\s+?(\\S+)?$/', '', mb_substr($string, 0, $length + 1), 'p');
            }
            if (!$middle) {
                return mb_substr($string, 0, $length) . $etc;
            } else {
                return mb_substr($string, 0, $length / 2) . $etc . mb_substr($string, -$length / 2);
            }
        } else {
            return $string;
        }
    } else {
        if (strlen($string) > $length) {
            $length -= min($length, strlen($etc));
            if (!$break_words && !$middle) {
                $string = preg_replace('/\\s+?(\\S+)?$/', '', substr($string, 0, $length + 1));
            }
            if (!$middle) {
                return substr($string, 0, $length) . $etc;
            } else {
                return substr($string, 0, $length / 2) . $etc . substr($string, -$length / 2);
            }
        } else {
            return $string;
        }
    }
}
Example #29
0
 /**
  * Render the field value. Handle both single and repetitive fields.
  *
  * Rendering of a single value is defined in render_single() and multiple values are concatenated by
  * separator provided by get_value_separator().
  *
  * @param bool $echo Echo the output?
  * @return string Rendered HTML.
  * @since 1.9.1
  */
 public function render($echo = false)
 {
     $field_value = $this->field->get_value();
     // Handle all fields as repetitive, we allways have array of individual field values.
     $output_values = array();
     // Optionally limit the number of rendered items
     $max_item_count = $this->get_maximum_item_count();
     $loop_limit = $max_item_count > 0 ? min($max_item_count, count($field_value)) : count($field_value);
     $is_limited_by_max_count = $loop_limit < count($field_value);
     for ($i = 0; $i < $loop_limit; ++$i) {
         $value = array_shift($field_value);
         $output_values[] = $this->render_single($value);
     }
     $output = implode($this->get_value_separator(), $output_values);
     $ellipsis = $this->get_ellipsis();
     $is_limited_by_max_total_length = $this->limit_by_maximum_total_length($output);
     $needs_separator = $is_limited_by_max_count && !$is_limited_by_max_total_length;
     $needs_ellipsis = $is_limited_by_max_count || $is_limited_by_max_total_length;
     if ($needs_separator) {
         $output .= $this->get_value_separator();
     }
     if ($needs_ellipsis) {
         $output .= $ellipsis;
     }
     if ($echo) {
         echo $output;
     }
     return $output;
 }
Example #30
0
function qa_vote_set($post, $userid, $handle, $cookieid, $vote)
{
    require_once QA_INCLUDE_DIR . 'qa-db-points.php';
    require_once QA_INCLUDE_DIR . 'qa-db-hotness.php';
    require_once QA_INCLUDE_DIR . 'qa-db-votes.php';
    require_once QA_INCLUDE_DIR . 'qa-app-limits.php';
    $vote = (int) min(1, max(-1, $vote));
    $oldvote = (int) qa_db_uservote_get($post['postid'], $userid);
    qa_db_uservote_set($post['postid'], $userid, $vote);
    qa_db_post_recount_votes($post['postid']);
    $postisanswer = $post['basetype'] == 'A';
    $columns = array();
    if ($vote > 0 || $oldvote > 0) {
        $columns[] = $postisanswer ? 'aupvotes' : 'qupvotes';
    }
    if ($vote < 0 || $oldvote < 0) {
        $columns[] = $postisanswer ? 'adownvotes' : 'qdownvotes';
    }
    qa_db_points_update_ifuser($userid, $columns);
    qa_db_points_update_ifuser($post['userid'], array($postisanswer ? 'avoteds' : 'qvoteds', 'upvoteds', 'downvoteds'));
    if ($post['basetype'] == 'Q') {
        qa_db_hotness_update($post['postid']);
    }
    if ($vote < 0) {
        $action = $postisanswer ? 'a_vote_down' : 'q_vote_down';
    } elseif ($vote > 0) {
        $action = $postisanswer ? 'a_vote_up' : 'q_vote_up';
    } else {
        $action = $postisanswer ? 'a_vote_nil' : 'q_vote_nil';
    }
    qa_report_write_action($userid, null, $action, $postisanswer ? null : $post['postid'], $postisanswer ? $post['postid'] : null, null);
    qa_report_event($action, $userid, $handle, $cookieid, array('postid' => $post['postid'], 'vote' => $vote, 'oldvote' => $oldvote));
}