Example #1
0
 /**
  * Trims the given string to a particular length.
  *
  * @param  string $content
  * @param  int $length  Defaults to 200
  * @return string Trimmed output
  *
  */
 public function trim($content, $length = 200)
 {
     $output = trimText(strip_tags($content), $length);
     return $output;
 }
Example #2
0
 public function getUri($title, $id = 0, $contenttypeslug = "", $fulluri = true, $allowempty = true)
 {
     $contenttype = $this->getContentType($contenttypeslug);
     $tablename = $this->getTablename($contenttype['slug']);
     $id = intval($id);
     $fulluri = util::str_to_bool($fulluri);
     $slug = makeSlug($title);
     // don't allow strictly numeric slugs.
     if (is_numeric($slug)) {
         $slug = $contenttype['singular_slug'] . "-" . $slug;
     }
     // Only add 'entry/' if $full is requested.
     if ($fulluri) {
         $prefix = "/" . $contenttype['singular_slug'] . "/";
     } else {
         $prefix = "";
     }
     $query = sprintf("SELECT id from %s WHERE slug=? and id!=?", $tablename);
     $res = $this->app['db']->executeQuery($query, array($slug, $id), array(\PDO::PARAM_STR, \PDO::PARAM_INT))->fetch();
     if (!$res) {
         $uri = $prefix . $slug;
     } else {
         for ($i = 1; $i <= 10; $i++) {
             $newslug = $slug . '-' . $i;
             $res = $this->app['db']->executeQuery($query, array($newslug, $id), array(\PDO::PARAM_STR, \PDO::PARAM_INT))->fetch();
             if (!$res) {
                 $uri = $prefix . $newslug;
                 break;
             }
         }
         // otherwise, just get a random slug.
         if (empty($uri)) {
             $slug = trimText($slug, 32, false, false) . "-" . $this->app['randomgenerator']->generateString(6, 'abcdefghijklmnopqrstuvwxyz01234567890');
             $uri = $prefix . $slug;
         }
     }
     // When storing, we should never have an empty slug/URI. If we can't make a nice one, set it to 'slug-XXXX'.
     if (!$allowempty && empty($uri)) {
         $uri = 'slug-' . $this->app['randomgenerator']->generateString(6, 'abcdefghijklmnopqrstuvwxyz01234567890');
     }
     return $uri;
 }
Example #3
0
 /**
  * @dataProvider trimTextDataProvider
  */
 public function testTrimText($str, $length, $nbsp, $hellip, $striptags, $expected)
 {
     $result = trimText($str, $length, $nbsp, $hellip, $striptags);
     $this->assertEquals($expected, $result);
 }
Example #4
0
 /**
  *
  * Create an excerpt for the content.
  *
  * @param int $length
  * @return string
  */
 public function excerpt($length = 200)
 {
     $excerpt = array();
     foreach ($this->contenttype['fields'] as $key => $field) {
         if (in_array($field['type'], array('text', 'html', 'textarea')) && isset($this->values[$key]) && !in_array($key, array("title", "name"))) {
             $excerpt[] = $this->values[$key];
         }
     }
     $excerpt = implode(" ", $excerpt);
     $excerpt = trimText(strip_tags($excerpt), $length);
     return $excerpt;
 }
Example #5
0
 /**
  * Creates RSS safe content. Wraps it in CDATA tags, strips style and
  * scripts out. Can optionally also return a (cleaned) excerpt.
  *
  * @param  string $field         The field to clean up
  * @param  int    $excerptLength Number of chars of the excerpt
  * @return string RSS safe string
  */
 public function rss_safe($field = '', $excerptLength = 0)
 {
     if (array_key_exists($field, $this->values)) {
         if ($this->fieldtype($field) == 'html') {
             $value = $this->values[$field];
             // Completely remove style and script blocks
             $maid = new \Maid\Maid(array('allowed-tags' => array('a', 'b', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'p', 'strong', 'em', 'i', 'u', 'strike', 'ul', 'ol', 'li', 'img'), 'output-format' => 'html'));
             $result = $maid->clean($value);
             if ($excerptLength > 0) {
                 $result = trimText($result, $excerptLength, false, true, false);
             }
             return '<![CDATA[ ' . $result . ' ]]>';
         } else {
             return $this->values[$field];
         }
     }
     return "";
 }
/**
 * Creates the file that holds the last trackbacks. Just returns
 * if we're using SQL.
 *
 * @param array $temptrack
 * @return void
 */
function generateLastTrackbacks($temptrack)
{
    global $PIVOTX;
    // If we're using MySQL, there's no need for the last trackbacks file..
    if ($PIVOTX['db']->db_type != "flat") {
        return "";
    }
    $lasttrack_file = $PIVOTX['paths']['db_path'] . 'ser_lasttrack.php';
    // if it exists, load it
    if (file_exists($lasttrack_file)) {
        $lasttrack = loadSerialize($lasttrack_file, true, true);
    } else {
        $lasttrack = array();
    }
    $lasttrack[] = array('title' => $temptrack['title'], 'excerpt' => trimText($temptrack['excerpt'], 250), 'name' => $temptrack['name'], 'url' => $temptrack['url'], 'date' => $temptrack['date'], 'entry_uid' => $temptrack['entry_uid'], 'uid' => makeTrackbackUID($temptrack), 'category' => $PIVOTX['db']->entry['category'], 'ip' => $temptrack['ip']);
    if (count($lasttrack) > intval($PIVOTX['config']->get('lastcomm_amount_max'))) {
        array_shift($lasttrack);
    }
    saveSerialize($lasttrack_file, $lasttrack);
}
Example #7
0
/**
 * Link to the previous page in the containing chapter.
 *
 * @param array $params
 * @return string
 */
function smarty_previouspage($params, &$smarty)
{
    global $PIVOTX;
    // This tag is only allowed on pages..
    if ($PIVOTX['parser']->modifier['pagetype'] != "page") {
        return;
    }
    $vars = $smarty->get_template_vars();
    // The current page must exist/have an uid
    if (empty($vars['page']['uid'])) {
        debug("There is no uid for the current page.");
        return;
    }
    $params = cleanParams($params);
    $chapters = $PIVOTX['pages']->getIndex();
    $pages = $chapters[$vars['page']['chapter']]['pages'];
    // Handle sorting
    $sort = false;
    if (isset($params['sort'])) {
        $sort = true;
        if ($params['sort'] == 'title') {
            $pages_sort_key = 'title';
        } else {
            if ($params['sort'] == 'uri') {
                $pages_sort_key = 'uri';
            } else {
                if ($params['sort'] == 'date') {
                    $pages_sort_key = 'date';
                } else {
                    $sort = false;
                }
            }
        }
    }
    if ($sort) {
        foreach ($pages as $key => $page) {
            $pages[$page[$pages_sort_key]] = $page;
            unset($pages[$key]);
        }
        ksort($pages);
    }
    // We will find the previous page by searching the array in reverse order.
    // This means that have to reverse it, if sortorder isn't reverse ;-)
    if ($params['sortorder'] != 'reverse') {
        $pages = array_reverse($pages, true);
    }
    $found = false;
    do {
        $page = current($pages);
        $prevpage = next($pages);
        if (!$found && $page['uid'] == $vars['page']['uid']) {
            $found = true;
        }
    } while ($prevpage !== false && !($prevpage['status'] == "publish" && $found));
    $text = getDefault($params['text'], '&laquo; <a href="%link%">%title%</a>');
    $cutoff = getDefault($params['cutoff'], 20);
    if ($prevpage) {
        $title = strlen($prevpage['title']) > 2 ? $prevpage['title'] : substr($prevpage['introduction'], 0, 100);
        $link = makePageLink($prevpage['uri'], $prevpage['title'], $prevpage['uid'], $prevpage['date'], $params['weblog']);
        $output = $text;
        $output = str_replace("%link%", $link, $output);
        $output = str_replace("%title%", trimText($title, $cutoff), $output);
        $output = str_replace("%subtitle%", trimText($prevpage['subtitle'], $cutoff), $output);
        return entifyAmpersand($output);
    } else {
        return "";
    }
}
Example #8
0
 $ii = 0;
 if ($countriesNum && 0) {
     $percent = floor(100 / $num_of_cols);
     for ($r = 0; $r < $num_of_rows; $r++) {
         $sortRowClass = $ii % 2 ? "l_row1" : "l_row2";
         $ii++;
         echo "\n\n<tr class='{$sortRowClass}'>";
         for ($c = 0; $c < $num_of_cols; $c++) {
             //	echo "<td style='width:".$countriesDivWidth."px'>";
             echo "<td class='countryList' width='{$percent}%'>";
             //compute which to show
             //echo "c=$c r=$r i=$i<br>";
             $i = $c * $num_of_rows + $r % $num_of_rows;
             if ($i < $countriesNum) {
                 $countryName = $countriesNames[$i];
                 $countryName = trimText($countryName, 20);
                 $linkTmp = getLeonardoLink(array('op' => 'useCurrent', 'country' => $countriesCodes[$i]));
                 echo "<a href='{$linkTmp}'>{$countryName}</a>\n";
                 /*
                 if ($currentlang=='hebrew')
                 	echo "<a href='$linkTmp'>(".$countriesFlightsNum[$i].") $countryName</a>\n";
                 else
                 	echo "<a href='$linkTmp'>$countryName (".$countriesFlightsNum[$i].")</a>\n";
                 */
             } else {
                 echo "&nbsp;";
             }
             echo "</td>";
         }
         echo '</tr>';
     }
/**
 * Creates the file that holds the queue for comment moderation. Just returns
 * if we're using SQL.
 *
 * @param array $tempcomm
 * @return void
 */
function generateModerationQueue($tempcomm)
{
    global $PIVOTX;
    // If we're using MySQL, there's no need for the latest comments file..
    if ($PIVOTX['db']->db_type != "flat") {
        return "";
    }
    $modqueue_file = $PIVOTX['paths']['db_path'] . 'ser_modqueue.php';
    // if it exists, load it
    if (file_exists($modqueue_file)) {
        $modqueue = loadSerialize($modqueue_file, true, true);
    } else {
        $modqueue = array();
    }
    $modqueue[] = array('name' => $tempcomm['name'], 'email' => $tempcomm['email'], 'url' => $tempcomm['url'], 'date' => $tempcomm['date'], 'comment' => $tempcomm['comment'], 'entry_uid' => $PIVOTX['db']->entry['code'], 'title' => trimText($PIVOTX['db']->entry['title'], 50), 'category' => $PIVOTX['db']->entry['category'], 'ip' => $tempcomm['ip'], 'useragent' => $tempcomm['useragent']);
    saveSerialize($modqueue_file, $modqueue);
}
Example #10
0
 public function getUri($title, $id = 0, $contenttypeslug, $fulluri = true)
 {
     $contenttype = $this->getContentType($contenttypeslug);
     $tablename = $this->prefix . $contenttype['slug'];
     $id = intval($id);
     $fulluri = util::str_to_bool($fulluri);
     $slug = makeSlug($title);
     // don't allow strictly numeric slugs.
     if (is_numeric($slug)) {
         $slug = $contenttype['singular_slug'] . "-" . $slug;
     }
     // Only add 'entry/' if $full is requested.
     if ($fulluri) {
         $prefix = "/" . $contenttype['singular_slug'] . "/";
     }
     $query = "SELECT id from {$tablename} WHERE slug='{$slug}' and id!='{$id}';";
     $res = $this->db->query($query)->fetch();
     if (!$res) {
         $uri = $prefix . $slug;
     } else {
         for ($i = 1; $i <= 10; $i++) {
             $newslug = $slug . '-' . $i;
             $query = "SELECT id from {$tablename} WHERE slug='{$newslug}' and id!='{$id}';";
             $res = $this->db->query($query)->fetch();
             if (!$res) {
                 $uri = $prefix . $newslug;
                 break;
             }
         }
         // otherwise, just get a random slug.
         if (empty($uri)) {
             $slug = trimText($slug, 32, false, false) . "-" . makeKey(6);
             $uri = $prefix . $slug;
         }
     }
     return $uri;
 }
Example #11
0
function getWaypointName($ID, $forceIntl = -1, $countryFirst = 0, $maxChars = 0)
{
    global $db, $waypointsTable;
    global $CONFIG_forceIntl;
    if ($forceIntl == -1) {
        $forceIntl = $CONFIG_forceIntl;
    }
    $query = "SELECT * from {$waypointsTable} WHERE ID=" . $ID;
    $res = $db->sql_query($query);
    if ($res <= 0) {
        return "UNKNOWN";
    }
    $row = $db->sql_fetchrow($res);
    $db->sql_freeresult($res);
    $tname = selectWaypointName($row["name"], $row["intName"], $row["countryCode"], $forceIntl);
    $tname = trimText($tname, $maxChars);
    if ($countryFirst) {
        return $row["countryCode"] . " - " . $tname;
    } else {
        return $tname . " - " . $row["countryCode"];
    }
}
Example #12
0
/**
 * Page for the Bookmarklet.
 */
function pageBookmarklet()
{
    global $PIVOTX;
    // check if the user is logged in.
    if (!$PIVOTX['session']->isLoggedIn()) {
        pageLogin('small');
        die;
    }
    $currentuser = $PIVOTX['users']->getUser($PIVOTX['session']->currentUsername());
    $entry = array();
    if ($PIVOTX['config']->get('default_category') != "") {
        $entry['category'] = array($PIVOTX['config']->get('default_category'));
    }
    if ($PIVOTX['config']->get('default_post_status') != "") {
        $entry['status'] = $PIVOTX['config']->get('default_post_status');
    }
    $entry['link'] = makeFileLink(array('date' => date("Y-m-d-H-i-s")), "", "");
    $entry['publish_date'] = date("Y-m-d-H-i-s", strtotime('+1 month'));
    // Set some things, based on referring page..
    $entry['introduction'] = "";
    // Execute the hook, if present..
    $PIVOTX['extensions']->executeHook('begin_bookmarklet', $entry);
    if (!empty($_GET['selection'])) {
        $entry['introduction'] .= "<p>&nbsp;</p>\n\n<blockquote>\n" . $_GET['selection'] . "\n</blockquote>\n\n";
    }
    if (!empty($_GET['title'])) {
        $entry['title'] = sanitizeTitle($_GET['title']);
        $entry['introduction'] .= sprintf("<p><a href='%s'>%s</a></p>", $_GET['url'], $entry['title']);
    } else {
        $entry['introduction'] .= sprintf("<p><a href='%s'>%s</a></p>", $_GET['url'], __("link"));
    }
    $PIVOTX['extensions']->executeHook('end_bookmarklet', $entry);
    // Make sure we only show the allowed categories.. Superadmins can always
    // see and use all categories..
    $categories = $PIVOTX['categories']->getCategories();
    if ($currentuser['userlevel'] < PIVOTX_UL_SUPERADMIN) {
        $allowedcats = $PIVOTX['categories']->allowedCategories($currentuser['username']);
        foreach ($categories as $key => $value) {
            if (!in_array($value['name'], $allowedcats)) {
                unset($categories[$key]);
            }
        }
    }
    if (!isset($_POST['title'])) {
        // Show the screen..
        $PIVOTX['template']->assign('entry', $entry);
        $PIVOTX['template']->assign('categories', $categories);
        $PIVOTX['template']->assign('pivotxsession', $PIVOTX['session']->getCSRF());
        $PIVOTX['template']->assign('entryuser', $PIVOTX['users']->getUser($entry['user']));
        renderTemplate('bookmarklet_entry.tpl');
    } else {
        // Make sure the current user is properly logged in, and that the request is legitimate
        $PIVOTX['session']->checkCSRF($_POST['pivotxsession']);
        // Sanitize the $_POST into an entry we can store
        $entry = sanitizePostedEntry($entry);
        if ($PIVOTX['config']->get('allow_comments') != "") {
            $entry['allow_comments'] = $PIVOTX['config']->get('allow_comments');
        }
        $entry['user'] = $currentuser['username'];
        $PIVOTX['extensions']->executeHook('entry_edit_beforesave', $entry);
        $entry = $PIVOTX['db']->set_entry($entry);
        if ($PIVOTX['db']->save_entry(TRUE)) {
            $message = sprintf(__('Your entry "%s" was successfully saved.'), '<em>' . trimText($entry['title'], 25) . '</em>');
            $PIVOTX['extensions']->executeHook('entry_edit_aftersave', $entry);
        } else {
            $message = sprintf(__('Your entry "%s" was NOT successfully saved.'), '<em>' . trimText($entry['title'], 25) . '</em>');
            $PIVOTX['extensions']->executeHook('entry_edit_aftersave_failed', $entry);
        }
        // Remove the compiled/parsed pages from the cache.
        if ($PIVOTX['config']->get('smarty_cache')) {
            $PIVOTX['template']->clear_cache();
        }
        // Show the screen..
        $PIVOTX['template']->assign('message', $message);
        $PIVOTX['template']->assign('uid', $PIVOTX['db']->entry['uid']);
        renderTemplate('bookmarklet_menu.tpl');
    }
}
Example #13
0
 /**
  * Ajax helper function to facilitate the selection of files from the images/
  * folder.
  *
  */
 public static function ext_fileSelector()
 {
     global $PIVOTX;
     $PIVOTX['session']->minLevel(PIVOTX_UL_NORMAL);
     $path = $PIVOTX['paths']['upload_base_path'];
     $url = $PIVOTX['paths']['upload_base_url'];
     if (empty($path) || empty($url)) {
         echo "Can't continue: paths not set..";
         die;
     }
     $breadcrumbs = array("<a href='#' onclick=\"fileSelectorChangefolder('')\">" . basename($path) . "</a>");
     if (!empty($_POST['folder'])) {
         $folder = fixPath($_POST['folder']) . "/";
         $path .= $folder;
         $url .= $folder;
         $incrementalpath = "";
         foreach (explode("/", $folder) as $item) {
             if (!empty($item)) {
                 $incrementalpath = $incrementalpath . $item . "/";
                 $breadcrumbs[] = sprintf("<a href='#' onclick=\"fileSelectorChangefolder('%s')\">%s</a>", $incrementalpath, $item);
             }
         }
     }
     $breadcrumbs = implode(" &raquo; ", $breadcrumbs);
     $files = array();
     $folders = array();
     $d = dir($path);
     while (false !== ($filename = $d->read())) {
         if (strpos($filename, '.thumb.') !== false || strpos($filename, '._') !== false || $filename == ".DS_Store" || $filename == "Thumbs.db" || $filename == "." || $filename == ".." || $filename == ".svn") {
             // Skip this one..
             continue;
         }
         if (is_file($path . $filename)) {
             $files[$filename]['link'] = $url . urlencode($filename);
             $files[$filename]['name'] = trimText($filename, 50);
             $ext = strtolower(getExtension($filename));
             $files[$filename]['ext'] = $ext;
             $files[$filename]['bytesize'] = filesize($path . "/" . $filename);
             $files[$filename]['size'] = formatFilesize($files[$filename]['bytesize']);
             if (in_array($ext, array('gif', 'jpg', 'jpeg', 'png'))) {
                 $dim = getimagesize($path . "/" . $filename);
                 $files[$filename]['dimension'] = sprintf('%s &#215; %s', $dim[0], $dim[1]);
                 $files[$filename]['image_type'] = $ext;
             }
             $files[$filename]['path'] = $folder . $filename;
         }
         if (is_dir($path . $filename)) {
             $folders[$filename] = array('link' => $url . urlencode($filename), 'name' => trimText($filename, 50), 'path' => $folder . $filename);
         }
     }
     $d->close();
     ksort($folders);
     ksort($files);
     echo "<div id='fileselector'>";
     printf("<p><strong>%s:</strong> %s </p>", __("Current path"), $breadcrumbs);
     foreach ($folders as $folder) {
         printf("<div class='folder'><a href='#' onclick=\"fileSelectorChangefolder('%s'); return false;\">%s</a></div>", addslashes($folder['path']), $folder['name']);
     }
     foreach ($files as $file) {
         if ($PIVOTX['config']->get('fileselector_thumbs') && !empty($file['image_type'])) {
             $height = getDefault($PIVOTX['config']->get('fileselector_thumbs_height'), 40);
             $link_text = sprintf("<img src='%sincludes/timthumb.php?h=%s&amp;src=%s' alt='%s' title='%s'>", $PIVOTX['paths']['pivotx_url'], $height, $file['path'], $file['name'], $file['name']);
             $extra_style = "style='height: {$height}px; margin-bottom: 5px;'";
         } else {
             $link_text = $file['name'];
             $extra_style = "";
         }
         printf("<div class='file' {$extra_style}><a href='#' onclick=\"fileSelectorChoose('%s'); return false;\">%s</a> <span>(%s%s)</span></div>", addslashes($file['path']), $link_text, $file['size'], !empty($file['dimension']) ? " - " . $file['dimension'] . " px" : "");
     }
     echo "</div>";
     //echo "<pre>\n"; print_r($folders); echo "</pre>";
     //echo "<pre>\n"; print_r($files); echo "</pre>";
 }
 /**
  * Returns a formatted properties table.
  *
  * @param array $props
  * @return string
  */
 private static function properties(array $props)
 {
     return "<h6>Assigned properties</h6><table class=grid>\n" . str_replace(["'", '...'], ["<i>'</i>", '<i>...</i>'], implode('', map($props, function ($v, $k) {
         return "<tr><th>{$k}<td>" . (is_string($v) ? "'" . htmlspecialchars(trimText($v, 300, '...')) . "'" : Debug::toString($v));
     })), $o) . "\n</table>";
 }
Example #15
0
 public function rss_safe($fields = '', $excerptLength = 0)
 {
     // Make sure we have an array of fields. Even if it's only one.
     if (!is_array($fields)) {
         $fields = explode(',', $fields);
     }
     $fields = array_map('trim', $fields);
     $result = '';
     foreach ($fields as $field) {
         if (array_key_exists($field, $this->values)) {
             // Completely remove style and script blocks
             $maid = new \Maid\Maid(array('allowed-tags' => array('a', 'b', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'p', 'strong', 'em', 'i', 'u', 'strike', 'ul', 'ol', 'li', 'img'), 'output-format' => 'html'));
             $result .= $maid->clean($this->values[$field]);
         }
     }
     if ($excerptLength > 0) {
         $result .= trimText($result, $excerptLength, false, true, false);
     }
     return '<![CDATA[ ' . $result . ' ]]>';
 }