[ Index ]

PHP Cross Reference of Nucleus CMS v3.51 code documentation

title

Body

[close]

/nucleus/libs/ -> BLOG.php (source)

   1  <?php
   2  
   3  /*

   4   * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)

   5   * Copyright (C) 2002-2009 The Nucleus Group

   6   *

   7   * This program is free software; you can redistribute it and/or

   8   * modify it under the terms of the GNU General Public License

   9   * as published by the Free Software Foundation; either version 2

  10   * of the License, or (at your option) any later version.

  11   * (see nucleus/documentation/index.html#license for more info)

  12   */
  13  /**

  14   * A class representing a blog and containing functions to get that blog shown

  15   * on the screen

  16   *

  17   * @license http://nucleuscms.org/license.txt GNU General Public License

  18   * @copyright Copyright (C) 2002-2009 The Nucleus Group

  19   * @version $Id: BLOG.php 1398 2009-08-05 22:14:07Z ftruscot $

  20   */
  21  
  22  if ( !function_exists('requestVar') ) exit;
  23  require_once dirname(__FILE__) . '/ITEMACTIONS.php';
  24  
  25  class BLOG {
  26  
  27      // blog id

  28      var $blogid;
  29  
  30      // ID of currently selected category

  31      var $selectedcatid;
  32  
  33      // After creating an object of the blog class, contains true if the BLOG object is

  34      // valid (the blog exists)

  35      var $isValid;
  36  
  37      // associative array, containing all blogsettings (use the get/set functions instead)

  38      var $settings;
  39  
  40      /**

  41       * Creates a new BLOG object for the given blog

  42       *

  43       * @param $id blogid

  44       */
  45  	function BLOG($id) {
  46          $this->blogid = intval($id);
  47          $this->readSettings();
  48  
  49          // try to set catid

  50          // (the parse functions in SKIN.php will override this, so it's mainly useless)

  51          global $catid;
  52          $this->setSelectedCategory($catid);
  53      }
  54  
  55      /**

  56       * Shows the given amount of items for this blog

  57       *

  58       * @param $template

  59       *        String representing the template _NAME_ (!)

  60       * @param $amountEntries

  61       *        amount of entries to show

  62       * @param $startpos

  63       *        offset from where items should be shown (e.g. 5 = start at fifth item)

  64       * @returns int

  65       *        amount of items shown

  66       */
  67  	function readLog($template, $amountEntries, $offset = 0, $startpos = 0) {
  68          return $this->readLogAmount($template,$amountEntries,'','',1,1,$offset, $startpos);
  69      }
  70  
  71      /**

  72       * Shows an archive for a given month

  73       *

  74       * @param $year

  75       *        year

  76       * @param $month

  77       *        month

  78       * @param $template

  79       *        String representing the template name to be used

  80       */
  81  	function showArchive($templatename, $year, $month=0, $day=0) {
  82  
  83          // create extra where clause for select query

  84          if ($day == 0 && $month != 0) {
  85              $timestamp_start = mktime(0,0,0,$month,1,$year);
  86              $timestamp_end = mktime(0,0,0,$month+1,1,$year);  // also works when $month==12

  87          } elseif ($month == 0) {
  88              $timestamp_start = mktime(0,0,0,1,1,$year);
  89              $timestamp_end = mktime(0,0,0,12,31,$year);  // also works when $month==12

  90          } else {
  91              $timestamp_start = mktime(0,0,0,$month,$day,$year);
  92              $timestamp_end = mktime(0,0,0,$month,$day+1,$year);
  93          }
  94          $extra_query = ' and i.itime>=' . mysqldate($timestamp_start)
  95                       . ' and i.itime<' . mysqldate($timestamp_end);
  96  
  97  
  98          $this->readLogAmount($templatename,0,$extra_query,'',1,1);
  99  
 100      }
 101  
 102  
 103      // sets/gets current category (only when category exists)

 104  	function setSelectedCategory($catid) {
 105          if ($this->isValidCategory($catid) || (intval($catid) == 0))
 106              $this->selectedcatid = intval($catid);
 107      }
 108  
 109  	function setSelectedCategoryByName($catname) {
 110          $this->setSelectedCategory($this->getCategoryIdFromName($catname));
 111      }
 112  
 113  	function getSelectedCategory() {
 114          return $this->selectedcatid;
 115      }
 116  
 117      /**

 118       * Shows the given amount of items for this blog

 119       *

 120       * @param $template

 121       *        String representing the template _NAME_ (!)

 122       * @param $amountEntries

 123       *        amount of entries to show (0 = no limit)

 124       * @param $extraQuery

 125       *        extra conditions to be added to the query

 126       * @param $highlight

 127       *        contains a query that should be highlighted

 128       * @param $comments

 129       *        1=show comments 0=don't show comments

 130       * @param $dateheads

 131       *        1=show dateheads 0=don't show dateheads

 132       * @param $offset

 133       *        offset

 134       * @returns int

 135       *        amount of items shown

 136       */
 137  	function readLogAmount($template, $amountEntries, $extraQuery, $highlight, $comments, $dateheads, $offset = 0, $startpos = 0) {
 138  
 139          $query = $this->getSqlBlog($extraQuery);
 140  
 141          if ($amountEntries > 0) {
 142                  // $offset zou moeten worden:

 143                  // (($startpos / $amountentries) + 1) * $offset ... later testen ...

 144                 $query .= ' LIMIT ' . intval($startpos + $offset).',' . intval($amountEntries);
 145          }
 146          return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
 147      }
 148  
 149  	function showUsingQuery($templateName, $query, $highlight = '', $comments = 0, $dateheads = 1) {
 150          global $CONF, $manager;
 151  
 152          $lastVisit = cookieVar($CONF['CookiePrefix'] .'lastVisit');
 153          if ($lastVisit != 0)
 154              $lastVisit = $this->getCorrectTime($lastVisit);
 155  
 156          // set templatename as global variable (so plugins can access it)

 157          global $currentTemplateName;
 158          $currentTemplateName = $templateName;
 159  
 160          $template =& $manager->getTemplate($templateName);
 161  
 162          // create parser object & action handler

 163          $actions =& new ITEMACTIONS($this);
 164          $parser =& new PARSER($actions->getDefinedActions(),$actions);
 165          $actions->setTemplate($template);
 166          $actions->setHighlight($highlight);
 167          $actions->setLastVisit($lastVisit);
 168          $actions->setParser($parser);
 169          $actions->setShowComments($comments);
 170  
 171          // execute query

 172          $items = sql_query($query);
 173  
 174          // loop over all items

 175          $old_date = 0;
 176          while ($item = sql_fetch_object($items)) {
 177  
 178              $item->timestamp = strtotime($item->itime);    // string timestamp -> unix timestamp

 179  
 180              // action handler needs to know the item we're handling

 181              $actions->setCurrentItem($item);
 182  
 183              // add date header if needed

 184              if ($dateheads) {
 185                  $new_date = date('dFY',$item->timestamp);
 186                  if ($new_date != $old_date) {
 187                      // unless this is the first time, write date footer

 188                      $timestamp = $item->timestamp;
 189                      if ($old_date != 0) {
 190                          $oldTS = strtotime($old_date);
 191                          $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
 192                          $tmp_footer = strftime(isset($template['DATE_FOOTER'])?$template['DATE_FOOTER']:'', $oldTS);
 193                          $parser->parse($tmp_footer);
 194                          $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
 195                      }
 196                      $manager->notify('PreDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
 197                      // note, to use templatvars in the dateheader, the %-characters need to be doubled in

 198                      // order to be preserved by strftime

 199                      $tmp_header = strftime((isset($template['DATE_HEADER']) ? $template['DATE_HEADER'] : null), $timestamp);
 200                      $parser->parse($tmp_header);
 201                      $manager->notify('PostDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
 202                  }
 203                  $old_date = $new_date;
 204              }
 205  
 206              // parse item

 207              $parser->parse($template['ITEM_HEADER']);
 208              $manager->notify('PreItem', array('blog' => &$this, 'item' => &$item));
 209              $parser->parse($template['ITEM']);
 210              $manager->notify('PostItem', array('blog' => &$this, 'item' => &$item));
 211              $parser->parse($template['ITEM_FOOTER']);
 212  
 213          }
 214  
 215          $numrows = sql_num_rows($items);
 216  
 217          // add another date footer if there was at least one item

 218          if (($numrows > 0) && $dateheads) {
 219              $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
 220              $parser->parse($template['DATE_FOOTER']);
 221              $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
 222          }
 223  
 224          sql_free_result($items);    // free memory

 225  
 226          return $numrows;
 227  
 228      }
 229  
 230  	function showOneitem($itemid, $template, $highlight) {
 231          $extraQuery = ' and inumber=' . intval($itemid);
 232  
 233          return $this->readLogAmount($template, 1, $extraQuery, $highlight, 0, 0);
 234      }
 235  
 236  
 237      /**

 238        * Adds an item to this blog

 239        */
 240  	function additem($catid, $title, $body, $more, $blogid, $authorid, $timestamp, $closed, $draft, $posted='1') {
 241          global $manager;
 242  
 243          $blogid     = intval($blogid);
 244          $authorid    = intval($authorid);
 245          $title        = $title;
 246          $body        = $body;
 247          $more        = $more;
 248          $catid        = intval($catid);
 249  
 250          // convert newlines to <br />

 251          if ($this->convertBreaks()) {
 252              $body = addBreaks($body);
 253              $more = addBreaks($more);
 254          }
 255  
 256          if ($closed != '1') $closed = '0';
 257          if ($draft != '0') $draft = '1';
 258  
 259          if (!$this->isValidCategory($catid))
 260              $catid = $this->getDefaultCategory();
 261  
 262          if ($timestamp > $this->getCorrectTime())
 263              $isFuture = 1;
 264  
 265          $timestamp = date('Y-m-d H:i:s',$timestamp);
 266  
 267          $manager->notify('PreAddItem',array('title' => &$title, 'body' => &$body, 'more' => &$more, 'blog' => &$this, 'authorid' => &$authorid, 'timestamp' => &$timestamp, 'closed' => &$closed, 'draft' => &$draft, 'catid' => &$catid));
 268  
 269          $title = addslashes($title);
 270          $body = addslashes($body);
 271          $more = addslashes($more);
 272  
 273          $query = 'INSERT INTO '.sql_table('item').' (ITITLE, IBODY, IMORE, IBLOG, IAUTHOR, ITIME, ICLOSED, IDRAFT, ICAT, IPOSTED) '
 274                 . "VALUES ('$title', '$body', '$more', $blogid, $authorid, '$timestamp', $closed, $draft, $catid, $posted)";
 275          sql_query($query);
 276          $itemid = sql_insert_id();
 277  
 278          $manager->notify('PostAddItem',array('itemid' => $itemid));
 279  
 280          if (!$draft)
 281              $this->updateUpdateFile();
 282  
 283          // send notification mail

 284          if (!$draft && !$isFuture && $this->getNotifyAddress() && $this->notifyOnNewItem())
 285              $this->sendNewItemNotification($itemid, stripslashes($title), stripslashes($body));
 286  
 287          return $itemid;
 288      }
 289  
 290  	function sendNewItemNotification($itemid, $title, $body) {
 291          global $CONF, $member;
 292  
 293          // create text version of html post

 294          $ascii = toAscii($body);
 295  
 296          $mailto_msg = _NOTIFY_NI_MSG . " \n";
 297  //        $mailto_msg .= $CONF['IndexURL'] . 'index.php?itemid=' . $itemid . "\n\n";

 298          $temp = parse_url($CONF['Self']);
 299          if ($temp['scheme']) {
 300              $mailto_msg .= createItemLink($itemid) . "\n\n";
 301          } else {
 302              $tempurl = $this->getURL();
 303              if (substr($tempurl, -1) == '/' || substr($tempurl, -4) == '.php') {
 304                  $mailto_msg .= $tempurl . '?itemid=' . $itemid . "\n\n";
 305              } else {
 306                  $mailto_msg .= $tempurl . '/?itemid=' . $itemid . "\n\n";
 307              }
 308          }
 309          $mailto_msg .= _NOTIFY_TITLE . ' ' . strip_tags($title) . "\n";
 310          $mailto_msg .= _NOTIFY_CONTENTS . "\n " . $ascii . "\n";
 311          $mailto_msg .= getMailFooter();
 312  
 313          $mailto_title = $this->getName() . ': ' . _NOTIFY_NI_TITLE;
 314  
 315          $frommail = $member->getNotifyFromMailAddress();
 316  
 317          $notify =& new NOTIFICATION($this->getNotifyAddress());
 318          $notify->notify($mailto_title, $mailto_msg , $frommail);
 319  
 320  
 321  
 322      }
 323  
 324  
 325      /**

 326        * Creates a new category for this blog

 327        *

 328        * @param $catName

 329        *        name of the new category. When empty, a name is generated automatically

 330        *        (starting with newcat)

 331        * @param $catDescription

 332        *        description of the new category. Defaults to 'New Category'

 333        *

 334        * @returns

 335        *        the new category-id in case of success.

 336        *        0 on failure

 337        */
 338  	function createNewCategory($catName = '', $catDescription = _CREATED_NEW_CATEGORY_DESC) {
 339          global $member, $manager;
 340  
 341          if ($member->blogAdminRights($this->getID())) {
 342              // generate

 343              if ($catName == '')
 344              {
 345                  $catName = _CREATED_NEW_CATEGORY_NAME;
 346                  $i = 1;
 347  
 348                  $res = sql_query('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->getID());
 349                  while (sql_num_rows($res) > 0)
 350                  {
 351                      $i++;
 352                      $res = sql_query('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->getID());
 353                  }
 354  
 355                  $catName = $catName . $i;
 356              }
 357  
 358              $manager->notify(
 359                  'PreAddCategory',
 360                  array(
 361                      'blog' => &$this,
 362                      'name' => &$catName,
 363                      'description' => $catDescription
 364                  )
 365              );
 366  
 367              $query = 'INSERT INTO '.sql_table('category').' (cblog, cname, cdesc) VALUES (' . $this->getID() . ", '" . addslashes($catName) . "', '" . addslashes($catDescription) . "')";
 368              sql_query($query);
 369              $catid = sql_insert_id();
 370  
 371              $manager->notify(
 372                  'PostAddCategory',
 373                  array(
 374                      'blog' => &$this,
 375                      'name' => $catName,
 376                      'description' => $catDescription,
 377                      'catid' => $catid
 378                  )
 379              );
 380  
 381              return $catid;
 382          } else {
 383              return 0;
 384          }
 385  
 386      }
 387  
 388  
 389      /**

 390       * Searches all months of this blog for the given query

 391       *

 392       * @param $query

 393       *        search query

 394       * @param $template

 395       *        template to be used (__NAME__ of the template)

 396       * @param $amountMonths

 397       *        max amount of months to be search (0 = all)

 398       * @param $maxresults

 399       *        max number of results to show

 400       * @param $startpos

 401       *        offset

 402       * @returns

 403       *        amount of hits found

 404       */
 405  	function search($query, $template, $amountMonths, $maxresults, $startpos) {
 406          global $CONF, $manager;
 407  
 408          $highlight     = '';
 409          $sqlquery    = $this->getSqlSearch($query, $amountMonths, $highlight);
 410  
 411          if ($sqlquery == '')
 412          {
 413              // no query -> show everything

 414              $extraquery = '';
 415              $amountfound = $this->readLogAmount($template, $maxresults, $extraQuery, $query, 1, 1);
 416          } else {
 417  
 418              // add LIMIT to query (to split search results into pages)

 419              if (intval($maxresults > 0))
 420                  $sqlquery .= ' LIMIT ' . intval($startpos).',' . intval($maxresults);
 421  
 422              // show results

 423              $amountfound = $this->showUsingQuery($template, $sqlquery, $highlight, 1, 1);
 424  
 425              // when no results were found, show a message

 426              if ($amountfound == 0)
 427              {
 428                  $template =& $manager->getTemplate($template);
 429                  $vars = array(
 430                      'query'        => htmlspecialchars($query),
 431                      'blogid'    => $this->getID()
 432                  );
 433                  echo TEMPLATE::fill($template['SEARCH_NOTHINGFOUND'],$vars);
 434              }
 435          }
 436  
 437          return $amountfound;
 438      }
 439  
 440      /**

 441       * Returns an SQL query to use for a search query

 442       *

 443       * @param $query

 444       *        search query

 445       * @param $amountMonths

 446       *        amount of months to search back. Default = 0 = unlimited

 447       * @param $mode

 448       *        either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query

 449       * @returns $highlight

 450       *        words to highlight (out parameter)

 451       * @returns

 452       *        either a full SQL query, or an empty string (if querystring empty)

 453       * @note

 454       *        No LIMIT clause is added. (caller should add this if multiple pages are requested)

 455       */
 456  	function getSqlSearch($query, $amountMonths = 0, &$highlight, $mode = '')
 457      {
 458          $searchclass =& new SEARCH($query);
 459  
 460          $highlight      = $searchclass->inclusive;
 461  
 462          // if querystring is empty, return empty string

 463          if ($searchclass->inclusive == '')
 464              return '';
 465  
 466  
 467          $where  = $searchclass->boolean_sql_where('ititle,ibody,imore');
 468          $select = $searchclass->boolean_sql_select('ititle,ibody,imore');
 469  
 470          // get list of blogs to search

 471          $blogs         = $searchclass->blogs;         // array containing blogs that always need to be included

 472          $blogs[]    = $this->getID();            // also search current blog (duh)

 473          $blogs         = array_unique($blogs);        // remove duplicates

 474          $selectblogs = '';
 475          if (count($blogs) > 0)
 476              $selectblogs = ' and i.iblog in (' . implode(',', $blogs) . ')';
 477  
 478          if ($mode == '')
 479          {
 480              $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author, m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
 481              if ($select)
 482                  $query .= ', '.$select. ' as score ';
 483          } else {
 484              $query = 'SELECT COUNT(*) as result ';
 485          }
 486  
 487          $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
 488                 . ' WHERE i.iauthor=m.mnumber'
 489                 . ' and i.icat=c.catid'
 490                 . ' and i.idraft=0'    // exclude drafts
 491                 . $selectblogs
 492                      // don't show future items

 493                 . ' and i.itime<=' . mysqldate($this->getCorrectTime())
 494                 . ' and '.$where;
 495  
 496          // take into account amount of months to search

 497          if ($amountMonths > 0)
 498          {
 499              $localtime = getdate($this->getCorrectTime());
 500              $timestamp_start = mktime(0,0,0,$localtime['mon'] - $amountMonths,1,$localtime['year']);
 501              $query .= ' and i.itime>' . mysqldate($timestamp_start);
 502          }
 503  
 504          if ($mode == '')
 505          {
 506              if ($select)
 507                  $query .= ' ORDER BY score DESC';
 508              else
 509                  $query .= ' ORDER BY i.itime DESC ';
 510          }
 511  
 512          return $query;
 513      }
 514  
 515      /**

 516       * Returns the SQL query that's normally used to display the blog items on the index type skins

 517       *

 518       * @param $mode

 519       *        either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query

 520       * @returns

 521       *        either a full SQL query, or an empty string

 522       * @note

 523       *        No LIMIT clause is added. (caller should add this if multiple pages are requested)

 524       */
 525  	function getSqlBlog($extraQuery, $mode = '')
 526      {
 527          if ($mode == '')
 528              $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author, m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
 529          else
 530              $query = 'SELECT COUNT(*) as result ';
 531  
 532          $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
 533                 . ' WHERE i.iblog='.$this->blogid
 534                 . ' and i.iauthor=m.mnumber'
 535                 . ' and i.icat=c.catid'
 536                 . ' and i.idraft=0'    // exclude drafts
 537                      // don't show future items

 538                 . ' and i.itime<=' . mysqldate($this->getCorrectTime());
 539  
 540          if ($this->getSelectedCategory())
 541              $query .= ' and i.icat=' . $this->getSelectedCategory() . ' ';
 542  
 543  
 544          $query .= $extraQuery;
 545  
 546          if ($mode == '')
 547              $query .= ' ORDER BY i.itime DESC';
 548  
 549          return $query;
 550      }
 551  
 552      /**

 553        * Shows the archivelist using the given template

 554        */
 555  	function showArchiveList($template, $mode = 'month', $limit = 0) {
 556          global $CONF, $catid, $manager;
 557  
 558          if (!isset ($linkparams)) {
 559              $linkparams = array();
 560          }
 561          
 562          if ($catid) {
 563              $linkparams = array('catid' => $catid);
 564          }
 565  
 566          $template =& $manager->getTemplate($template);
 567          $data['blogid'] = $this->getID();
 568  
 569          $tplt = isset($template['ARCHIVELIST_HEADER']) ? $template['ARCHIVELIST_HEADER']
 570                                                         : '';
 571          echo TEMPLATE::fill($tplt, $data);
 572  
 573          $query = 'SELECT itime, SUBSTRING(itime,1,4) AS Year, SUBSTRING(itime,6,2) AS Month, SUBSTRING(itime,9,2) as Day FROM '.sql_table('item')
 574          . ' WHERE iblog=' . $this->getID()
 575          . ' and itime <=' . mysqldate($this->getCorrectTime())    // don't show future items!
 576          . ' and idraft=0'; // don't show draft items

 577  
 578          if ($catid)
 579              $query .= ' and icat=' . intval($catid);
 580  
 581          $query .= ' GROUP BY Year';
 582          if ($mode == 'month' || $mode == 'day')
 583              $query .= ', Month';
 584          if ($mode == 'day')
 585              $query .= ', Day';
 586  
 587          $query .= ' ORDER BY itime DESC';
 588  
 589          if ($limit > 0)
 590              $query .= ' LIMIT ' . intval($limit);
 591  
 592          $res = sql_query($query);
 593  
 594          while ($current = sql_fetch_object($res)) {
 595              $current->itime = strtotime($current->itime);    // string time -> unix timestamp

 596  
 597              if ($mode == 'day') {
 598                  $archivedate = date('Y-m-d',$current->itime);
 599                  $archive['day'] = date('d',$current->itime);
 600                  $data['day'] = date('d',$current->itime);
 601                  $data['month'] = date('m',$current->itime);
 602                  $archive['month'] = $data['month'];
 603              } elseif ($mode == 'year') {
 604                  $archivedate = date('Y',$current->itime);
 605                  $data['day'] = '';
 606                  $data['month'] = '';
 607                  $archive['day'] = '';
 608                  $archive['month'] = '';
 609              } else {
 610                  $archivedate = date('Y-m',$current->itime);
 611                  $data['month'] = date('m',$current->itime);
 612                  $archive['month'] = $data['month'];
 613                  $data['day'] = '';
 614                  $archive['day'] = '';
 615              }
 616  
 617              $data['year'] = date('Y',$current->itime);
 618              $archive['year'] = $data['year'];
 619              $data['archivelink'] = createArchiveLink($this->getID(),$archivedate,$linkparams);
 620  
 621              $manager->notify(
 622                  'PreArchiveListItem',
 623                  array(
 624                      'listitem' => &$data
 625                  )
 626              );
 627  
 628              $temp = TEMPLATE::fill($template['ARCHIVELIST_LISTITEM'],$data);
 629              echo strftime($temp,$current->itime);
 630  
 631          }
 632  
 633          sql_free_result($res);
 634  
 635          $tplt = isset($template['ARCHIVELIST_FOOTER']) ? $template['ARCHIVELIST_FOOTER']
 636                                                         : '';
 637          echo TEMPLATE::fill($tplt, $data);
 638      }
 639  
 640  
 641      /**

 642        * Shows the list of categories using a given template

 643        */
 644  	function showCategoryList($template) {
 645          global $CONF, $manager;
 646  
 647          // determine arguments next to catids

 648          // I guess this can be done in a better way, but it works

 649          global $archive, $archivelist;
 650  
 651          $linkparams = array();
 652          if ($archive) {
 653              $blogurl = createArchiveLink($this->getID(), $archive, '');
 654              $linkparams['blogid'] = $this->getID();
 655              $linkparams['archive'] = $archive;
 656          } else if ($archivelist) {
 657              $blogurl = createArchiveListLink($this->getID(), '');
 658              $linkparams['archivelist'] = $archivelist;
 659          } else {
 660              $blogurl = createBlogidLink($this->getID(), '');
 661              $linkparams['blogid'] = $this->getID();
 662          }
 663  
 664          //$blogurl = $this->getURL() . $qargs;

 665          //$blogurl = createBlogLink($this->getURL(), $linkparams);

 666  
 667          $template =& $manager->getTemplate($template);
 668  
 669          echo TEMPLATE::fill((isset($template['CATLIST_HEADER']) ? $template['CATLIST_HEADER'] : null),
 670                              array(
 671                                  'blogid' => $this->getID(),
 672                                  'blogurl' => $blogurl,
 673                                  'self' => $CONF['Self']
 674                              ));
 675  
 676          $query = 'SELECT catid, cdesc as catdesc, cname as catname FROM '.sql_table('category').' WHERE cblog=' . $this->getID() . ' ORDER BY cname ASC';
 677          $res = sql_query($query);
 678  
 679  
 680          while ($data = sql_fetch_assoc($res)) {
 681              $data['blogid'] = $this->getID();
 682              $data['blogurl'] = $blogurl;
 683              $data['catlink'] = createLink(
 684                                  'category',
 685                                  array(
 686                                      'catid' => $data['catid'],
 687                                      'name' => $data['catname'],
 688                                      'extra' => $linkparams
 689                                  )
 690                                 );
 691              $data['self'] = $CONF['Self'];
 692              
 693              //catiscurrent

 694              if ($this->getSelectedCategory()) {
 695                  if ($this->getSelectedCategory() == $data['catid']) {
 696                      $data['catiscurrent'] = 'yes';
 697                      $data['currentcat'] = 'yes';
 698                  }
 699                  else {
 700                      $data['catiscurrent'] = 'no';
 701                      $data['currentcat'] = 'no';
 702                  }
 703              }
 704              else {
 705                  global $itemid;
 706                  if (intval($itemid) && $manager->existsItem(intval($itemid),0,0)) {
 707                      $iobj =& $manager->getItem(intval($itemid),0,0);
 708                      $cid = $iobj['catid'];
 709                      if ($cid == $data['catid']) {
 710                          $data['catiscurrent'] = 'yes';
 711                          $data['currentcat'] = 'yes';
 712                      }
 713                      else {
 714                          $data['catiscurrent'] = 'no';
 715                          $data['currentcat'] = 'no';
 716                      }
 717                  }
 718              }
 719  
 720              $manager->notify(
 721                  'PreCategoryListItem',
 722                  array(
 723                      'listitem' => &$data
 724                  )
 725              );
 726  
 727              echo TEMPLATE::fill((isset($template['CATLIST_LISTITEM']) ? $template['CATLIST_LISTITEM'] : null), $data);
 728              //$temp = TEMPLATE::fill((isset($template['CATLIST_LISTITEM']) ? $template['CATLIST_LISTITEM'] : null), $data);

 729              //echo strftime($temp, $current->itime);

 730  
 731          }
 732  
 733          sql_free_result($res);
 734  
 735          echo TEMPLATE::fill((isset($template['CATLIST_FOOTER']) ? $template['CATLIST_FOOTER'] : null),
 736                              array(
 737                                  'blogid' => $this->getID(),
 738                                  'blogurl' => $blogurl,
 739                                  'self' => $CONF['Self']
 740                              ));
 741      }
 742  
 743      /**

 744        * Shows a list of all blogs in the system using a given template

 745        * ordered by     number, name, shortname or description

 746        * in ascending or descending order

 747        */
 748  	function showBlogList($template, $bnametype, $orderby, $direction) {
 749          global $CONF, $manager;
 750  
 751          switch ($orderby) {
 752              case 'number':
 753                  $orderby='bnumber';
 754                  break;
 755              case 'name':
 756                  $orderby='bname';
 757                  break;
 758              case 'shortname':
 759                  $orderby='bshortname';
 760                  break;
 761              case 'description':
 762                  $orderby='bdesc';
 763                  break;
 764              default:
 765                  $orderby='bnumber';
 766                  break;
 767          }
 768  
 769          $direction=strtolower($direction);
 770          switch ($direction) {
 771              case 'asc':
 772                  $direction='ASC';
 773                  break;
 774              case 'desc':
 775                  $direction='DESC';
 776                  break;
 777              default:
 778                  $direction='ASC';
 779                  break;
 780          }
 781  
 782          $template =& $manager->getTemplate($template);
 783  
 784          echo TEMPLATE::fill((isset($template['BLOGLIST_HEADER']) ? $template['BLOGLIST_HEADER'] : null),
 785                              array(
 786                                  'sitename' => $CONF['SiteName'],
 787                                  'siteurl' => $CONF['IndexURL']
 788                              ));
 789  
 790          $query = 'SELECT bnumber, bname, bshortname, bdesc, burl FROM '.sql_table('blog').' ORDER BY '.$orderby.' '.$direction;
 791          $res = sql_query($query);
 792  
 793          while ($data = sql_fetch_assoc($res)) {
 794  
 795              $list = array();
 796  
 797  //            $list['bloglink'] = createLink('blog', array('blogid' => $data['bnumber']));

 798              $list['bloglink'] = createBlogidLink($data['bnumber']);
 799  
 800              $list['blogdesc'] = $data['bdesc'];
 801  
 802              $list['blogurl'] = $data['burl'];
 803  
 804              if ($bnametype=='shortname') {
 805                  $list['blogname'] = $data['bshortname'];
 806              }
 807              else { // all other cases
 808                  $list['blogname'] = $data['bname'];
 809              }
 810  
 811              $manager->notify(
 812                  'PreBlogListItem',
 813                  array(
 814                      'listitem' => &$list
 815                  )
 816              );
 817  
 818              echo TEMPLATE::fill((isset($template['BLOGLIST_LISTITEM']) ? $template['BLOGLIST_LISTITEM'] : null), $list);
 819  
 820          }
 821  
 822          sql_free_result($res);
 823  
 824          echo TEMPLATE::fill((isset($template['BLOGLIST_FOOTER']) ? $template['BLOGLIST_FOOTER'] : null),
 825                              array(
 826                                  'sitename' => $CONF['SiteName'],
 827                                  'siteurl' => $CONF['IndexURL']
 828                              ));
 829  
 830      }
 831  
 832      /**

 833        * Blogsettings functions

 834        */
 835  
 836  	function readSettings() {
 837          $query =  'SELECT *'
 838                 . ' FROM '.sql_table('blog')
 839                 . ' WHERE bnumber=' . $this->blogid;
 840          $res = sql_query($query);
 841  
 842          $this->isValid = (sql_num_rows($res) > 0);
 843          if (!$this->isValid)
 844              return;
 845  
 846          $this->settings = sql_fetch_assoc($res);
 847      }
 848  
 849  	function writeSettings() {
 850  
 851          // (can't use floatval since not available prior to PHP 4.2)

 852          $offset = $this->getTimeOffset();
 853          if (!is_float($offset))
 854              $offset = intval($offset);
 855  
 856          $query =  'UPDATE '.sql_table('blog')
 857                 . " SET bname='" . addslashes($this->getName()) . "',"
 858                 . "     bshortname='". addslashes($this->getShortName()) . "',"
 859                 . "     bcomments=". intval($this->commentsEnabled()) . ","
 860                 . "     bmaxcomments=" . intval($this->getMaxComments()) . ","
 861                 . "     btimeoffset=" . $offset . ","
 862                 . "     bpublic=" . intval($this->isPublic()) . ","
 863                 . "     breqemail=" . intval($this->emailRequired()) . ","
 864                 . "     bconvertbreaks=" . intval($this->convertBreaks()) . ","
 865                 . "     ballowpast=" . intval($this->allowPastPosting()) . ","
 866                 . "     bnotify='" . addslashes($this->getNotifyAddress()) . "',"
 867                 . "     bnotifytype=" . intval($this->getNotifyType()) . ","
 868                 . "     burl='" . addslashes($this->getURL()) . "',"
 869                 . "     bupdate='" . addslashes($this->getUpdateFile()) . "',"
 870                 . "     bdesc='" . addslashes($this->getDescription()) . "',"
 871                 . "     bdefcat=" . intval($this->getDefaultCategory()) . ","
 872                 . "     bdefskin=" . intval($this->getDefaultSkin()) . ","
 873                 . "     bincludesearch=" . intval($this->getSearchable())
 874                 . " WHERE bnumber=" . intval($this->getID());
 875          sql_query($query);
 876  
 877      }
 878  
 879  
 880  
 881      // update update file if requested

 882  	function updateUpdatefile() {
 883           if ($this->getUpdateFile()) {
 884              $f_update = fopen($this->getUpdateFile(),'w');
 885              fputs($f_update,$this->getCorrectTime());
 886              fclose($f_update);
 887           }
 888  
 889      }
 890  
 891  	function isValidCategory($catid) {
 892          $query = 'SELECT * FROM '.sql_table('category').' WHERE cblog=' . $this->getID() . ' and catid=' . intval($catid);
 893          $res = sql_query($query);
 894          return (sql_num_rows($res) != 0);
 895      }
 896  
 897  	function getCategoryName($catid) {
 898          $res = sql_query('SELECT cname FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and catid=' . intval($catid));
 899          $o = sql_fetch_object($res);
 900          return $o->cname;
 901      }
 902  
 903  	function getCategoryDesc($catid) {
 904          $res = sql_query('SELECT cdesc FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and catid=' . intval($catid));
 905          $o = sql_fetch_object($res);
 906          return $o->cdesc;
 907      }
 908  
 909  	function getCategoryIdFromName($name) {
 910          $res = sql_query('SELECT catid FROM '.sql_table('category').' WHERE cblog='.$this->getID().' and cname="' . addslashes($name) . '"');
 911          if (sql_num_rows($res) > 0) {
 912              $o = sql_fetch_object($res);
 913              return $o->catid;
 914          } else {
 915              return $this->getDefaultCategory();
 916          }
 917      }
 918  
 919  	function convertBreaks() {
 920          return $this->getSetting('bconvertbreaks');
 921      }
 922  
 923  	function insertJavaScriptInfo($authorid = '') {
 924          global $member, $CONF;
 925  
 926          if ($authorid == '')
 927              $authorid = $member->getID();
 928  
 929          ?>
 930          <script type="text/javascript">
 931              setConvertBreaks(<?php echo  $this->convertBreaks() ? 'true' : 'false' ?>);
 932              setMediaUrl("<?php echo $CONF['MediaURL']?>");
 933              setAuthorId(<?php echo $authorid?>);
 934          </script><?php    }
 935  
 936  	function setConvertBreaks($val) {
 937          $this->setSetting('bconvertbreaks',$val);
 938      }
 939  	function setAllowPastPosting($val) {
 940          $this->setSetting('ballowpast',$val);
 941      }
 942  	function allowPastPosting() {
 943          return $this->getSetting('ballowpast');
 944      }
 945  
 946  	function getCorrectTime($t=0) {
 947          if ($t == 0) $t = time();
 948          return ($t + 3600 * $this->getTimeOffset());
 949      }
 950  
 951  	function getName() {
 952          return $this->getSetting('bname');
 953      }
 954  
 955  	function getShortName() {
 956          return $this->getSetting('bshortname');
 957      }
 958  
 959  	function getMaxComments() {
 960          return $this->getSetting('bmaxcomments');
 961      }
 962  
 963  	function getNotifyAddress() {
 964          return $this->getSetting('bnotify');
 965      }
 966  
 967  	function getNotifyType() {
 968          return $this->getSetting('bnotifytype');
 969      }
 970  
 971  	function notifyOnComment() {
 972          $n = $this->getNotifyType();
 973          return (($n != 0) && (($n % 3) == 0));
 974      }
 975  
 976  	function notifyOnVote() {
 977          $n = $this->getNotifyType();
 978          return (($n != 0) && (($n % 5) == 0));
 979      }
 980  
 981  	function notifyOnNewItem() {
 982          $n = $this->getNotifyType();
 983          return (($n != 0) && (($n % 7) == 0));
 984      }
 985  
 986  	function setNotifyType($val) {
 987          $this->setSetting('bnotifytype',$val);
 988      }
 989  
 990  
 991  	function getTimeOffset() {
 992          return $this->getSetting('btimeoffset');
 993      }
 994  
 995  	function commentsEnabled() {
 996          return $this->getSetting('bcomments');
 997      }
 998  
 999  	function getURL() {
1000          return $this->getSetting('burl');
1001      }
1002  
1003  	function getDefaultSkin() {
1004          return $this->getSetting('bdefskin');
1005      }
1006  
1007  	function getUpdateFile() {
1008          return $this->getSetting('bupdate');
1009      }
1010  
1011  	function getDescription() {
1012          return $this->getSetting('bdesc');
1013      }
1014  
1015  	function isPublic() {
1016          return $this->getSetting('bpublic');
1017      }
1018  
1019  	function emailRequired() {
1020          return $this->getSetting('breqemail');
1021      }
1022  
1023  	function getSearchable() {
1024          return $this->getSetting('bincludesearch');
1025      }
1026  
1027  	function getDefaultCategory() {
1028          return $this->getSetting('bdefcat');
1029      }
1030  
1031  	function setPublic($val) {
1032          $this->setSetting('bpublic',$val);
1033      }
1034  
1035  	function setSearchable($val) {
1036          $this->setSetting('bincludesearch',$val);
1037      }
1038  
1039  	function setDescription($val) {
1040          $this->setSetting('bdesc',$val);
1041      }
1042  
1043  	function setUpdateFile($val) {
1044          $this->setSetting('bupdate',$val);
1045      }
1046  
1047  	function setDefaultSkin($val) {
1048          $this->setSetting('bdefskin',$val);
1049      }
1050  
1051  	function setURL($val) {
1052          $this->setSetting('burl',$val);
1053      }
1054  
1055  	function setName($val) {
1056          $this->setSetting('bname',$val);
1057      }
1058  
1059  	function setShortName($val) {
1060          $this->setSetting('bshortname',$val);
1061      }
1062  
1063  	function setCommentsEnabled($val) {
1064          $this->setSetting('bcomments',$val);
1065      }
1066  
1067  	function setMaxComments($val) {
1068          $this->setSetting('bmaxcomments',$val);
1069      }
1070  
1071  	function setNotifyAddress($val) {
1072          $this->setSetting('bnotify',$val);
1073      }
1074  
1075  	function setEmailRequired($val) {
1076          $this->setSetting('breqemail',$val);
1077      }
1078  
1079  	function setTimeOffset($val) {
1080          // check validity of value

1081          // 1. replace , by . (common mistake)

1082          $val = str_replace(',','.',$val);
1083          // 2. cast to float or int

1084          if (is_numeric($val) && strstr($val,'.5')) {
1085              $val = (float) $val;
1086          } else {
1087              $val = intval($val);
1088          }
1089  
1090          $this->setSetting('btimeoffset',$val);
1091      }
1092  
1093  	function setDefaultCategory($val) {
1094          $this->setSetting('bdefcat',$val);
1095      }
1096  
1097  	function getSetting($key) {
1098          return $this->settings[$key];
1099      }
1100  
1101  	function setSetting($key,$value) {
1102          $this->settings[$key] = $value;
1103      }
1104  
1105  
1106      // tries to add a member to the team. Returns false if the member was already on

1107      // the team

1108  	function addTeamMember($memberid, $admin) {
1109          global $manager;
1110  
1111          $memberid = intval($memberid);
1112          $admin = intval($admin);
1113  
1114          // check if member is already a member

1115          $tmem = MEMBER::createFromID($memberid);
1116  
1117          if ($tmem->isTeamMember($this->getID()))
1118              return 0;
1119  
1120          $manager->notify(
1121              'PreAddTeamMember',
1122              array(
1123                  'blog' => &$this,
1124                  'member' => &$tmem,
1125                  'admin' => &$admin
1126              )
1127          );
1128  
1129          // add to team

1130          $query = 'INSERT INTO '.sql_table('team').' (TMEMBER, TBLOG, TADMIN) '
1131                 . 'VALUES (' . $memberid .', '.$this->getID().', "'.$admin.'")';
1132          sql_query($query);
1133  
1134          $manager->notify(
1135              'PostAddTeamMember',
1136              array(
1137                  'blog' => &$this,
1138                  'member' => &$tmem,
1139                  'admin' => $admin
1140              )
1141  
1142          );
1143  
1144          $logMsg = sprintf(_TEAM_ADD_NEWTEAMMEMBER, $tmem->getDisplayName(), $memberid, $this->getName());
1145          ACTIONLOG::add(INFO, $logMsg);
1146  
1147          return 1;
1148      }
1149  
1150  	function getID() {
1151          return intVal($this->blogid);
1152      }
1153  
1154      // returns true if there is a blog with the given shortname (static)

1155  	function exists($name) {
1156          $r = sql_query('select * FROM '.sql_table('blog').' WHERE bshortname="'.addslashes($name).'"');
1157          return (sql_num_rows($r) != 0);
1158      }
1159  
1160      // returns true if there is a blog with the given ID (static)

1161  	function existsID($id) {
1162          $r = sql_query('select * FROM '.sql_table('blog').' WHERE bnumber='.intval($id));
1163          return (sql_num_rows($r) != 0);
1164      }
1165  
1166          // flag there is a future post pending

1167          function setFuturePost() {
1168          $query =  'UPDATE '.sql_table('blog')
1169                 . " SET bfuturepost='1' WHERE bnumber=" . $this->getID();
1170          sql_query($query);
1171          }
1172  
1173      // clear there is a future post pending

1174  	function clearFuturePost() {
1175          $query =  'UPDATE '.sql_table('blog')
1176                 . " SET bfuturepost='0' WHERE bnumber=" . $this->getID();
1177          sql_query($query);
1178      }
1179  
1180      // check if we should throw justPosted event

1181  	function checkJustPosted() {
1182          global $manager;
1183  
1184          if ($this->settings['bfuturepost'] == 1) {
1185              $blogid = $this->getID();
1186              $result = sql_query("SELECT * FROM " . sql_table('item')
1187                        . " WHERE iposted=0 AND iblog=" . $blogid . " AND itime<NOW()");
1188              if (sql_num_rows($result) > 0) {
1189                  // This $pinged is allow a plugin to tell other hook to the event that a ping is sent already

1190                  // Note that the plugins's calling order is subject to thri order in the plugin list

1191                  $pinged = false;
1192                  $manager->notify(
1193                          'JustPosted',
1194                          array('blogid' => $blogid,
1195                          'pinged' => &$pinged
1196                          )
1197                  );
1198  
1199                  // clear all expired future posts

1200                  sql_query("UPDATE " . sql_table('item') . " SET iposted='1' WHERE iblog=" . $blogid . " AND itime<NOW()");
1201  
1202                  // check to see any pending future post, clear the flag is none

1203                  $result = sql_query("SELECT * FROM " . sql_table('item')
1204                            . " WHERE iposted=0 AND iblog=" . $blogid);
1205                  if (sql_num_rows($result) == 0) {
1206                      $this->clearFuturePost();
1207                  }
1208              }
1209          }
1210      }
1211  
1212      /**

1213       * Shows the given list of items for this blog

1214       *

1215       * @param $itemarray

1216       *        array of item numbers to be displayed

1217       * @param $template

1218       *        String representing the template _NAME_ (!)

1219       * @param $highlight

1220       *        contains a query that should be highlighted

1221       * @param $comments

1222       *        1=show comments 0=don't show comments

1223       * @param $dateheads

1224       *        1=show dateheads 0=don't show dateheads

1225       * @returns int

1226       *        amount of items shown

1227       */
1228  	function readLogFromList($itemarray, $template, $highlight = '', $comments = 1, $dateheads = 1) {
1229  
1230          $query = $this->getSqlItemList($itemarray);
1231  
1232          return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
1233      }
1234  
1235      /**

1236       * Returns the SQL query used to fill out templates for a list of items

1237       *

1238       * @param $itemarray

1239       *        an array holding the item numbers of the items to be displayed

1240       * @returns

1241       *        either a full SQL query, or an empty string

1242       * @note

1243       *        No LIMIT clause is added. (caller should add this if multiple pages are requested)

1244       */
1245  	function getSqlItemList($itemarray)
1246      {
1247          if (!is_array($itemarray)) return '';
1248          $items = array();
1249          foreach ($itemarray as $value) {
1250              if (intval($value)) $items[] = intval($value);
1251          }
1252          if (!count($items)) return '';
1253          //$itemlist = implode(',',$items);

1254          $i = count($items);
1255          $query = '';
1256          foreach ($items as $value) {
1257              $query .= '('
1258                      .    'SELECT'
1259                      .    ' i.inumber as itemid,'
1260                      .    ' i.ititle as title,'
1261                      .    ' i.ibody as body,'
1262                      .    ' m.mname as author,'
1263                      .    ' m.mrealname as authorname,'
1264                      .    ' i.itime,'
1265                      .    ' i.imore as more,'
1266                      .    ' m.mnumber as authorid,'
1267                      .    ' m.memail as authormail,'
1268                      .    ' m.murl as authorurl,'
1269                      .    ' c.cname as category,'
1270                      .    ' i.icat as catid,'
1271                      .    ' i.iclosed as closed';
1272  
1273              $query .= ' FROM '
1274                      . sql_table('item') . ' as i, '
1275                      . sql_table('member') . ' as m, '
1276                      . sql_table('category') . ' as c'
1277                      . ' WHERE'
1278                      .    ' i.iblog='.$this->blogid
1279                     . ' and i.iauthor=m.mnumber'
1280                     . ' and i.icat=c.catid'
1281                     . ' and i.idraft=0'    // exclude drafts
1282                          // don't show future items

1283                     . ' and i.itime<=' . mysqldate($this->getCorrectTime());
1284  
1285              //$query .= ' and i.inumber IN ('.$itemlist.')';

1286              $query .= ' and i.inumber='.intval($value);
1287              $query .= ')';
1288              $i--;
1289              if ($i) $query .= ' UNION ';
1290          }
1291  
1292          return $query;
1293      }
1294  
1295  }
1296  
1297  ?>


Generated: Sun Aug 1 03:56:06 2010
Open Source related documentation for developers.