4 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5 * Copyright (C) 2002-2012 The Nucleus Group
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)
14 * A class representing a blog and containing functions to get that blog shown
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 1624 2012-01-09 11:36:20Z sakamocchi $
22 if ( !function_exists('requestVar') ) exit;
23 require_once dirname(__FILE__) . '/ITEMACTIONS.php';
30 // After creating an object of the blog class, contains true if the BLOG object is
31 // valid (the blog exists)
34 // associative array, containing all blogsettings (use the get/set functions instead)
37 // ID of currently selected category
38 private $selectedcatid;
42 * Creates a new BLOG object for the given blog
44 * @param integer $id blogid
47 public function __construct($id)
51 $this->blogid = (integer) $id;
52 $this->readSettings();
53 $this->setSelectedCategory($catid);
59 * Shows the given amount of items for this blog
61 * @param string $template String representing the template _NAME_ (!)
62 * @param integer $amountEntries amount of entries to show
63 * @param integer $startpos offset from where items should be shown (e.g. 5 = start at fifth item)
64 * @return integer amount of items shown
66 public function readLog($template, $amountEntries, $offset = 0, $startpos = 0)
68 return $this->readLogAmount($template,$amountEntries,'','',1,1,$offset, $startpos);
73 * Shows an archive for a given month
75 * @param integer $year year
76 * @param integer $month month
77 * @param string $template String representing the template name to be used
80 public function showArchive($templatename, $year, $month=0, $day=0)
82 // create extra where clause for select query
83 if ( $day == 0 && $month != 0 )
85 $timestamp_start = mktime(0,0,0,$month,1,$year);
86 // also works when $month==12
87 $timestamp_end = mktime(0,0,0,$month+1,1,$year);
89 elseif ( $month == 0 )
91 $timestamp_start = mktime(0,0,0,1,1,$year);
92 // also works when $month==12
93 $timestamp_end = mktime(0,0,0,12,31,$year);
97 $timestamp_start = mktime(0,0,0,$month,$day,$year);
98 $timestamp_end = mktime(0,0,0,$month,$day+1,$year);
100 $extra_query = " and i.itime>=%s and i.itime<%s";
101 $extra_query = sprintf($extra_query, DB::formatDateTime($timestamp_start), DB::formatDateTime($timestamp_end));
103 $this->readLogAmount($templatename,0,$extra_query,'',1,1);
108 * Blog::setSelectedCategory()
109 * Sets the selected category by id (only when category exists)
111 * @param integer $catid ID for category
114 public function setSelectedCategory($catid)
116 if ( $this->isValidCategory($catid) || (intval($catid) == 0) )
118 $this->selectedcatid = intval($catid);
124 * Blog::setSelectedCategoryByName()
125 * Sets the selected category by name
127 * @param string $catname name of category
130 public function setSelectedCategoryByName($catname)
132 $this->setSelectedCategory($this->getCategoryIdFromName($catname));
137 * Blog::getSelectedCategory()
138 * Returns the selected category
143 public function getSelectedCategory()
145 return $this->selectedcatid;
149 * Shows the given amount of items for this blog
151 * @param string $template string representing the template _NAME_ (!)
152 * @param integer $amountEntries amount of entries to show (0 = no limit)
153 * @param string $extraQuery extra conditions to be added to the query
154 * @param string $highlight contains a query that should be highlighted
155 * @param integer $comments 1=show comments 0=don't show comments
156 * @param integer $dateheads 1=show dateheads 0=don't show dateheads
157 * @param integer $offset offset
158 * @return integer amount of items shown
160 private function readLogAmount($template, $amountEntries, $extraQuery, $highlight, $comments, $dateheads, $offset = 0, $startpos = 0)
162 $query = $this->getSqlBlog($extraQuery);
164 if ( $amountEntries > 0 )
166 // $offset zou moeten worden:
167 // (($startpos / $amountentries) + 1) * $offset ... later testen ...
168 $query .= ' LIMIT ' . intval($startpos + $offset).',' . intval($amountEntries);
170 return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
174 * Blog::showUsingQuery()
175 * Do the job for readLogAmmount
177 * @param string $templateName template name
178 * @param string $query string for query
179 * @param string $highlight string to be highlighted
180 * @param integer $comments the number of comments
181 * @param boolean $dateheads date header is needed or not
182 * @return integer the number of rows as a result of mysql query
184 private function showUsingQuery($templateName, $query, $highlight = '', $comments = 0, $dateheads = 1)
186 global $CONF, $manager, $currentTemplateName;
188 $lastVisit = cookieVar($CONF['CookiePrefix'] .'lastVisit');
189 if ( $lastVisit != 0 )
191 $lastVisit = $this->getCorrectTime($lastVisit);
194 // set templatename as global variable (so plugins can access it)
195 $currentTemplateName = $templateName;
196 $template =& $manager->getTemplate($templateName);
198 // create parser object & action handler
199 $handler = new ItemActions($this);
200 $handler->setTemplate($template);
201 $handler->setHighlight($highlight);
202 $handler->setLastVisit($lastVisit);
203 $handler->setShowComments($comments);
205 $parser = new Parser($handler);
208 $items = DB::getResult($query);
210 // loop over all items
212 foreach ( $items as $item )
214 // string timestamp -> unix timestamp
215 $item['timestamp'] = strtotime($item['itime']);
217 // action handler needs to know the item we're handling
218 $handler->setCurrentItem($item);
220 // add date header if needed
223 $new_date = date('dFY', $item['timestamp']);
224 if ( $new_date != $old_date )
226 // unless this is the first time, write date footer
227 $timestamp = $item['timestamp'];
228 if ( $old_date != 0 )
230 $oldTS = strtotime($old_date);
231 $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
233 if ( !in_array('DATE_FOOTER', $template) || empty($template['DATE_FOOTER']) )
239 $tmp_footer = i18n::formatted_datetime($template['DATE_FOOTER'], $oldTS);
241 $parser->parse($tmp_footer);
242 $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => $oldTS));
245 $manager->notify('PreDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
247 // note, to use templatvars in the dateheader, the %-characters need to be doubled in
248 // order to be preserved by strftime
249 if ( !in_array('DATE_HEADER', $template) || empty($template['DATE_HEADER']) )
255 $tmp_header = i18n::formatted_datetime($template['DATE_HEADER'], $timestamp);
257 $parser->parse($tmp_header);
258 $manager->notify('PostDateHead',array('blog' => &$this, 'timestamp' => $timestamp));
260 $old_date = $new_date;
264 $parser->parse($template['ITEM_HEADER']);
265 $manager->notify('PreItem', array('blog' => &$this, 'item' => &$item));
266 $parser->parse($template['ITEM']);
267 $manager->notify('PostItem', array('blog' => &$this, 'item' => &$item));
268 $parser->parse($template['ITEM_FOOTER']);
271 $numrows = $items->rowCount();
273 // add another date footer if there was at least one item
274 if ( ($numrows > 0) && $dateheads )
276 $manager->notify('PreDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
277 $parser->parse($template['DATE_FOOTER']);
278 $manager->notify('PostDateFoot',array('blog' => &$this, 'timestamp' => strtotime($old_date)));
281 $items->closeCursor();
286 * Blog::showOneitem()
287 * Simplified function for showing only one item
289 * @param integer $itemid ID for item
290 * @param array $template template for item
291 * @param string $highlight string for highlight
294 public function showOneitem($itemid, $template, $highlight)
296 $extraQuery = ' and inumber=' . intval($itemid);
298 return $this->readLogAmount($template, 1, $extraQuery, $highlight, 0, 0);
303 * Adds an item to this blog
305 * @param integer $catid ID for category
306 * @param string $title ID for
307 * @param string $body text for body
308 * @param string $more text for more
309 * @param integer $blogid ID for blog
310 * @param integer $authorid ID for author
311 * @param timestamp $timestamp UNIX timestamp for post
312 * @param boolean $closed opened or closed
313 * @param boolean $draft draft or not
314 * @param boolean $posted posted or not
315 * @return integer ID for added item
317 function additem($catid, $title, $body, $more, $blogid, $authorid, $timestamp, $closed, $draft, $posted='1')
321 $blogid = (integer) $blogid;
322 $authorid = (integer) $authorid;
326 $catid = intval($catid);
328 // convert newlines to <br />
329 if ( $this->convertBreaks() )
331 $body = addBreaks($body);
332 $more = addBreaks($more);
335 if ( $closed != '1' )
344 if ( !$this->isValidCategory($catid) )
346 $catid = $this->getDefaultCategory();
350 if ( $timestamp > $this->getCorrectTime() )
355 $timestamp = date('Y-m-d H:i:s',$timestamp);
357 $manager->notify('PreAddItem',array('title' => &$title, 'body' => &$body, 'more' => &$more, 'blog' => &$this, 'authorid' => &$authorid, 'timestamp' => &$timestamp, 'closed' => &$closed, 'draft' => &$draft, 'catid' => &$catid));
359 $ititle = DB::quoteValue($title);
360 $ibody = DB::quoteValue($body);
361 $imore = DB::quoteValue($more);
362 $timestamp = DB::formatDateTime(strtotime($timestamp));
364 $query = "INSERT INTO %s (ITITLE, IBODY, IMORE, IBLOG, IAUTHOR, ITIME, ICLOSED, IDRAFT, ICAT, IPOSTED) VALUES (%s, %s, %s, %d, %d, %s, %s, %s, %s, %s)";
365 $query = sprintf($query, sql_table('item'), $ititle, $ibody, $imore, $blogid, $authorid, $timestamp, $closed, $draft, $catid, $posted);
367 $itemid = DB::getInsertId();
369 $manager->notify('PostAddItem',array('itemid' => $itemid));
373 $this->updateUpdateFile();
375 // send notification mail
376 if ( !$draft && !$isFuture && $this->getNotifyAddress() && $this->notifyOnNewItem() )
378 $this->sendNewItemNotification($itemid, $title, $body);
384 * Blog::sendNewItemNotification()
385 * Send a new item notification to the notification list
387 * @param string $itemid ID of the item
388 * @param string $title title of the item
389 * @param string $body body of the item
392 public function sendNewItemNotification($itemid, $title, $body)
394 global $CONF, $member;
396 $ascii = Entity::anchor_footnoting($body);
398 $message = _NOTIFY_NI_MSG . " \n";
399 $temp = parse_url($CONF['Self']);
400 if ( $temp['scheme'] )
402 $message .= Link::create_item_link($itemid) . "\n\n";
406 $tempurl = $this->getURL();
407 if ( i18n::substr($tempurl, -1) == '/' || i18n::substr($tempurl, -4) == '.php' )
409 $message .= $tempurl . '?itemid=' . $itemid . "\n\n";
413 $message .= $tempurl . '/?itemid=' . $itemid . "\n\n";
416 $message .= _NOTIFY_TITLE . ' ' . strip_tags($title) . "\n";
417 $message .= _NOTIFY_CONTENTS . "\n " . $ascii . "\n";
418 $message .= NOTIFICATION::get_mail_footer();
420 $subject = $this->getName() . ': ' . _NOTIFY_NI_TITLE;
422 $from = $member->getNotifyFromMailAddress();
424 NOTIFICATION::mail($this->getNotifyAddress(), $subject, $message, $from, i18n::get_current_charset());
429 * Blog::createNewCategory()
430 * Creates a new category for this blog
432 * @param string $catName name of the new category. When empty, a name is generated automatically (starting with newcat)
433 * @param string $catDescription description of the new category. Defaults to 'New Category'
434 * @return integer ID for new category on success. 0 on failure
436 public function createNewCategory($catName = '', $catDescription = _CREATED_NEW_CATEGORY_DESC)
438 global $member, $manager;
440 if ( !$member->blogAdminRights($this->blogid) )
446 if ( $catName == '' )
448 $catName = _CREATED_NEW_CATEGORY_NAME;
451 $res = DB::getResult('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->blogid);
452 while ( $res->rowCount() > 0 )
455 $res = DB::getResult('SELECT * FROM '.sql_table('category')." WHERE cname='".$catName.$i."' and cblog=".$this->blogid);
458 $catName = $catName . $i;
464 'description' => $catDescription
466 $manager->notify('PreAddCategory', $data);
468 $query = "INSERT INTO %s (cblog, cname, cdesc) VALUES (%d, %s, %s)";
469 $query = sprintf($query, sql_table('category'), (integer) $this->blogid, DB::quoteValue($catName), DB::quoteValue($catDescription));
471 $catid = DB::getInsertId();
476 'description' => $catDescription,
479 $manager->notify('PostAddCategory', $data);
486 * Searches all months of this blog for the given query
488 * @param string $query search query
489 * @param array $template template to be used (__NAME__ of the template)
490 * @param integer $amountMonths max amount of months to be search (0 = all)
491 * @param integer $maxresults max number of results to show
492 * @param integer $startpos offset
493 * @return amount of hits found
495 public function search($query, $template, $amountMonths, $maxresults, $startpos) {
496 global $CONF, $manager;
499 $sqlquery = $this->getSqlSearch($query, $amountMonths, $highlight);
501 if ( $sqlquery == '' )
503 // no query -> show everything
505 $amountfound = $this->readLogAmount($template, $maxresults, $extraQuery, $query, 1, 1);
509 // add LIMIT to query (to split search results into pages)
510 if ( intval($maxresults > 0) )
512 $sqlquery .= ' LIMIT ' . intval($startpos) . ',' . intval($maxresults);
516 $amountfound = $this->showUsingQuery($template, $sqlquery, $highlight, 1, 1);
518 // when no results were found, show a message
519 if ( $amountfound == 0 )
521 $template =& $manager->getTemplate($template);
523 'query' => Entity::hsc($query),
524 'blogid' => $this->blogid
526 echo Template::fill($template['SEARCH_NOTHINGFOUND'], $vars);
533 * Blog::getSqlSearch()
534 * Returns an SQL query to use for a search query
535 * No LIMIT clause is added. (caller should add this if multiple pages are requested)
537 * @param string $query search query
538 * @param integer $amountMonths amount of months to search back. Default = 0 = unlimited
539 * @param string $mode either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query
540 * @return string $highlight words to highlight (out parameter)
541 * @return string either a full SQL query, or an empty string (if querystring empty)
543 public function getSqlSearch($query, $amountMonths = 0, &$highlight, $mode = '')
545 $searchclass = new Search($query);
547 $highlight = $searchclass->inclusive;
549 // if querystring is empty, return empty string
550 if ( $searchclass->inclusive == '' )
555 $where = $searchclass->boolean_sql_where('ititle,ibody,imore');
556 $select = $searchclass->boolean_sql_select('ititle,ibody,imore');
558 // get list of blogs to search
559 $blogs = $searchclass->blogs; // array containing blogs that always need to be included
560 $blogs[] = $this->blogid; // also search current blog (duh)
561 $blogs = array_unique($blogs); // remove duplicates
563 if ( count($blogs) > 0 )
565 $selectblogs = ' and i.iblog in (' . implode(',', $blogs) . ')';
570 $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, i.itime, i.imore as more, i.icat as catid, i.iclosed as closed,
571 m.mname as author, m.mrealname as authorname, m.mnumber as authorid, m.memail as authormail, m.murl as authorurl,
572 c.cname as category';
576 $query .= ', '.$select. ' as score ';
581 $query = 'SELECT COUNT(*) as result ';
584 $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
585 . ' WHERE i.iauthor=m.mnumber'
586 . ' and i.icat=c.catid'
590 // don't show future items
591 . ' and i.itime<=' . DB::formatDateTime($this->getCorrectTime())
594 // take into account amount of months to search
595 if ( $amountMonths > 0 )
597 $localtime = getdate($this->getCorrectTime());
598 $timestamp_start = mktime(0,0,0,$localtime['mon'] - $amountMonths,1,$localtime['year']);
599 $query .= ' and i.itime>' . DB::formatDateTime($timestamp_start);
606 $query .= ' ORDER BY score DESC';
610 $query .= ' ORDER BY i.itime DESC ';
619 * Returns the SQL query that's normally used to display the blog items on the index type skins
620 * No LIMIT clause is added. (caller should add this if multiple pages are requested)
622 * @param string $extraQuery extra query string
623 * @param string $mode either empty, or 'count'. In this case, the query will be a SELECT COUNT(*) query
624 * @return string either a full SQL query, or an empty string
626 public function getSqlBlog($extraQuery, $mode = '')
630 $query = 'SELECT i.inumber as itemid, i.ititle as title, i.ibody as body, m.mname as author,
631 m.mrealname as authorname, i.itime, i.imore as more, m.mnumber as authorid, m.memail as authormail,
632 m.murl as authorurl, c.cname as category, i.icat as catid, i.iclosed as closed';
636 $query = 'SELECT COUNT(*) as result ';
639 $query .= ' FROM '.sql_table('item').' as i, '.sql_table('member').' as m, '.sql_table('category').' as c'
640 . ' WHERE i.iblog='.$this->blogid
641 . ' and i.iauthor=m.mnumber'
642 . ' and i.icat=c.catid'
643 . ' and i.idraft=0' // exclude drafts
644 . ' and i.itime<=' . DB::formatDateTime($this->getCorrectTime()); // don't show future items
646 if ( $this->selectedcatid )
648 $query .= ' and i.icat=' . $this->selectedcatid . ' ';
651 $query .= $extraQuery;
655 $query .= ' ORDER BY i.itime DESC';
661 * Blog::showArchiveList()
662 * Shows the archivelist using the given template
664 * @param string $template template name
665 * @param string $mode year/month/day
666 * @param integer $limit limit of record count
669 public function showArchiveList($template, $mode = 'month', $limit = 0)
671 global $CONF, $catid, $manager;
673 if ( !isset ($linkparams) )
675 $linkparams = array();
680 $linkparams = array('catid' => $catid);
683 $template =& $manager->getTemplate($template);
684 $data['blogid'] = $this->blogid;
686 if ( !array_key_exists('ARCHIVELIST_HEADER', $template) || !$template['ARCHIVELIST_HEADER'] )
692 $tplt = $template['ARCHIVELIST_HEADER'];
695 echo Template::fill($tplt, $data);
697 $query = 'SELECT itime, SUBSTRING(itime,1,4) AS Year, SUBSTRING(itime,6,2) AS Month, SUBSTRING(itime,9,2) AS Day'
698 . ' FROM '.sql_table('item')
699 . ' WHERE iblog=' . $this->blogid
700 . ' AND itime <=' . DB::formatDateTime($this->getCorrectTime()) // don't show future items!
701 . ' AND idraft=0'; // don't show draft items
705 $query .= ' and icat=' . intval($catid);
708 $query .= ' GROUP BY Year';
709 if ( $mode == 'month' || $mode == 'day' )
713 if ( $mode == 'day' )
718 $query .= ' ORDER BY itime DESC';
722 $query .= ' LIMIT ' . intval($limit);
725 $res = DB::getResult($query);
726 foreach ( $res as $current )
728 /* string time -> unix timestamp */
729 $current['itime'] = strtotime($current['itime']);
731 if ( $mode == 'day' )
733 $archivedate = date('Y-m-d',$current['itime']);
734 $archive['day'] = date('d',$current['itime']);
735 $data['day'] = date('d',$current['itime']);
736 $data['month'] = date('m',$current['itime']);
737 $archive['month'] = $data['month'];
739 elseif ( $mode == 'year' )
741 $archivedate = date('Y',$current['itime']);
744 $archive['day'] = '';
745 $archive['month'] = '';
749 $archivedate = date('Y-m',$current['itime']);
750 $data['month'] = date('m',$current['itime']);
751 $archive['month'] = $data['month'];
753 $archive['day'] = '';
756 $data['year'] = date('Y',$current['itime']);
757 $archive['year'] = $data['year'];
758 $data['archivelink'] = Link::create_archive_link($this->blogid,$archivedate,$linkparams);
760 $manager->notify('PreArchiveListItem', array('listitem' => &$data));
762 $temp = Template::fill($template['ARCHIVELIST_LISTITEM'],$data);
763 echo i18n::formatted_datetime($temp, $current['itime']);
769 if ( !array_key_exists('ARCHIVELIST_FOOTER', $template) || !$template['ARCHIVELIST_FOOTER'] )
775 $tplt = $template['ARCHIVELIST_FOOTER'];
778 echo Template::fill($tplt, $data);
783 * Blog::showCategoryList()
784 * Shows the list of categories using a given template
786 * @param string $template Template Name
789 public function showCategoryList($template)
791 global $CONF, $archive, $archivelist, $manager;
794 * determine arguments next to catids
795 * I guess this can be done in a better way, but it works
797 $linkparams = array();
800 $blogurl = Link::create_archive_link($this->blogid, $archive, '');
801 $linkparams['blogid'] = $this->blogid;
802 $linkparams['archive'] = $archive;
804 else if ( $archivelist )
806 $blogurl = Link::create_archivelist_link($this->blogid, '');
807 $linkparams['archivelist'] = $archivelist;
811 $blogurl = Link::create_blogid_link($this->blogid, '');
812 $linkparams['blogid'] = $this->blogid;
815 $template =& $manager->getTemplate($template);
817 //: Change: Set nocatselected variable
818 if ( $this->selectedcatid )
820 $nocatselected = 'no';
824 $nocatselected = 'yes';
828 'blogid' => $this->blogid,
829 'blogurl' => $blogurl,
830 'self' => $CONF['Self'],
831 'catiscurrent' => $nocatselected, // Change: Set catiscurrent template variable for header
832 'currentcat' => $nocatselected
835 /* output header of category list item */
836 if ( !array_key_exists('CATLIST_HEADER', $template) || empty($template['CATLIST_HEADER']) )
838 echo Template::fill(NULL, $args);
842 echo Template::fill($template['CATLIST_HEADER'], $args);
845 $query = "SELECT catid, cdesc as catdesc, cname as catname FROM %s WHERE cblog=%d ORDER BY cname ASC;";
846 $query = sprintf($query, sql_table('category'), (integer) $this->blogid);
847 $res = DB::getResult($query);
849 foreach ( $res as $data )
852 'catid' => $data['catid'],
853 'name' => $data['catname'],
854 'extra' => $linkparams
857 $data['blogid'] = $this->blogid;
858 $data['blogurl'] = $blogurl;
859 $data['catlink'] = Link::create_link('category', $args);
860 $data['self'] = $CONF['Self'];
862 // this gives catiscurrent = no when no category is selected.
863 $data['catiscurrent'] = 'no';
864 $data['currentcat'] = 'no';
866 if ( $this->selectedcatid )
868 if ( $this->selectedcatid == $data['catid'] )
870 $data['catiscurrent'] = 'yes';
871 $data['currentcat'] = 'yes';
877 if ( (integer) $itemid && $manager->existsItem((integer) $itemid, 0, 0) )
879 $iobj =& $manager->getItem($itemid, 0, 0);
880 $cid = $iobj['catid'];
882 if ( $cid == $data['catid'] )
884 $data['catiscurrent'] = 'yes';
885 $data['currentcat'] = 'yes';
890 $manager->notify('PreCategoryListItem', array('listitem' => &$data));
892 if ( !array_key_exists('CATLIST_LISTITEM', $template) || empty($template['CATLIST_LISTITEM']))
894 echo Template::fill(NULL, $data);
898 echo Template::fill($template['CATLIST_LISTITEM'], $data);
905 'blogid' => $this->blogid,
906 'blogurl' => $blogurl,
907 'self' => $CONF['Self'],
908 'catiscurrent' => $nocatselected, //: Change: Set catiscurrent template variable for footer
909 'currentcat' => $nocatselected
912 if ( !array_key_exists('CATLIST_FOOTER', $template) || empty($template['CATLIST_FOOTER']))
914 echo Template::fill(NULL, $args);
918 echo Template::fill($template['CATLIST_FOOTER'], $args);
925 * Blog::showBlogList()
926 * Shows a list of all blogs in the system using a given template
927 * ordered by number, name, shortname or description
928 * in ascending or descending order
930 * @param string $template tempalte name
931 * @param string $bnametype bname/bshortname
932 * @param string $orderby string for 'ORDER BY' SQL
933 * @param string $direction ASC/DESC
936 public function showBlogList($template, $bnametype, $orderby, $direction)
938 global $CONF, $manager;
949 $orderby='bshortname';
959 $direction=strtolower($direction);
960 switch ( $direction )
973 $template =& $manager->getTemplate($template);
975 if ( array_key_exists('BLOGLIST_HEADER', $template) && !empty($template['BLOGLIST_HEADER']) )
978 'sitename' => $CONF['SiteName'],
979 'siteurl' => $CONF['IndexURL']
982 echo Template::fill($template['BLOGLIST_HEADER'], $vars);
985 if ( array_key_exists('BLOGLIST_LISTITEM', $template) && !empty($template['BLOGLIST_LISTITEM']) )
987 $query = 'SELECT bnumber, bname, bshortname, bdesc, burl FROM '.sql_table('blog').' ORDER BY '.$orderby.' '.$direction;
988 $res = DB::getResult($query);
990 foreach ( $res as $data )
993 $list['bloglink'] = Link::create_blogid_link($data['bnumber']);
994 $list['blogdesc'] = $data['bdesc'];
995 $list['blogurl'] = $data['burl'];
997 if ( $bnametype == 'shortname' )
999 $list['blogname'] = $data['bshortname'];
1003 /* all other cases */
1004 $list['blogname'] = $data['bname'];
1007 $manager->notify('PreBlogListItem',array('listitem' => &$list));
1009 echo Template::fill($template['BLOGLIST_LISTITEM'], $list);
1012 $res->closeCursor();
1016 if ( array_key_exists('BLOGLIST_FOOTER', $template) && !empty($template['BLOGLIST_FOOTER']) )
1019 'sitename' => $CONF['SiteName'],
1020 'siteurl' => $CONF['IndexURL']
1022 echo Template::fill($template['BLOGLIST_FOOTER']);
1028 * Blog::readSettings()
1029 * Read the blog settings
1034 public function readSettings()
1036 $query = 'SELECT * FROM %s WHERE bnumber=%d;';
1037 $query = sprintf($query, sql_table('blog'), (integer) $this->blogid);
1038 $res = DB::getResult($query);
1040 $this->isValid = ($res->rowCount() > 0);
1041 if ( $this->isValid )
1043 $this->settings = $res->fetch(PDO::FETCH_ASSOC);
1049 * Blog::writeSettings()
1050 * Write the blog settings
1052 public function writeSettings()
1054 // (can't use floatval since not available prior to PHP 4.2)
1055 $offset = $this->getTimeOffset();
1056 if ( !is_float($offset) )
1058 $offset = (integer) $offset;
1061 $query = 'UPDATE '.sql_table('blog')
1062 . ' SET bname=' . DB::quoteValue($this->getName()) . ','
1063 . ' bshortname='. DB::quoteValue($this->getShortName()) . ','
1064 . ' bcomments='. intval($this->commentsEnabled()) . ','
1065 . ' bmaxcomments=' . intval($this->getMaxComments()) . ','
1066 . ' btimeoffset=' . $offset . ','
1067 . ' bpublic=' . intval($this->isPublic()) . ','
1068 . ' breqemail=' . intval($this->emailRequired()) . ','
1069 . ' bconvertbreaks=' . intval($this->convertBreaks()) . ','
1070 . ' ballowpast=' . intval($this->allowPastPosting()) . ','
1071 . ' bnotify=' . DB::quoteValue($this->getNotifyAddress()) . ','
1072 . ' bnotifytype=' . intval($this->getNotifyType()) . ','
1073 . ' burl=' . DB::quoteValue($this->getURL()) . ','
1074 . ' bupdate=' . DB::quoteValue($this->getUpdateFile()) . ','
1075 . ' bdesc=' . DB::quoteValue($this->getDescription()) . ','
1076 . ' bdefcat=' . intval($this->getDefaultCategory()) . ','
1077 . ' bdefskin=' . intval($this->getDefaultSkin()) . ','
1078 . ' bincludesearch=' . intval($this->getSearchable())
1079 . ' WHERE bnumber=' . intval($this->blogid);
1080 DB::execute($query);
1085 * Blog::updateUpdatefile()
1086 * Update the update file if requested
1091 public function updateUpdatefile()
1093 if ( $this->getUpdateFile() )
1095 $f_update = fopen($this->getUpdateFile(), 'w');
1096 fputs($f_update,$this->getCorrectTime());
1103 * Blog::isValidCategory()
1104 * Check if a category with a given catid is valid
1106 * @param integer $catid ID for category
1107 * @return boolean exists or not
1109 public function isValidCategory($catid)
1111 $query = 'SELECT * FROM %s WHERE cblog=%d and catid=%d;';
1112 $query = sprintf($query, sql_table('category'), (integer) $this->blogid, (integer) $catid);
1113 $res = DB::getResult($query);
1114 return ($res->rowCount() != 0);
1118 * Blog::getCategoryName()
1119 * Get the category name for a given catid
1121 * @param integer $catid ID for category
1122 * @return string name of category
1124 public function getCategoryName($catid)
1126 $query = 'SELECT cname FROM %s WHERE cblog=%d and catid=%d;';
1127 $query = sprintf($query, sql_table('category'), (integer) $this->blogid, (integer) $catid);
1128 $res = DB::getValue($query);
1133 * Blog::getCategoryDesc()
1134 * Get the category description for a given catid
1139 public function getCategoryDesc($catid)
1141 $query = 'SELECT cdesc FROM %s WHERE cblog=%d and catid=%d;';
1142 $query = sprintf($querym, sql_table('category'), (integer) $this->blogid, (integer) $catid);
1143 $res = DB::getValue();
1148 * Blog::getCategoryIdFromName
1149 * Get the category id for a given category name
1151 * @param string $name category name
1152 * @return ID for category
1154 public function getCategoryIdFromName($name)
1156 $query = 'SELECT catid FROM %s WHERE cblog=%d and cname=%s;';
1157 $query = sprintf($query, sql_table('category'), (integer) $this->blogid, DB::quoteValue($name));
1159 $res = DB::getValue();
1162 return $this->getDefaultCategory();
1168 * Blog::insertJavaScriptInfo()
1169 * Insert a javascript that includes information about the settings
1170 * of an author: ConvertBreaks, MediaUrl and AuthorId
1172 * @param $authorid id of the author
1174 public function insertJavaScriptInfo($authorid = '')
1176 global $member, $CONF;
1178 if ( $authorid == '' )
1180 $authorid = $member->getID();
1183 echo "<script type=\"text/javascript\">\n";
1185 if ( !$this->convertBreaks() )
1187 echo "setConvertBreaks(false);\n";
1191 echo "setConvertBreaks(true);\n";
1193 echo "setMediaUrl('{$CONF['MediaURL']}');\n";
1194 echo "setAuthorId('{$authorid}');\n";
1200 * Blog::setAllowPastPosting()
1201 * Set the the setting for allowing to publish postings in the past
1203 * @param boolean $val new value for ballowpast
1206 public function setAllowPastPosting($val)
1208 $this->setSetting('ballowpast', $val);
1213 * Blog::allowPastPosting()
1214 * Get the the setting if it is allowed to publish postings in the past
1215 * [should be named as getAllowPastPosting()]
1220 public function allowPastPosting()
1222 return $this->getSetting('ballowpast');
1226 * Blog::getCorrectTime()
1231 public function getCorrectTime($t=0)
1237 return ($t + 3600 * $this->getTimeOffset());
1244 * @return string name of this weblog
1246 public function getName()
1248 return $this->getSetting('bname');
1252 * Blog::getShortName()
1255 * @return string short name of this weblog
1257 public function getShortName()
1259 return $this->getSetting('bshortname');
1263 * Blog::getMaxComments()
1266 * @return integer maximum number of comments
1268 public function getMaxComments()
1270 return $this->getSetting('bmaxcomments');
1274 * Blog::getNotifyAddress()
1277 * @return string mail address for notifying
1279 public function getNotifyAddress()
1281 return $this->getSetting('bnotify');
1285 * Blog::getNotifyType()
1288 * @return integer notifycation type
1290 public function getNotifyType()
1292 return $this->getSetting('bnotifytype');
1296 * Blog::notifyOnComment()
1301 public function notifyOnComment()
1303 $n = $this->getNotifyType();
1304 return (($n != 0) && (($n % 3) == 0));
1308 * Blog::notifyOnVote()
1313 public function notifyOnVote()
1315 $n = $this->getNotifyType();
1316 return (($n != 0) && (($n % 5) == 0));
1320 * Blog::notifyOnNewItem()
1325 public function notifyOnNewItem()
1327 $n = $this->getNotifyType();
1328 return (($n != 0) && (($n % 7) == 0));
1332 * Blog::setNotifyType()
1334 * @param integer $val
1337 public function setNotifyType($val)
1339 $this->setSetting('bnotifytype',$val);
1344 * Blog::getTimeOffset()
1348 public function getTimeOffset()
1350 return $this->getSetting('btimeoffset');
1354 * Blog::commentsEnabled()
1356 * @return integer enabled or not
1358 public function commentsEnabled()
1360 return $this->getSetting('bcomments');
1366 * @return string URI for this weblog
1368 public function getURL()
1370 return $this->getSetting('burl');
1374 * Blog::getDefaultSkin()
1376 * @return name of skin as default for this weblog
1378 public function getDefaultSkin()
1380 return $this->getSetting('bdefskin');
1384 * Blog::getUpdateFile()
1386 * @return string name of file to be updated when weblog is updated
1388 public function getUpdateFile()
1390 return $this->getSetting('bupdate');
1394 * Blog::getDescription()
1396 * @return string description for this weblog
1398 public function getDescription()
1400 return $this->getSetting('bdesc');
1406 * @return integer publlic or not
1408 public function isPublic()
1410 return $this->getSetting('bpublic');
1414 * Blog::emailRequired()
1416 * @return integer email is required when posting comment or not
1418 public function emailRequired()
1420 return $this->getSetting('breqemail');
1424 * Blog::getSearchable()
1426 * @return integer searchable or not
1428 public function getSearchable()
1430 return $this->getSetting('bincludesearch');
1434 * Blog::getDefaultCategory()
1436 * @return ID for category as a default
1438 public function getDefaultCategory()
1440 return $this->getSetting('bdefcat');
1445 * @param integer $val allow comments by non-registered members or not
1448 public function setPublic($val)
1450 $this->setSetting('bpublic', $val);
1455 * Blog::setSearchable()
1456 * @param integer $val searchable from the other blogs or not
1459 public function setSearchable($val)
1461 $this->setSetting('bincludesearch', $val);
1466 * Blog::setDescription
1467 * @param string $val description for this weblog
1470 public function setDescription($val)
1472 $this->setSetting('bdesc',$val);
1477 * Blog::setUpdateFile()
1478 * @param string $val name of file to beupdated when weblog is updated
1481 public function setUpdateFile($val)
1483 $this->setSetting('bupdate',$val);
1488 * Blog::setDefaultSkin()
1489 * @param integer $val ID for default skin to use when displaying this weblog
1492 public function setDefaultSkin($val)
1494 $this->setSetting('bdefskin', $val);
1500 * @param string $val URI for this weblog
1503 public function setURL($val)
1505 $this->setSetting('burl', $val);
1511 * @param string $val name of this weblog
1514 public function setName($val)
1516 $this->setSetting('bname', $val);
1521 * Blog::setShortName()
1522 * @param string $val short name for this weblog
1525 public function setShortName($val)
1527 $this->setSetting('bshortname', $val);
1532 * Blog::setCommentsEnabled()
1533 * @param integer $val enabling posting comment or not
1536 public function setCommentsEnabled($val)
1538 $this->setSetting('bcomments',$val);
1543 * Blog::setMaxComments()
1544 * @param integer $val maximum number of comments for this weblog
1547 public function setMaxComments($val)
1549 $this->setSetting('bmaxcomments', $val);
1554 * Blog::setNotifyAddress()
1555 * @param string $val email to be notified if weblog updated
1558 public function setNotifyAddress($val)
1560 $this->setSetting('bnotify', $val);
1565 * Blog::setEmailRequired()
1566 * @param string requiring comments with email or not from non member
1569 public function setEmailRequired($val)
1571 $this->setSetting('breqemail', $val);
1576 * Blog::setTimeOffset()
1577 * @param integer $val time offset
1580 public function setTimeOffset($val)
1582 // check validity of value
1583 // 1. replace , by . (common mistake)
1584 $val = str_replace(',','.',$val);
1586 // 2. cast to float or int
1587 if ( is_numeric($val) && (i18n::strpos($val, '.5') === (i18n::strlen($val) - 2)) )
1589 $val = (float) $val;
1593 $val = (integer) $val;
1596 $this->setSetting('btimeoffset',$val);
1601 * Blog::setDefaultCategory()
1602 * @param integer $val ID for default category for this weblog
1605 public function setDefaultCategory($val)
1607 $this->setSetting('bdefcat',$val);
1612 * Blog::getSetting()
1613 * @param string $key key for setting of this weblog
1614 * @return mixed value for the setting
1616 public function getSetting($key)
1618 return $this->settings[$key];
1622 * Blog::setSetting()
1623 * @param string $key key for setting of this weblog
1624 * @param mixed $value value for the key
1627 public function setSetting($key, $value)
1629 $this->settings[$key] = $value;
1634 * Blog::addTeamMember()
1635 * Tries to add a member to the team.
1636 * Returns false if the member was already on the team
1638 * @param integer $memberid id for member
1639 * @param boolean $admin super-admin or not
1640 * @return boolean Success/Fail
1642 public function addTeamMember($memberid, $admin)
1646 $memberid = intval($memberid);
1647 $admin = intval($admin);
1649 // check if member is already a member
1650 $tmem =& $manager->getMember($memberid);
1652 if ( $tmem->isTeamMember($this->blogid) )
1662 $manager->notify('PreAddTeamMember', $data);
1665 $query = "INSERT INTO %s (TMEMBER, TBLOG, TADMIN) VALUES (%d, %d, %d);";
1666 $query = sprintf($query, sql_table('team'), (integer) $memberid, (integer) $this->blogid, (integer) $admin);
1667 DB::execute($query);
1674 $manager->notify('PostAddTeamMember', $data);
1676 $logMsg = sprintf(_TEAM_ADD_NEWTEAMMEMBER, $tmem->getDisplayName(), $memberid, $this->getName());
1677 ActionLog::add(INFO, $logMsg);
1685 * @return integer ID for this weblog
1687 public function getID()
1689 return (integer) $this->blogid;
1693 * Checks if a blog with a given shortname exists
1694 * Returns true if there is a blog with the given shortname (static)
1696 * @param string $name blog shortname
1697 * @return boolean exists or not
1699 public function exists($name)
1701 $r = DB::getResult('SELECT * FROM '.sql_table('blog').' WHERE bshortname='. DB::quoteValue($name));
1702 return ($r->rowCount() != 0);
1706 * Checks if a blog with a given id exists
1707 * Returns true if there is a blog with the given ID (static)
1709 * @param integer $id ID for searched weblog
1710 * @return boolean exists or not
1712 public function existsID($id)
1714 $r = DB::getResult('SELECT * FROM '.sql_table('blog').' WHERE bnumber='.intval($id));
1715 return ($r->rowCount() != 0);
1719 * Blog::setFuturePost()
1720 * flag there is a future post pending
1725 public function setFuturePost()
1727 $query = "UPDATE %s SET bfuturepost='1' WHERE bnumber=%d;";
1728 $query = sprintf($query, sql_table('blog'), (integer) $this->blogid);
1729 DB::execute($query);
1734 * Blog::clearFuturePost()
1735 * clear there is a future post pending
1740 public function clearFuturePost()
1742 $query = "UPDATE %s SET bfuturepost='0' WHERE bnumber=%d;";
1743 $query = sprintf($query, sql_table('blog'), (integer) $this->blogid);
1744 DB::execute($query);
1749 * Blog::checkJustPosted()
1750 * check if we should throw justPosted event
1755 public function checkJustPosted()
1759 if ( $this->settings['bfuturepost'] == 1 )
1761 $query = "SELECT * FROM %s WHERE iposted=0 AND iblog=%d AND itime < NOW();";
1762 $query = sprintf($query, sql_table('item'), (integer) $this->blogid);
1764 $result = DB::getResult($query);
1765 if ( $result->rowCount() > 0 )
1767 // This $pinged is allow a plugin to tell other hook to the event that a ping is sent already
1768 // Note that the plugins's calling order is subject to thri order in the plugin list
1770 $manager->notify('JustPosted', array('blogid' => $this->blogid, 'pinged' => &$pinged));
1772 // clear all expired future posts
1773 $query = "UPDATE %s SET iposted='1' WHERE iblog=%d AND itime < NOW();";
1774 $query = spriintf($query, sql_table('item'), (integer) $this->blogid);
1775 DB::execute($query);
1777 // check to see any pending future post, clear the flag is none
1778 $query = "SELECT * FROM %s WHERE iposted=0 AND iblog=%d;";
1779 $query = sprintf($query, sql_table('item'), (integer) $this->blogid);
1781 $result = DB::getResult($query);
1782 if ( $result->rowCount() == 0 )
1784 $this->clearFuturePost();
1792 * Blog::readLogFromList()
1793 * Shows the given list of items for this blog
1795 * @param array $itemarray array of item numbers to be displayed
1796 * @param string $template string representing the template _NAME_ (!)
1797 * @param string $highlight contains a query that should be highlighted
1798 * @param boolean $comments 1=show comments 0=don't show comments
1799 * @param boolean $dateheads 1=show dateheads 0=don't show dateheads
1800 * @param boolean $showDrafts 0=do not show drafts 1=show drafts
1801 * @param boolean $showFuture 0=do not show future posts 1=show future posts
1802 * @return integer amount of items shown
1804 public function readLogFromList($itemarray, $template, $highlight = '', $comments = 1, $dateheads = 1,$showDrafts = 0, $showFuture = 0)
1806 $query = $this->getSqlItemList($itemarray,$showDrafts,$showFuture);
1807 return $this->showUsingQuery($template, $query, $highlight, $comments, $dateheads);
1811 * Blog::getSqlItemList()
1812 * Returns the SQL query used to fill out templates for a list of items
1813 * No LIMIT clause is added. (caller should add this if multiple pages are requested)
1815 * @param array $itemarray an array holding the item numbers of the items to be displayed
1816 * @param integer $showDrafts 0=do not show drafts 1=show drafts
1817 * @param integer $showFuture 0=do not show future posts 1=show future posts
1818 * @return string either a full SQL query, or an empty string
1820 public function getSqlItemList($itemarray,$showDrafts = 0,$showFuture = 0)
1822 if ( !is_array($itemarray) )
1827 $showDrafts = intval($showDrafts);
1828 $showFuture = intval($showFuture);
1831 foreach ( $itemarray as $value )
1833 if ( intval($value) )
1835 $items[] = intval($value);
1838 if ( !count($items) )
1845 foreach ( $items as $value )
1849 . ' i.inumber as itemid,'
1850 . ' i.ititle as title,'
1851 . ' i.ibody as body,'
1852 . ' m.mname as author,'
1853 . ' m.mrealname as authorname,'
1855 . ' i.imore as more,'
1856 . ' m.mnumber as authorid,'
1857 . ' m.memail as authormail,'
1858 . ' m.murl as authorurl,'
1859 . ' c.cname as category,'
1860 . ' i.icat as catid,'
1861 . ' i.iclosed as closed';
1864 . sql_table('item') . ' as i, '
1865 . sql_table('member') . ' as m, '
1866 . sql_table('category') . ' as c'
1868 . ' i.iblog='.$this->blogid
1869 . ' and i.iauthor=m.mnumber'
1870 . ' and i.icat=c.catid';
1875 $query .= ' and i.idraft=0';
1879 // don't show future items
1880 $query .= ' and i.itime<=' . DB::formatDateTime($this->getCorrectTime());
1883 $query .= ' and i.inumber='.intval($value);
1886 if ($i) $query .= ' UNION ';
1893 * Blog::convertBreaks()
1894 * Get the the setting for the line break handling
1895 * [should be named as getConvertBreaks()]
1901 public function convertBreaks()
1903 return $this->getSetting('bconvertbreaks');
1907 * Set the the setting for the line break handling
1910 * @param boolean $val new value for bconvertbreaks
1913 public function setConvertBreaks($val)
1915 $this->setSetting('bconvertbreaks', $val);