예제 #1
0
 function SEARCH($text)
 {
     global $blogid;
     //		$text = preg_replace ("/[<,>,=,?,!,#,^,(,),[,\],:,;,\\\,%]/","",$text);
     /* * * for jp * * * * * * * * * * */
     $this->encoding = strtolower(preg_replace('|[^a-z0-9-_]|i', '', _CHARSET));
     if ($this->encoding != 'utf-8') {
         $text = mb_convert_encoding($text, "UTF-8", $this->encoding);
     }
     $text = str_replace(" ", ' ', $text);
     $text = preg_replace("/[<>=?!#^()[\\]:;\\%]/", "", $text);
     $this->ascii = '[\\x00-\\x7F]';
     $this->two = '[\\xC0-\\xDF][\\x80-\\xBF]';
     $this->three = '[\\xE0-\\xEF][\\x80-\\xBF][\\x80-\\xBF]';
     $this->jpmarked = $this->boolean_mark_atoms_jp($text);
     /* * * * * * * * * * * * * * * * */
     $this->querystring = $text;
     //		$this->marked	  = $this->boolean_mark_atoms($text);
     $this->inclusive = $this->boolean_inclusive_atoms($text);
     $this->blogs = array();
     // get all public searchable blogs, no matter what, include the current blog allways.
     $res = sql_query('SELECT bnumber FROM ' . sql_table('blog') . ' WHERE bincludesearch=1 ');
     while ($obj = sql_fetch_object($res)) {
         $this->blogs[] = intval($obj->bnumber);
     }
 }
예제 #2
0
 /**
  * This function creates an sql dump of the database and sends it to
  * the user as a file (can be gzipped if they want)
  *
  * @requires
  *		no output may have preceded (new headers are sent)
  * @param gzip
  *		1 = compress backup file, 0 = no compression (default)
  */
 function do_backup($gzip = 0)
 {
     global $manager;
     // tables of which backup is needed
     $tables = array(sql_table('actionlog'), sql_table('ban'), sql_table('blog'), sql_table('comment'), sql_table('config'), sql_table('item'), sql_table('karma'), sql_table('member'), sql_table('skin'), sql_table('skin_desc'), sql_table('team'), sql_table('template'), sql_table('template_desc'), sql_table('plugin'), sql_table('plugin_event'), sql_table('plugin_option'), sql_table('plugin_option_desc'), sql_table('category'), sql_table('activation'), sql_table('tickets'));
     // add tables that plugins want to backup to the list
     // catch all output generated by plugins
     ob_start();
     $res = sql_query('SELECT pfile FROM ' . sql_table('plugin'));
     while ($plugName = sql_fetch_object($res)) {
         $plug =& $manager->getPlugin($plugName->pfile);
         if ($plug) {
             $tables = array_merge($tables, (array) $plug->getTableList());
         }
     }
     ob_end_clean();
     // remove duplicates
     $tables = array_unique($tables);
     // make sure browsers don't cache the backup
     header("Pragma: no-cache");
     // don't allow gzip compression when extension is not loaded
     if ($gzip != 0 && !extension_loaded("zlib")) {
         $gzip = 0;
     }
     if ($gzip) {
         // use an output buffer
         @ob_start();
         @ob_implicit_flush(0);
         // set filename
         $filename = 'nucleus_db_backup_' . strftime("%Y-%m-%d-%H-%M-%S", time()) . ".sql.gz";
     } else {
         $filename = 'nucleus_db_backup_' . strftime("%Y-%m-%d-%H-%M-%S", time()) . ".sql";
     }
     // send headers that tell the browser a file is coming
     header("Content-Type: text/x-delimtext; name=\"{$filename}\"");
     header("Content-disposition: attachment; filename={$filename}");
     // dump header
     echo "#\n";
     echo "# " . _BACKUP_BACKUPFILE_TITLE . " \n";
     echo "# " . _ADMINPAGEFOOT_OFFICIALURL . "\n";
     echo "#\n";
     echo "# " . _BACKUP_BACKUPFILE_BACKUPDATE . gmdate("d-m-Y H:i:s", time()) . " GMT\n";
     global $nucleus;
     echo "# " . _BACKUP_BACKUPFILE_NUCLEUSVERSION . $nucleus['version'] . "\n";
     echo "#\n";
     echo "# " . _BACKUP_WARNING_NUCLEUSVERSION . "\n";
     echo "#\n";
     // dump all tables
     reset($tables);
     array_walk($tables, array(&$this, '_backup_dump_table'));
     if ($gzip) {
         $Size = ob_get_length();
         $Crc = crc32(ob_get_contents());
         $contents = gzcompress(ob_get_contents());
         ob_end_clean();
         echo "‹" . substr($contents, 0, strlen($contents) - 4) . $this->gzip_PrintFourChars($Crc) . $this->gzip_PrintFourChars($Size);
     }
     exit;
 }
예제 #3
0
 /**
  * Returns the requested comment
  *
  * @static
  */
 function getComment($commentid)
 {
     $query = 'SELECT `cnumber` AS commentid, `cbody` AS body, `cuser` AS user, `cmail` AS userid, `cemail` AS email, `cmember` AS memberid, `ctime`, `chost` AS host, `mname` AS member, `cip` AS ip, `cblog` AS blogid' . ' FROM ' . sql_table('comment') . ' LEFT OUTER JOIN ' . sql_table('member') . ' ON `cmember` = `mnumber`' . ' WHERE `cnumber` = ' . intval($commentid);
     $comments = sql_query($query);
     $aCommentInfo = sql_fetch_assoc($comments);
     if ($aCommentInfo) {
         $aCommentInfo['timestamp'] = strtotime($aCommentInfo['ctime']);
     }
     return $aCommentInfo;
 }
예제 #4
0
 /**
  * Removes a ban from the banlist (correct iprange is needed as argument)
  * Returns 1 on success, 0 on error
  */
 function removeBan($blogid, $iprange)
 {
     global $manager;
     $blogid = intval($blogid);
     $manager->notify('PreDeleteBan', array('blogid' => $blogid, 'range' => $iprange));
     $query = 'DELETE FROM ' . sql_table('ban') . " WHERE blogid={$blogid} and iprange='" . sql_real_escape_string($iprange) . "'";
     sql_query($query);
     $result = sql_affected_rows() > 0;
     $manager->notify('PostDeleteBan', array('blogid' => $blogid, 'range' => $iprange));
     return $result;
 }
예제 #5
0
 function NP_SpamBayes()
 {
     global $DIR_PLUGINS;
     $this->table_cat = sql_table('plug_sb_cat');
     // categories
     $this->table_wf = sql_table('plug_sb_wf');
     // word frequencies
     $this->table_ref = sql_table('plug_sb_ref');
     // references
     $this->table_log = sql_table('plug_sb_log');
     // logging
     include_once $DIR_PLUGINS . "spambayes/spambayes.php";
     $this->spambayes = new NaiveBayesian($this);
 }
예제 #6
0
 public function event_PostAuthentication(&$data)
 {
     global $CONF;
     static $blogid = 0;
     static $blogs = array();
     MediaUtils::$lib_path = preg_replace('#/*$#', '', $this->getDirectory());
     MediaUtils::$prefix = (bool) $CONF['MediaPrefix'];
     MediaUtils::$maxsize = (int) $CONF['MaxUploadSize'];
     $suffixes = explode(',', $CONF['AllowedTypes']);
     foreach ($suffixes as $suffix) {
         $suffix = trim($suffix);
         if (!in_array($suffix, MediaUtils::$suffixes)) {
             MediaUtils::$suffixes[] = strtolower($suffix);
         }
     }
     $result = sql_query('SELECT bnumber, bshortname FROM ' . sql_table('blog') . ';');
     while (FALSE !== ($row = sql_fetch_assoc($result))) {
         $blogs[$row['bnumber']] = $row['bshortname'];
     }
     MediaUtils::$blogs =& $blogs;
     if (array_key_exists('blogid', $_GET)) {
         $blogid = (int) $_GET['blogid'];
     } else {
         if (array_key_exists('blogid', $_POST)) {
             $blogid = (int) $_POST['blogid'];
         } else {
             if (array_key_exists('itemid', $_GET) && function_exists('getBlogIDFromItemID')) {
                 $blogid = (int) getBlogIDFromItemID((int) $_GET['itemid']);
             } else {
                 if (array_key_exists('itemid', $_POST) && function_exists('getBlogIDFromItemID')) {
                     $blogid = (int) getBlogIDFromItemID((int) $_POST['itemid']);
                 } else {
                     if (array_key_exists(MediaUtils::$cookiename, $_COOKIE)) {
                         $blogid = (int) $_COOKIE['blogid'];
                     } else {
                         return;
                     }
                 }
             }
         }
     }
     MediaUtils::$blogid =& $blogid;
     MediaUtils::$bshortname =& MediaUtils::$blogs[MediaUtils::$blogid];
     return;
 }
예제 #7
0
 /**
  * (Static) Method to trim the action log (from over 500 back to 250 entries)
  */
 function trimLog()
 {
     static $checked = 0;
     // only check once per run
     if ($checked) {
         return;
     }
     // trim
     $checked = 1;
     $iTotal = quickQuery('SELECT COUNT(*) AS result FROM ' . sql_table('actionlog'));
     // if size > 500, drop back to about 250
     $iMaxSize = 500;
     $iDropSize = 250;
     if ($iTotal > $iMaxSize) {
         $tsChop = quickQuery('SELECT timestamp as result FROM ' . sql_table('actionlog') . ' ORDER BY timestamp DESC LIMIT ' . $iDropSize . ',1');
         sql_query('DELETE FROM ' . sql_table('actionlog') . ' WHERE timestamp < \'' . $tsChop . '\'');
     }
 }
 function doSkinVar($skinType, $numOfPostsToShow)
 {
     global $blog;
     if ($numOfPostsToShow <= 0) {
         $numOfPostsToShow = 10;
     }
     $q = "SELECT inumber as id, ititle as title, " . "citem,COUNT(cnumber) as num_of_comments, " . "SUM(SubComment.cVal)*POW(COUNT(cnumber),2)*MAX(SubComment.iVal) as CurrentVal " . "FROM ( " . "SELECT *, " . "SQRT(1.0 / POW((DATEDIFF(c.ctime,CURDATE()) / 365),2)) as cVal," . "SQRT(1.0 / POW((DATEDIFF(i.itime,CURDATE()) / 365),2)) as iVal " . "FROM " . sql_table('comment') . " as c " . "INNER JOIN " . sql_table('item') . " as i " . "ON i.inumber=c.citem) as SubComment " . "GROUP BY inumber, ititle " . "ORDER BY `CurrentVal` DESC " . "LIMIT 0, " . intval($numOfPostsToShow);
     $res = mysql_query($q);
     echo $this->getOption('header');
     $link_templ = $this->getOption('link');
     while ($row = mysql_fetch_array($res)) {
         $out = str_replace("%l", createItemLink($row[id]), $link_templ);
         $out = str_replace("%p", $row['title'], $out);
         $out = str_replace("%c", $row['num_of_comments'], $out);
         $out = str_replace("%s", $row['CurrentVal'], $out);
         echo $out;
     }
     echo $this->getOption('footer');
 }
예제 #9
0
 /**
  * Outputs the XML contents of the export file
  *
  * @param $setHeaders
  *		set to 0 if you don't want to send out headers
  *		(optional, default 1)
  */
 function export($setHeaders = 1)
 {
     if ($setHeaders) {
         // make sure the mimetype is correct, and that the data does not show up
         // in the browser, but gets saved into and XML file (popup download window)
         header('Content-Type: text/xml');
         header('Content-Disposition: attachment; filename="skinbackup.xml"');
         header('Expires: 0');
         header('Pragma: no-cache');
     }
     echo "<nucleusskin>\n";
     // meta
     echo "\t<meta>\n";
     // skins
     foreach ($this->skins as $skinId => $skinName) {
         $skinName = htmlspecialchars($skinName, ENT_QUOTES);
         if (strtoupper(_CHARSET) != 'UTF-8') {
             $skinName = mb_convert_encoding($skinName, 'UTF-8', _CHARSET);
         }
         echo "\t\t" . '<skin name="' . htmlspecialchars($skinName, ENT_QUOTES) . '" />' . "\n";
     }
     // templates
     foreach ($this->templates as $templateId => $templateName) {
         $templateName = htmlspecialchars($templateName, ENT_QUOTES);
         if (strtoupper(_CHARSET) != 'UTF-8') {
             $templateName = mb_convert_encoding($templateName, 'UTF-8', _CHARSET);
         }
         echo "\t\t" . '<template name="' . htmlspecialchars($templateName, ENT_QUOTES) . '" />' . "\n";
     }
     // extra info
     if ($this->info) {
         if (strtoupper(_CHARSET) != 'UTF-8') {
             $skin_info = mb_convert_encoding($this->info, 'UTF-8', _CHARSET);
         } else {
             $skin_info = $this->info;
         }
         echo "\t\t<info><![CDATA[" . $skin_info . "]]></info>\n";
     }
     echo "\t</meta>\n\n\n";
     // contents skins
     foreach ($this->skins as $skinId => $skinName) {
         $skinId = intval($skinId);
         $skinObj = new SKIN($skinId);
         $skinName = htmlspecialchars($skinName, ENT_QUOTES);
         $contentT = htmlspecialchars($skinObj->getContentType(), ENT_QUOTES);
         $incMode = htmlspecialchars($skinObj->getIncludeMode(), ENT_QUOTES);
         $incPrefx = htmlspecialchars($skinObj->getIncludePrefix(), ENT_QUOTES);
         $skinDesc = htmlspecialchars($skinObj->getDescription(), ENT_QUOTES);
         if (strtoupper(_CHARSET) != 'UTF-8') {
             $skinName = mb_convert_encoding($skinName, 'UTF-8', _CHARSET);
             $contentT = mb_convert_encoding($contentT, 'UTF-8', _CHARSET);
             $incMode = mb_convert_encoding($incMode, 'UTF-8', _CHARSET);
             $incPrefx = mb_convert_encoding($incPrefx, 'UTF-8', _CHARSET);
             $skinDesc = mb_convert_encoding($skinDesc, 'UTF-8', _CHARSET);
         }
         echo "\t" . '<skin name="' . $skinName . '" type="' . $contentT . '" includeMode="' . $incMode . '" includePrefix="' . $incPrefx . '">' . "\n";
         echo "\t\t" . '<description>' . $skinDesc . '</description>' . "\n";
         $que = 'SELECT' . '    stype,' . '    scontent ' . 'FROM ' . sql_table('skin') . ' WHERE' . '    sdesc = ' . $skinId;
         $res = sql_query($que);
         while ($partObj = sql_fetch_object($res)) {
             $type = htmlspecialchars($partObj->stype, ENT_QUOTES);
             $cdata = $this->escapeCDATA($partObj->scontent);
             if (strtoupper(_CHARSET) != 'UTF-8') {
                 $type = mb_convert_encoding($type, 'UTF-8', _CHARSET);
                 $cdata = mb_convert_encoding($cdata, 'UTF-8', _CHARSET);
             }
             echo "\t\t" . '<part name="' . $type . '">';
             echo '<![CDATA[' . $cdata . ']]>';
             echo "</part>\n\n";
         }
         echo "\t</skin>\n\n\n";
     }
     // contents templates
     foreach ($this->templates as $templateId => $templateName) {
         $templateId = intval($templateId);
         $templateName = htmlspecialchars($templateName, ENT_QUOTES);
         $templateDesc = htmlspecialchars(TEMPLATE::getDesc($templateId), ENT_QUOTES);
         if (strtoupper(_CHARSET) != 'UTF-8') {
             $templateName = mb_convert_encoding($templateName, 'UTF-8', _CHARSET);
             $templateDesc = mb_convert_encoding($templateDesc, 'UTF-8', _CHARSET);
         }
         echo "\t" . '<template name="' . $templateName . '">' . "\n";
         echo "\t\t" . '<description>' . $templateDesc . "</description>\n";
         $que = 'SELECT' . ' tpartname,' . ' tcontent' . ' FROM ' . sql_table('template') . ' WHERE' . ' tdesc = ' . $templateId;
         $res = sql_query($que);
         while ($partObj = sql_fetch_object($res)) {
             $type = htmlspecialchars($partObj->tpartname, ENT_QUOTES);
             $cdata = $this->escapeCDATA($partObj->tcontent);
             if (strtoupper(_CHARSET) != 'UTF-8') {
                 $type = mb_convert_encoding($type, 'UTF-8', _CHARSET);
                 $cdata = mb_convert_encoding($cdata, 'UTF-8', _CHARSET);
             }
             echo "\t\t" . '<part name="' . $type . '">';
             echo '<![CDATA[' . $cdata . ']]>';
             echo '</part>' . "\n\n";
         }
         echo "\t</template>\n\n\n";
     }
     echo '</nucleusskin>';
 }
예제 #10
0
 /**
  * Returns the SQL query used to fill out templates for a list of items
  *
  * @param $itemarray
  *	  an array holding the item numbers of the items to be displayed
  * @param $showDrafts
  *		0=do not show drafts 1=show drafts
  * @param $showFuture
  *		0=do not show future posts 1=show future posts
  * @returns
  *	  either a full SQL query, or an empty string
  * @note
  *	  No LIMIT clause is added. (caller should add this if multiple pages are requested)
  */
 function getSqlItemList($itemarray, $showDrafts = 0, $showFuture = 0)
 {
     if (!is_array($itemarray)) {
         return '';
     }
     $showDrafts = intval($showDrafts);
     $showFuture = intval($showFuture);
     $items = array();
     foreach ($itemarray as $value) {
         if (intval($value)) {
             $items[] = intval($value);
         }
     }
     if (!count($items)) {
         return '';
     }
     //$itemlist = implode(',',$items);
     $i = count($items);
     $query = '';
     foreach ($items as $value) {
         $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';
         $query .= ' FROM ' . sql_table('item') . ' as i, ' . sql_table('member') . ' as m, ' . sql_table('category') . ' as c' . ' WHERE' . ' i.iblog   = ' . $this->blogid . ' and i.iauthor = m.mnumber' . ' and i.icat	= c.catid';
         if (!$showDrafts) {
             $query .= ' and i.idraft=0';
         }
         // exclude drafts
         if (!$showFuture) {
             $query .= ' and i.itime<=' . mysqldate($this->getCorrectTime());
         }
         // don't show future items
         //$query .= ' and i.inumber IN ('.$itemlist.')';
         $query .= ' and i.inumber = ' . intval($value);
         $query .= ')';
         $i--;
         if ($i) {
             $query .= ' UNION ';
         }
     }
     return $query;
 }
 function doAction($type = '')
 {
     global $CONF, $manager;
     if (!$type) {
         $type = 'google';
     }
     if ($type !== 'google' && $type !== 'yahoo') {
         return;
     }
     $sitemap = array();
     $blog_res = sql_query('SELECT * FROM ' . sql_table('blog'));
     while ($blog = sql_fetch_array($blog_res)) {
         if ($this->getBlogOption($blog['bnumber'], 'IncludeSitemap') == 'yes') {
             if ($blog['bnumber'] != $CONF['DefaultBlog']) {
                 $sitemap[] = array('loc' => $this->_prepareLink($blog['bnumber'], createBlogidLink($blog['bnumber'])), 'priority' => '1.0', 'changefreq' => 'daily');
             } else {
                 $sitemap[] = array('loc' => $blog['burl'], 'priority' => '1.0', 'changefreq' => 'daily');
             }
             $params = array(sql_table('category'), $blog['bnumber']);
             $cat_res = sql_query(vsprintf('SELECT * FROM %s WHERE cblog=%s ORDER BY catid', $params));
             while ($cat = sql_fetch_array($cat_res)) {
                 $sitemap[] = array('loc' => $this->_prepareLink($blog['bnumber'], createCategoryLink($cat['catid'])), 'priority' => '1.0', 'changefreq' => 'daily');
             }
             $b =& $manager->getBlog($blog['bnumber']);
             $item_res = sql_query('
                 SELECT 
                     *,
                     UNIX_TIMESTAMP(itime) AS timestamp
                 FROM 
                     ' . sql_table('item') . ' 
                 WHERE
                     iblog = ' . $blog['bnumber'] . ' AND
                     idraft = 0
                     AND itime <= ' . mysqldate($b->getCorrectTime()) . '
                 ORDER BY 
                     inumber DESC
             ');
             $now = $_SERVER['HTTP_REQUEST_TIME'];
             while ($item = sql_fetch_array($item_res)) {
                 $tz = date('O', $item['timestamp']);
                 $tz = substr($tz, 0, 3) . ':' . substr($tz, 3, 2);
                 $pasttime = $now - $item['timestamp'];
                 if ($pasttime < 86400 * 2) {
                     $fq = 'hourly';
                 } elseif ($pasttime < 86400 * 14) {
                     $fq = 'daily';
                 } elseif ($pasttime < 86400 * 62) {
                     $fq = 'weekly';
                 } else {
                     $fq = 'monthly';
                 }
                 $sitemap[] = array('loc' => $this->_prepareLink($blog['bnumber'], createItemLink($item['inumber'])), 'lastmod' => gmdate('Y-m-d\\TH:i:s', $item['timestamp']) . $tz, 'priority' => '1.0', 'changefreq' => $fq);
             }
         }
     }
     $eventdata = array('sitemap' => &$sitemap);
     $manager->notify('SiteMap', $eventdata);
     if ($type == 'google') {
         header("Content-type: application/xml");
         echo "<?xml version='1.0' encoding='UTF-8'?>\n\n";
         echo "<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' ";
         echo "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
         echo "xsi:schemaLocation='http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'>\n";
         $tpl = "\t\t<%s>%s</%s>\n";
         foreach ($sitemap as $url) {
             echo "\t<url>\n";
             foreach ($url as $key => $value) {
                 echo sprintf($tpl, $key, htmlspecialchars($value, ENT_QUOTES, _CHARSET), $key);
             }
             echo "\t</url>\n";
         }
         echo "</urlset>\n";
     } else {
         header("Content-type: text/plain");
         foreach ($sitemap as $url) {
             echo $url['loc'] . "\n";
         }
     }
     exit;
 }
예제 #12
0
/**
 * Returns a list of recent items (Nucleus Version)
 * ($amount = max 20);
 */
function _getRecentItems($blogid, $username, $password, $amount)
{
    $blogid = intval($blogid);
    $amount = intval($amount);
    // 1. login
    $mem = new MEMBER();
    if (!$mem->login($username, $password)) {
        return _error(1, "Could not log in");
    }
    // 2. check if allowed
    if (!BLOG::existsID($blogid)) {
        return _error(2, "No such blog ({$blogid})");
    }
    if (!$mem->teamRights($blogid)) {
        return _error(3, "Not a team member");
    }
    $amount = intval($amount);
    if ($amount < 1 or $amount > 20) {
        return _error(5, "Amount parameter must be in range 1..20");
    }
    // 3. create and return list of recent items
    // Struct returned has dateCreated, userid, blogid and content
    $structarray = array();
    // the array in which the structs will be stored
    $query = "SELECT ibody, iauthor, ibody, imore, ititle, iclosed, idraft, itime" . ' FROM ' . sql_table('item') . " WHERE iblog={$blogid}" . " ORDER BY itime DESC" . " LIMIT {$amount}";
    $r = sql_query($query);
    while ($obj = sql_fetch_object($r)) {
        $newstruct = new xmlrpcval(array("publishDate" => new xmlrpcval(iso8601_encode(strtotime($obj->itime)), "dateTime.iso8601"), "userid" => new xmlrpcval($obj->iauthor, "string"), "blogid" => new xmlrpcval($blogid, "string"), "title" => new xmlrpcval($obj->ititle, "string"), "body" => new xmlrpcval($obj->ibody, "string"), "more" => new xmlrpcval($obj->imore, "string"), "draft" => new xmlrpcval($obj->idraft, "boolean"), "closed" => new xmlrpcval($obj->iclosed, "boolean")), 'struct');
        array_push($structarray, $newstruct);
    }
    return new xmlrpcresp(new xmlrpcval($structarray, "array"));
}
예제 #13
0
 /**
  * @static
  * @todo document this
  */
 function _insertPluginOptions($context, $contextid = 0)
 {
     // get all current values for this contextid
     // (note: this might contain doubles for overlapping contextids)
     $aIdToValue = array();
     $res = sql_query('SELECT oid, ovalue FROM ' . sql_table('plugin_option') . ' WHERE ocontextid=' . intval($contextid));
     while ($o = sql_fetch_object($res)) {
         $aIdToValue[$o->oid] = $o->ovalue;
     }
     // get list of oids per pid
     $query = 'SELECT * FROM ' . sql_table('plugin_option_desc') . ',' . sql_table('plugin') . ' WHERE opid=pid and ocontext=\'' . sql_real_escape_string($context) . '\' ORDER BY porder, oid ASC';
     $res = sql_query($query);
     $aOptions = array();
     while ($o = sql_fetch_object($res)) {
         if (in_array($o->oid, array_keys($aIdToValue))) {
             $value = $aIdToValue[$o->oid];
         } else {
             $value = $o->odef;
         }
         array_push($aOptions, array('pid' => $o->pid, 'pfile' => $o->pfile, 'oid' => $o->oid, 'value' => $value, 'name' => $o->oname, 'description' => $o->odesc, 'type' => $o->otype, 'typeinfo' => $o->oextra, 'contextid' => $contextid, 'extra' => ''));
     }
     global $manager;
     $manager->notify('PrePluginOptionsEdit', array('context' => $context, 'contextid' => $contextid, 'options' => &$aOptions));
     $iPrevPid = -1;
     foreach ($aOptions as $aOption) {
         // new plugin?
         if ($iPrevPid != $aOption['pid']) {
             $iPrevPid = $aOption['pid'];
             if (!defined('_PLUGIN_OPTIONS_TITLE')) {
                 define('_PLUGIN_OPTIONS_TITLE', 'Options for %s');
             }
             echo '<tr><th colspan="2">' . sprintf(_PLUGIN_OPTIONS_TITLE, htmlspecialchars($aOption['pfile'], ENT_QUOTES)) . '</th></tr>';
         }
         $meta = NucleusPlugin::getOptionMeta($aOption['typeinfo']);
         if (@$meta['access'] != 'hidden') {
             echo '<tr>';
             listplug_plugOptionRow($aOption);
             echo '</tr>';
         }
     }
 }
예제 #14
0
 function RegistPath($objID, $path, $bid, $oParam, $name, $new = FALSE)
 {
     global $CONF;
     switch ($oParam) {
         case 'item':
         case 'member':
             if (preg_match('/.html$/', $path)) {
                 $path = substr($path, 0, -5);
             }
             break;
         case 'blog':
         case 'category':
         case 'subcategory':
             break;
         default:
             return;
             break;
     }
     $bid = intval($bid);
     $objID = intval($objID);
     $name = rawurlencode($name);
     if ($new && $oParam == 'item') {
         $tque = 'SELECT itime as result FROM %s WHERE inumber = %d';
         $itime = quickQuery(sprintf($tque, sql_table('item'), $objID));
         list($y, $m, $d, $trush) = sscanf($itime, '%d-%d-%d %s');
         $param['year'] = sprintf('%04d', $y);
         $param['month'] = sprintf('%02d', $m);
         $param['day'] = sprintf('%02d', $d);
         $dfItem = $this->getOption('customurl_dfitem');
         $ikey = TEMPLATE::fill($dfItem, $param);
         if ($path == $ikey) {
             $path = $ikey . '_' . $objID;
         }
     } elseif (!$new && strlen($path) == 0) {
         $del_que = 'DELETE FROM %s WHERE obj_id = %d AND obj_param = "%s"';
         sql_query(sprintf($del_que, _CUSTOMURL_TABLE, $objID, $oParam));
         $msg = array(0, _DELETE_PATH, $name, _DELETE_MSG);
         return $msg;
         exit;
     }
     $dotslash = array('.', '/');
     $path = str_replace($dotslash, '_', $path);
     if (!preg_match('/^[-_a-zA-Z0-9]+$/', $path)) {
         $msg = array(1, _INVALID_ERROR, $name, _INVALID_MSG);
         return $msg;
         exit;
     }
     $tempPath = $path;
     if ($oParam == 'item' || $oParam == 'member') {
         $tempPath .= '.html';
     }
     $conf_que = 'SELECT obj_id FROM %s' . ' WHERE obj_name = "%s"' . ' AND    obj_bid = %d' . ' AND  obj_param = "%s"' . ' AND    obj_id != %d';
     $res = sql_query(sprintf($conf_que, _CUSTOMURL_TABLE, $tempPath, $bid, $oParam, $objID));
     if ($res && sql_num_rows($res)) {
         $msg = array(0, _CONFLICT_ERROR, $name, _CONFLICT_MSG);
         $path .= '_' . $objID;
     }
     if ($oParam == 'category' && !$msg) {
         $conf_cat = 'SELECT obj_id FROM %s WHERE obj_name = "%s"' . ' AND obj_param = "blog"';
         $res = sql_query(sprintf($conf_cat, _CUSTOMURL_TABLE, $tempPath));
         if ($res && sql_num_rows($res)) {
             $msg = array(0, _CONFLICT_ERROR, $name, _CONFLICT_MSG);
             $path .= '_' . $objID;
         }
     }
     if ($oParam == 'blog' && !$msg) {
         $conf_blg = 'SELECT obj_id FROM %s WHERE obj_name = "%s"' . ' AND obj_param = "category"';
         $res = sql_query(sprintf($conf_blg, _CUSTOMURL_TABLE, $tempPath));
         if ($res && sql_num_rows($res)) {
             $msg = array(0, _CONFLICT_ERROR, $name, _CONFLICT_MSG);
             $path .= '_' . $objID;
         }
     }
     $newPath = $path;
     if ($oParam == 'item' || $oParam == 'member') {
         $newPath .= '.html';
     }
     $query = 'SELECT * FROM %s WHERE obj_id = %d AND obj_param = "%s"';
     $res = sql_query(sprintf($query, _CUSTOMURL_TABLE, $objID, $oParam));
     $row = sql_fetch_object($res);
     $pathID = $row->id;
     if ($pathID) {
         $query = 'UPDATE %s SET obj_name = "%s" WHERE id = %d';
         sql_query(sprintf($query, _CUSTOMURL_TABLE, $newPath, $pathID));
     } else {
         $query = 'INSERT INTO %s (obj_param, obj_name, obj_id, obj_bid)' . ' VALUES ("%s", "%s", %d, %d)';
         sql_query(sprintf($query, _CUSTOMURL_TABLE, $oParam, $newPath, $objID, $bid));
     }
     switch ($oParam) {
         case 'blog':
             $this->setBlogOption($objID, 'customurl_bname', $path);
             break;
         case 'category':
             $this->setCategoryOption($objID, 'customurl_cname', $path);
             break;
         case 'member':
             $this->setMemberOption($objID, 'customurl_mname', $path);
             break;
         default:
             break;
     }
     return $msg;
 }
예제 #15
0
/**
 * Returns a list of recent items
 */
function _getRecentItemsBlogger($blogid, $username, $password, $amount)
{
    $blogid = intval($blogid);
    $amount = intval($amount);
    // 1. login
    $mem = new MEMBER();
    if (!$mem->login($username, $password)) {
        return _error(1, "Could not log in");
    }
    // 2. check if allowed
    if (!BLOG::existsID($blogid)) {
        return _error(2, "No such blog ({$blogid})");
    }
    if (!$mem->teamRights($blogid)) {
        return _error(3, "Not a team member");
    }
    $amount = intval($amount);
    if ($amount < 1 or $amount > 20) {
        return _error(5, "Amount parameter must be in range 1..20");
    }
    // 3. create and return list of recent items
    // Struct returned has dateCreated, userid, blogid and content
    $blog = new BLOG($blogid);
    $structarray = array();
    // the array in which the structs will be stored
    $query = "SELECT mname, ibody, iauthor, ibody, inumber, ititle as title, itime, cname as category" . ' FROM ' . sql_table('item') . ', ' . sql_table('category') . ', ' . sql_table('member') . " WHERE iblog={$blogid} and icat=catid and iauthor=mnumber" . " ORDER BY itime DESC" . " LIMIT {$amount}";
    $r = sql_query($query);
    while ($row = sql_fetch_assoc($r)) {
        // remove linebreaks if needed
        if ($blog->convertBreaks()) {
            $row['ibody'] = removeBreaks($row['ibody']);
        }
        $content = blogger_specialTags($row) . $row['ibody'];
        $newstruct = new xmlrpcval(array("userid" => new xmlrpcval($row['iauthor'], "string"), "dateCreated" => new xmlrpcval(iso8601_encode(strtotime($row['itime'])), "dateTime.iso8601"), "blogid" => new xmlrpcval($blogid, "string"), "content" => new xmlrpcval($content, "string"), "postid" => new xmlrpcval($row['inumber'], "string"), "authorName" => new xmlrpcval($row['mname'], 'string'), "title" => new xmlrpcval($row['title'], 'string')), 'struct');
        array_push($structarray, $newstruct);
    }
    return new xmlrpcresp(new xmlrpcval($structarray, "array"));
}
예제 #16
0
 function unInstall()
 {
     // restore to standard settings
     sql_query(sprintf("UPDATE %s SET value='2' WHERE name='DisableJSTools'", sql_table('config')));
 }
예제 #17
0
 function _deleteKeyword($itemid, $keyword)
 {
     $keywordid = $this->_getKeywordID($keyword);
     $sql = sprintf('DELETE FROM %s WHERE key_id=%d AND keyword_id=%d', sql_table('plug_keywords_relationship'), intval($itemid), intval($keywordid));
     sql_query($sql);
 }
예제 #18
0
 /**
  * @param $aOptions: array ( 'oid' => array( 'contextid' => 'value'))
  *        (taken from request using requestVar())
  * @param $newContextid: integer (accepts a contextid when it is for a new
  *        contextid there was no id available at the moment of writing the
  *        formcontrols into the page (by ex: itemOptions for new item)
  * @static
  */
 function _applyPluginOptions(&$aOptions, $newContextid = 0)
 {
     global $manager;
     if (!is_array($aOptions)) {
         return;
     }
     foreach ($aOptions as $oid => $values) {
         // get option type info
         $query = 'SELECT opid, oname, ocontext, otype, oextra, odef FROM ' . sql_table('plugin_option_desc') . ' WHERE oid=' . intval($oid);
         $res = sql_query($query);
         if ($o = sql_fetch_object($res)) {
             foreach ($values as $key => $value) {
                 // avoid overriding the key used by foreach statement
                 $contextid = $key;
                 // retreive any metadata
                 $meta = NucleusPlugin::getOptionMeta($o->oextra);
                 // if the option is readonly or hidden it may not be saved
                 if ($meta['access'] != 'readonly' && $meta['access'] != 'hidden') {
                     $value = undoMagic($value);
                     // value comes from request
                     switch ($o->otype) {
                         case 'yesno':
                             if ($value != 'yes' && $value != 'no') {
                                 $value = 'no';
                             }
                             break;
                         default:
                             break;
                     }
                     // check the validity of numerical options
                     if ($meta['datatype'] == 'numerical' && !is_numeric($value)) {
                         //the option must be numeric, but the it isn't
                         //use the default for this option
                         $value = $o->odef;
                     }
                     // decide wether we are using the contextid of newContextid
                     if ($newContextid != 0) {
                         $contextid = $newContextid;
                     }
                     //trigger event PrePluginOptionsUpdate to give the plugin the
                     //possibility to change/validate the new value for the option
                     $manager->notify('PrePluginOptionsUpdate', array('context' => $o->ocontext, 'plugid' => $o->opid, 'optionname' => $o->oname, 'contextid' => $contextid, 'value' => &$value));
                     // delete the old value for the option
                     sql_query('DELETE FROM ' . sql_table('plugin_option') . ' WHERE oid=' . intval($oid) . ' AND ocontextid=' . intval($contextid));
                     sql_query('INSERT INTO ' . sql_table('plugin_option') . " (oid, ocontextid, ovalue) VALUES (" . intval($oid) . "," . intval($contextid) . ",'" . sql_real_escape_string($value) . "')");
                 }
             }
         }
         // clear option value cache if the plugin object is already loaded
         if (is_object($o)) {
             $plugin =& $manager->pidLoaded($o->opid);
             if ($plugin) {
                 $plugin->clearOptionValueCache();
             }
         }
     }
 }
예제 #19
0
 function action_itemview($bid = 0, $msg = '')
 {
     global $CONF, $oPluginAdmin;
     if (empty($bid)) {
         if (getVar('blogid')) {
             $bid = intGetVar('blogid');
         } else {
             $bid = intval($CONF['DefaultBlog']);
         }
     } else {
         $bid = intval($bid);
     }
     $oPluginAdmin->start();
     $printData = '<h2>' . _ADMIN_AREA_TITLE . '</h2>' . '<ul style="list-style:none;">' . '  <li>' . '    <a href="' . $this->pediturl . '">' . _OPTION_SETTING . '    </a>' . '  </li>' . '  <li>' . '    <a href="' . $this->adminurl . 'index.php?action=blogview">' . _FOR_BLOG_SETTING . '    </a>' . '  </li>' . '  <li>' . '    <a href="' . $this->adminurl . 'index.php?action=categoryview&amp;blogid=' . $bid . '">' . _FOR_CATEGORY_SETTING . '    </a>' . '  </li>' . '  <li>' . '    <a href="' . $this->adminurl . 'index.php?action=memberview">' . _FOR_MEMBER_SETTING . '    </a>' . '  </li>' . '</ul>' . '<p><h3>' . $this->_hsc($msg) . '</h3>';
     echo $printData;
     unset($printData);
     $this->print_tablehead(_LISTS_TITLE, _LISTS_ITEM_DESC);
     $query = 'SELECT %s,%s,%s FROM %s WHERE iblog = %d ORDER BY itime DESC';
     $query = sprintf($query, ititle, inumber, ibody, sql_table('item'), $bid);
     $res = sql_query($query);
     while ($i = mysql_fetch_object($res)) {
         $query = 'SELECT obj_name as result FROM %s WHERE obj_param = "item" AND obj_id = %d';
         $query = sprintf($query, sql_table('plug_customurl'), intval($i->inumber));
         $temp_res = quickQuery($query);
         $ipath = $this->_hsc(substr($temp_res, 0, -5));
         $data = array('oid' => intval($i->inumber), 'obd' => $bid, 'opr' => 'item', 'name' => $this->_hsc($i->ititle), 'ret' => 'itemview', 'ed_URL' => $this->editurl . 'index.php?action=itemedit' . '&amp;itemid=' . intval($i->inumber), 'path' => $ipath);
         if (extension_loaded('mbstring')) {
             $data['desc'] = $this->_hsc(mb_substr(strip_tags($i->ibody), 0, 80));
         } else {
             $this->_hsc(substr(strip_tags($i->ibody), 0, 80));
         }
         $this->print_tablerow($data);
     }
     echo '</tbody></table></p>';
     unset($query);
     $oPluginAdmin->end();
 }
예제 #20
0
// defines how much media items will be shown per page. You can override this
// in config.php if you like. (changing it in config.php instead of here will
// allow your settings to be kept even after a Nucleus upgrade)
$CONF['MediaPerPage'] = 10;
// include all classes and config data
require '../../../../../config.php';
include $DIR_LIBS . 'MEDIA.php';
// media classes
sendContentType('application/xhtml+xml', 'media');
// user needs to be logged in to use this
if (!$member->isLoggedIn()) {
    media_loginAndPassThrough();
    exit;
}
// check if member is on at least one teamlist
$query = 'SELECT * FROM ' . sql_table('team') . ' WHERE tmember=' . $member->getID();
if ($manager->pluginInstalled('NP_SQLite')) {
    $teams = nucleus_mysql_query($query);
    if (nucleus_mysql_num_rows($teams) == 0) {
        media_doError(_ERROR_DISALLOWEDUPLOAD);
    }
} else {
    $teams = sql_query($query);
    if (sql_num_rows($teams) == 0) {
        media_doError(_ERROR_DISALLOWEDUPLOAD);
    }
}
// get action
$action = requestVar('action');
if ($action == '') {
    $action = 'selectmedia';
예제 #21
0
 function event_LoginFailed(&$data)
 {
     if ($this->enable_security == 'yes' && $this->max_failed_login > 0) {
         global $_SERVER;
         $login = $data['username'];
         $ip = $_SERVER['REMOTE_ADDR'];
         $lres = sql_query("SELECT * FROM " . sql_table('plug_securityenforcer') . " WHERE login='******'");
         if (sql_num_rows($lres)) {
             sql_query("UPDATE " . sql_table('plug_securityenforcer') . " SET fails=fails+1, lastfail=" . time() . " WHERE login='******'");
         } else {
             sql_query("INSERT INTO " . sql_table('plug_securityenforcer') . " (login,fails,lastfail) VALUES ('" . sql_real_escape_string($login) . "',1," . time() . ")");
         }
         $lres = sql_query("SELECT * FROM " . sql_table('plug_securityenforcer') . " WHERE login='******'");
         if (sql_num_rows($lres)) {
             sql_query("UPDATE " . sql_table('plug_securityenforcer') . " SET fails=fails+1, lastfail=" . time() . " WHERE login='******'");
         } else {
             sql_query("INSERT INTO " . sql_table('plug_securityenforcer') . " (login,fails,lastfail) VALUES ('" . sql_real_escape_string($ip) . "',1," . time() . ")");
         }
     }
     return;
 }
예제 #22
0
/**
 *  Install custom plugins
 */
function installCustomPlugs(&$manager)
{
    global $aConfPlugsToInstall, $DIR_LIBS;
    $aErrors = array();
    if (count($aConfPlugsToInstall) == 0) {
        return $aErrors;
    }
    $res = sql_query('SELECT * FROM ' . sql_table('plugin'));
    $numCurrent = sql_num_rows($res);
    foreach ($aConfPlugsToInstall as $plugName) {
        // do this before calling getPlugin (in case the plugin id is used there)
        $query = 'INSERT INTO ' . sql_table('plugin') . ' (porder, pfile) VALUES (' . ++$numCurrent . ', "' . addslashes($plugName) . '")';
        sql_query($query);
        // get and install the plugin
        $manager->clearCachedInfo('installedPlugins');
        $plugin =& $manager->getPlugin($plugName);
        $plugin->plugid = $numCurrent;
        if (!$plugin) {
            sql_query('DELETE FROM ' . sql_table('plugin') . ' WHERE pfile=\'' . addslashes($plugName) . '\'');
            $numCurrent--;
            array_push($aErrors, _ERROR22 . $plugName);
            continue;
        }
        $plugin->install();
    }
    // SYNC PLUGIN EVENT LIST
    sql_query('DELETE FROM ' . sql_table('plugin_event'));
    // loop over all installed plugins
    $res = sql_query('SELECT pid, pfile FROM ' . sql_table('plugin'));
    while ($o = sql_fetch_object($res)) {
        $pid = $o->pid;
        $plug =& $manager->getPlugin($o->pfile);
        if ($plug) {
            $eventList = $plug->getEventList();
            foreach ($eventList as $eventName) {
                sql_query('INSERT INTO ' . sql_table('plugin_event') . ' (pid, event) VALUES (' . $pid . ', \'' . $eventName . '\')');
            }
        }
    }
    return $aErrors;
}
예제 #23
0
 /**
  * Cleans up entries in the activation table. All entries older than 2 days are removed.
  * (static)
  *
  * @author dekarma
  */
 function cleanupActivationTable()
 {
     $actdays = 2;
     if (isset($CONF['ActivationDays']) && intval($CONF['ActivationDays']) > 0) {
         $actdays = intval($CONF['ActivationDays']);
     } else {
         $CONF['ActivationDays'] = 2;
     }
     $boundary = time() - 60 * 60 * 24 * $actdays;
     // 1. walk over all entries, and see if special actions need to be performed
     $res = sql_query('SELECT * FROM ' . sql_table('activation') . ' WHERE vtime < \'' . date('Y-m-d H:i:s', $boundary) . '\'');
     while ($o = sql_fetch_object($res)) {
         switch ($o->vtype) {
             case 'register':
                 // delete all information about this site member. registration is undone because there was
                 // no timely activation
                 include_once $DIR_LIBS . 'ADMIN.php';
                 ADMIN::deleteOneMember(intval($o->vmember));
                 break;
             case 'addresschange':
                 // revert the e-mail address of the member back to old address
                 list($oldEmail, $oldCanLogin) = explode('/', $o->vextra);
                 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin='******', memail=\'' . sql_real_escape_string($oldEmail) . '\' WHERE mnumber=' . intval($o->vmember));
                 break;
             case 'forgot':
                 // delete the activation link and ignore. member can request a new password using the
                 // forgot password link
                 break;
         }
     }
     // 2. delete activation entries for real
     sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vtime < \'' . date('Y-m-d H:i:s', $boundary) . '\'');
 }
예제 #24
0
function SE_unlockLogin($login)
{
    sql_query("DELETE FROM " . sql_table('plug_securityenforcer') . " WHERE login='******'");
}
예제 #25
0
function _linklist_makeSelect($mode, $data, $default = '')
{
    global $member;
    $arr = array();
    $str = '';
    $arr_def = (array) $default;
    $size = '';
    $multiple = '';
    switch ($mode) {
        case 'bid[]':
            $size = 'size="3"';
            $multiple = 'multiple="multiple"';
            $arr =& $data;
            if (count($arr) < 2) {
                //set default
                $arr_def = array_keys($arr);
            }
            if (!$member->isAdmin() and count($arr_def) == 1 and empty($arr_def[0])) {
                $arr_def[0] = array_shift(array_keys($arr));
            }
            break;
        case 'gid':
        case 'sortkey':
            //alphabet (group)
            $arr =& $data;
            break;
        case 'blogselected':
            if ($data == 0 or !preg_match("/^[0-9,]+\$/", $data)) {
                //hidden
                $arr[0] = 'ALL';
            } else {
                //get blogname from ids
                $query = sprintf("SELECT bnumber, bname FROM %s " . "WHERE bnumber IN (%s) ORDER BY bnumber", sql_table('blog'), $data);
                $res = sql_query($query);
                while ($row = mysql_fetch_assoc($res)) {
                    $arr[$row['bnumber']] = shorten($row['bname'], 15, '..');
                }
            }
            break;
    }
    $str .= <<<OUT
<select name="{$mode}" {$size} {$multiple}>
OUT;
    foreach ($arr as $key => $val) {
        $selected = in_array($key, $arr_def) ? 'selected="selected"' : '';
        if ($mode == 'bid[]') {
            $val = "{$key}:{$val}";
        }
        $str .= <<<OUT
<option value="{$key}" {$selected}>{$val}</option>
OUT;
    }
    $str .= "</select>";
    return $str;
}
예제 #26
0
 function DefaultSkin()
 {
     $_ = htmlspecialchars($this->getOption('spskinname'), ENT_QUOTES, _CHARSET);
     if (empty($_)) {
         $sql = sprintf('SELECT sdname FROM `%s` ORDER BY `sdname` ASC', sql_table('skin_desc'));
         $res = sql_fetch_assoc(sql_query($sql));
         $_ = $res['sdname'];
     }
     $this->setOption('spskinname', $_);
     return $_;
 }
예제 #27
0
 function getDesc($id)
 {
     $query = 'SELECT tddesc FROM ' . sql_table('template_desc') . ' WHERE tdnumber=' . intval($id);
     $res = sql_query($query);
     $obj = sql_fetch_object($res);
     return $obj->tddesc;
 }
예제 #28
0
 /**
  * static: returns an array of friendly names
  */
 function getFriendlyNames()
 {
     $skintypes = array('index' => _SKIN_PART_MAIN, 'item' => _SKIN_PART_ITEM, 'archivelist' => _SKIN_PART_ALIST, 'archive' => _SKIN_PART_ARCHIVE, 'search' => _SKIN_PART_SEARCH, 'error' => _SKIN_PART_ERROR, 'member' => _SKIN_PART_MEMBER, 'imagepopup' => _SKIN_PART_POPUP);
     $query = "SELECT stype FROM " . sql_table('skin') . " WHERE stype NOT IN ('index', 'item', 'error', 'search', 'archive', 'archivelist', 'imagepopup', 'member')";
     $res = sql_query($query);
     while ($row = sql_fetch_array($res)) {
         $skintypes[strtolower($row['stype'])] = ucfirst($row['stype']);
     }
     return $skintypes;
 }
 function checkTBVersion()
 {
     $res = sql_query('SHOW FIELDS FROM ' . sql_table('plugin_tb'));
     $fieldnames = array();
     while ($co = sql_fetch_assoc($res)) {
         $fieldnames[] = $co['Field'];
     }
     if (in_array('block', $fieldnames)) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
예제 #30
0
 /**
  * Adds a new comment to the database
  * @param string $timestamp
  * @param array $comment
  * @return mixed
  */
 function addComment($timestamp, $comment)
 {
     global $CONF, $member, $manager;
     $blogid = getBlogIDFromItemID($this->itemid);
     $settings =& $manager->getBlog($blogid);
     $settings->readSettings();
     // begin if: comments disabled
     if (!$settings->commentsEnabled()) {
         return _ERROR_COMMENTS_DISABLED;
     }
     // end if
     // begin if: public cannot comment
     if (!$settings->isPublic() && !$member->isLoggedIn()) {
         return _ERROR_COMMENTS_NONPUBLIC;
     }
     // end if
     // begin if: comment uses a protected member name
     if ($CONF['ProtectMemNames'] && !$member->isLoggedIn() && MEMBER::isNameProtected($comment['user'])) {
         return _ERROR_COMMENTS_MEMBERNICK;
     }
     // end if
     // begin if: email required, but missing (doesn't apply to members)
     if ($settings->emailRequired() && strlen($comment['email']) == 0 && !$member->isLoggedIn()) {
         return _ERROR_EMAIL_REQUIRED;
     }
     // end if
     ## Note usage of mb_strlen() vs strlen() below ##
     // begin if: commenter's name is too long
     if (mb_strlen($comment['user']) > 40) {
         return _ERROR_USER_TOO_LONG;
     }
     // end if
     // begin if: commenter's email is too long
     if (mb_strlen($comment['email']) > 100) {
         return _ERROR_EMAIL_TOO_LONG;
     }
     // end if
     // begin if: commenter's url is too long
     if (mb_strlen($comment['userid']) > 100) {
         return _ERROR_URL_TOO_LONG;
     }
     // end if
     $comment['timestamp'] = $timestamp;
     $comment['host'] = gethostbyaddr(serverVar('REMOTE_ADDR'));
     $comment['ip'] = serverVar('REMOTE_ADDR');
     // begin if: member is logged in, use that data
     if ($member->isLoggedIn()) {
         $comment['memberid'] = $member->getID();
         $comment['user'] = '';
         $comment['userid'] = '';
         $comment['email'] = '';
     } else {
         $comment['memberid'] = 0;
     }
     // spam check
     $continue = FALSE;
     $plugins = array();
     if (isset($manager->subscriptions['ValidateForm'])) {
         $plugins = array_merge($plugins, $manager->subscriptions['ValidateForm']);
     }
     if (isset($manager->subscriptions['PreAddComment'])) {
         $plugins = array_merge($plugins, $manager->subscriptions['PreAddComment']);
     }
     if (isset($manager->subscriptions['PostAddComment'])) {
         $plugins = array_merge($plugins, $manager->subscriptions['PostAddComment']);
     }
     $plugins = array_unique($plugins);
     while (list(, $plugin) = each($plugins)) {
         $p = $manager->getPlugin($plugin);
         $continue = $continue || $p->supportsFeature('handleSpam');
     }
     $spamcheck = array('type' => 'comment', 'body' => $comment['body'], 'id' => $comment['itemid'], 'live' => TRUE, 'return' => $continue);
     // begin if: member logged in
     if ($member->isLoggedIn()) {
         $spamcheck['author'] = $member->displayname;
         $spamcheck['email'] = $member->email;
     } else {
         $spamcheck['author'] = $comment['user'];
         $spamcheck['email'] = $comment['email'];
         $spamcheck['url'] = $comment['userid'];
     }
     // end if
     $manager->notify('SpamCheck', array('spamcheck' => &$spamcheck));
     if (!$continue && isset($spamcheck['result']) && $spamcheck['result'] == TRUE) {
         return _ERROR_COMMENTS_SPAM;
     }
     // isValidComment returns either "1" or an error message
     $isvalid = $this->isValidComment($comment, $spamcheck);
     if ($isvalid != 1) {
         return $isvalid;
     }
     // begin if: send email to notification address
     if ($settings->getNotifyAddress() && $settings->notifyOnComment()) {
         $mailto_msg = _NOTIFY_NC_MSG . ' ' . $this->itemid . "\n";
         //			$mailto_msg .= $CONF['IndexURL'] . 'index.php?itemid=' . $this->itemid . "\n\n";
         $temp = parse_url($CONF['Self']);
         if ($temp['scheme']) {
             $mailto_msg .= createItemLink($this->itemid) . "\n\n";
         } else {
             $tempurl = $settings->getURL();
             if (substr($tempurl, -1) == '/' || substr($tempurl, -4) == '.php') {
                 $mailto_msg .= $tempurl . '?itemid=' . $this->itemid . "\n\n";
             } else {
                 $mailto_msg .= $tempurl . '/?itemid=' . $this->itemid . "\n\n";
             }
         }
         if ($comment['memberid'] == 0) {
             $mailto_msg .= _NOTIFY_USER . ' ' . $comment['user'] . "\n";
             $mailto_msg .= _NOTIFY_USERID . ' ' . $comment['userid'] . "\n";
         } else {
             $mailto_msg .= _NOTIFY_MEMBER . ' ' . $member->getDisplayName() . ' (ID=' . $member->getID() . ")\n";
         }
         $mailto_msg .= _NOTIFY_HOST . ' ' . $comment['host'] . "\n";
         $mailto_msg .= _NOTIFY_COMMENT . "\n " . $comment['body'] . "\n";
         $mailto_msg .= getMailFooter();
         $item =& $manager->getItem($this->itemid, 0, 0);
         $mailto_title = _NOTIFY_NC_TITLE . ' ' . strip_tags($item['title']) . ' (' . $this->itemid . ')';
         $frommail = $member->getNotifyFromMailAddress($comment['email']);
         $notify =& new NOTIFICATION($settings->getNotifyAddress());
         $notify->notify($mailto_title, $mailto_msg, $frommail);
     }
     $comment = COMMENT::prepare($comment);
     $manager->notify('PreAddComment', array('comment' => &$comment, 'spamcheck' => &$spamcheck));
     $name = sql_real_escape_string($comment['user']);
     $url = sql_real_escape_string($comment['userid']);
     $email = sql_real_escape_string($comment['email']);
     $body = sql_real_escape_string($comment['body']);
     $host = sql_real_escape_string($comment['host']);
     $ip = sql_real_escape_string($comment['ip']);
     $memberid = intval($comment['memberid']);
     $timestamp = date('Y-m-d H:i:s', $comment['timestamp']);
     $itemid = $this->itemid;
     $qSql = 'SELECT COUNT(*) AS result ' . 'FROM ' . sql_table('comment') . ' WHERE ' . 'cmail   = "' . $url . '"' . ' AND cmember = "' . $memberid . '"' . ' AND cbody   = "' . $body . '"' . ' AND citem   = "' . $itemid . '"' . ' AND cblog   = "' . $blogid . '"';
     $result = (int) quickQuery($qSql);
     if ($result > 0) {
         return _ERROR_BADACTION;
     }
     $query = 'INSERT INTO ' . sql_table('comment') . ' (CUSER, CMAIL, CEMAIL, CMEMBER, CBODY, CITEM, CTIME, CHOST, CIP, CBLOG) ' . "VALUES ('{$name}', '{$url}', '{$email}', {$memberid}, '{$body}', {$itemid}, '{$timestamp}', '{$host}', '{$ip}', '{$blogid}')";
     sql_query($query);
     // post add comment
     $commentid = sql_insert_id();
     $manager->notify('PostAddComment', array('comment' => &$comment, 'commentid' => &$commentid, 'spamcheck' => &$spamcheck));
     // succeeded !
     return TRUE;
 }