function getVendors( ) { global $db; $query = "select * from Vendors"; if (!$result = $db->sql_query($query)) { RestLog("Error 16522 in query: $query\n".$db->sql_error()); RestUtils::sendResponse(500, "16522 - There was a problem attempting to locate the PO"); //Internal Server Error return false; } $i = 0; while ( $row = $db->sql_fetchrow( $result ) ) { $vendors[$i]['VendorID'] = $row['VendorID']; $vendors[$i]['VendorName'] = $row['VendorName']; $i++; } RestLog("Successful Request\n"); //08.10.2012 naj - return code 200 OK. RestUtils::sendResponse(200,json_encode( stripHTML( $vendors ) )); return true; }
function printMobileEntryListView($entries, $listid, $title, $paging, $count = 0, $header = true) { $context = Model_Context::getInstance(); $itemsView = '<ul data-role="listview" class="posts" id="' . $listid . '" title="' . $title . '" selected="false" data-inset="true">' . CRLF; if ($header) { $itemsView .= '<li class="group ui-bar ui-bar-e">' . CRLF; $itemsView .= ' <h3>' . $title . '</h3>' . CRLF; $itemsView .= ' <span class="ui-li-count">' . $count . '</span>' . CRLF; $itemsView .= ' <span class="ui-li-aside">' . _text('페이지') . ' ' . $paging['page'] . ' / ' . $paging['pages'] . '</span>' . CRLF; $itemsView .= '</li>' . CRLF; } foreach ($entries as $item) { $author = User::getName($item['userid']); if ($imageName = printMobileAttachmentExtract($item['content'])) { $imageSrc = printMobileImageResizer($context->getProperty('blog.id'), $imageName, 80); } else { $imageSrc = $context->getProperty('service.path') . '/resources/style/iphone/images/noPostThumb.png'; } $itemsView .= '<li data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-bar-b ui-btn-up-c" style="font-size:8pt;font-weight:normal">'; $itemsView .= ' ' . Timestamp::format5($item['published']) . '</li>' . CRLF; $itemsView .= '<li class="post_item">' . CRLF; $itemsView .= ' <a href="' . $context->getProperty('uri.blog') . '/entry/' . $item['id'] . '" class="link">' . CRLF; $itemsView .= ' <img src="' . $imageSrc . '" />' . CRLF; $itemsView .= ' <h3>' . fireEvent('ViewListTitle', htmlspecialchars($item['title'])) . '</h3>' . CRLF; $itemsView .= ' <p class="ui-li-count"> ' . _textf('댓글 %1개', $item['comments'] > 0 ? $item['comments'] : 0) . '</p>' . CRLF; if (!empty($item['content'])) { $itemsView .= ' <p>' . htmlspecialchars(Utils_Unicode::lessenAsEm(removeAllTags(stripHTML($item['content'])), 150)) . '</p>' . CRLF; } $itemsView .= ' </a>' . CRLF; $itemsView .= '</li>' . CRLF; } $itemsView .= '</ul>' . CRLF; return $itemsView; }
function FM_TTML_summary($blogid, $id, $content, $keywords = array(), $useAbsolutePath = true) { global $blog; $view = FM_TTML_format($blogid, $id, $content, $keywords, $useAbsolutePath, true); if (!$blog['publishWholeOnRSS']) { $view = Utils_Unicode::lessen(removeAllTags(stripHTML($view)), 255); } return $view; }
function FM_Textile_summary($blogid, $id, $content, $keywords = array(), $useAbsolutePath = true) { $context = Model_Context::getInstance(); $view = FM_Textile_format($blogid, $id, $content, $keywords, $useAbsolutePath, true); if (!$context->getProperty("blog.publishWholeOnRSS")) { $view = Utils_Unicode::lessen(removeAllTags(stripHTML($view)), 255); } return $view; }
function getItemInfo($vars, $responsetype) { global $db; $ar = $vars; if (empty($ar) || !isset($ar['VendorID']) || !isset($ar['ItemNumber'])) { RestLog("16584 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n"); RestUtils::sendResponse(400, "16584 - Insufficient data provided"); //Internal Server Error return false; } //now we grab inventory records for the requested item and build up our package to return //to the dealer //08.28.2015 ghh - added weight field $query = "select Items.ItemID, Items.MSRP, NLA, CloseOut,\n\t\t\t\tPriceCode, Cost, MAP, Category, \n\t\t\t\tManufItemNumber, ManufName, SupersessionID, Weight\n\t\t\t\tfrom Items\n\t\t\t\twhere \n\t\t\t\tItemNumber='{$ar['ItemNumber']}' and\n\t\t\t\tVendorID={$ar['VendorID']}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16585 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16585 - There was a problem getting item information."); //Internal Server Error return false; } $row = $db->sql_fetchrow($result); $item['OrigManufName'] = $row['ManufName']; $item['OrigManufNumber'] = $row['ManufItemNumber']; $item['NLA'] = $row['NLA']; $item['CloseOut'] = $row['CloseOut']; $item['MSRP'] = $row['MSRP']; $item['Category'] = $row['Category']; $item['MAP'] = $row['MAP']; $item['Weight'] = $row['Weight']; //08.28.2015 ghh - if ($row['ItemID'] > 0) { $item['Cost'] = getItemCost($row['ItemID'], $ar['DealerID'], $row['PriceCode'], $row['Cost'], $row['MSRP']); } //08.25.2015 ghh - if BSV asked for full detail then we're also going to send back //images data and other items of interest if ($row['SupersessionID'] > 0) { $query = "select ItemNumber from Items where ItemID={$row['SupersessionID']}"; if (!($tmpresult = $db->sql_query($query))) { RestLog("Error 16586 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16586 - There was a problem retrieving the supersession number"); //Internal Server Error return false; } $tmprow = $db->sql_fetchrow($tmpresult); $item['SupersessionNumber'] = $tmprow['ItemNumber']; } RestLog("Successful Request\n"); //08.10.2012 naj - return code 200 OK. RestUtils::sendResponse(200, json_encode(stripHTML($item))); return true; }
/** * 函数名称:filterStr * 功能描述:对字符串、数组等进行过滤 * @param $arr * @return array|null|string */ function filterStr($arr) { if (!isset($arr)) { return null; } if (is_array($arr)) { foreach ($arr as $k => $v) { $arr[$k] = filter(stripSQLChars(stripHTML(trim($v), true))); } } else { $arr = filter(stripSQLChars(stripHTML(trim($arr), true))); } return $arr; }
/** * @brief Syndicating routine. * @see Tag, User, DBModel, Model_Context */ function SyndicateToEolin($entryId, $entry, $mode) { $context = Model_Context::getInstance(); $blogid = $context->getProperty('blog.id'); $rpc = new XMLRPC(); $rpc->url = 'http://ping.eolin.com/'; $summary = array('blogURL' => $context->getProperty('uri.default'), 'syncURL' => $context->getProperty('uri.default') . "/plugin/abstractToEolin?entryId={$entryId}"); if ($mode == 'create') { $summary['blogTitle'] = $context->getProperty('blog.title'); $summary['language'] = $context->getProperty('blog.language'); $summary['permalink'] = $context->getProperty('uri.default') . "/" . ($context->getProperty('blog.useSloganOnPost') ? "entry/{$entry['slogan']}" : $entry['id']); $summary['title'] = Utils_Unicode::lessenAsByte($entry['title'], 255); $summary['content'] = Utils_Unicode::lessenAsByte(stripHTML(getEntryContentView($blogid, $entry['id'], $entry['content'], $entry['contentformatter'])), 1023, ''); $summary['author'] = User::authorName($entry['userid'], $entryId); $summary['tags'] = Tag::getTagsWithEntryId($blogid, $entry); $summary['location'] = $entry['location']; $summary['written'] = Timestamp::getRFC1123($entry['published']); } return $rpc->call("sync.{$mode}", $summary); }
function updateComment($blogid, $comment, $password) { $openid = Acl::getIdentity('openid'); if (!doesHaveOwnership()) { // if filtered, only block and not send to trash if (!Filter::isAllowed($comment['homepage'])) { if (Filter::isFiltered('ip', $comment['ip'])) { return 'blocked'; } if (Filter::isFiltered('name', $comment['name'])) { return 'blocked'; } if (Filter::isFiltered('url', $comment['homepage'])) { return 'blocked'; } if (Filter::isFiltered('content', $comment['comment'])) { return 'blocked'; } if (!fireEvent('ModifyingComment', true, $comment)) { return 'blocked'; } } } $pool = DBModel::getInstance(); $comment['homepage'] = stripHTML($comment['homepage']); $comment['name'] = Utils_Unicode::lessenAsEncoding($comment['name'], 80); $comment['homepage'] = Utils_Unicode::lessenAsEncoding($comment['homepage'], 80); $comment['comment'] = Utils_Unicode::lessenAsEncoding($comment['comment'], 65535); $guestcomment = false; $pool->reset('Comments'); $pool->setQualifier('blogid', 'eq', $blogid); $pool->setQualifier('id', 'eq', $comment['id']); $pool->setQualifier('replier', 'eq', NULL); if ($pool->doesExist()) { $guestcomment = true; } $pool->reset('Comments'); $setPassword = ''; $userid = getUserId(); if (!empty($userid)) { $comment['replier'] = $userid; $name = User::getName($userid); $homepage = User::getHomepage($userid); $pool->setAttribute('password', '', true); if (empty($homepage) && $openid) { $homepage = $openid; } } else { $name = $comment['name']; if ($comment['password'] !== true) { $pool->setAttribute('password', empty($comment['password']) ? '' : md5($comment['password']), true); } $homepage = $comment['homepage']; } $comment0 = $comment['comment']; $wherePassword = ''; if (!doesHaveOwnership()) { if ($guestcomment == false) { if (!doesHaveMembership()) { return false; } $pool->setQualifier('replier', 'eq', $userid); } else { if (empty($password) && $openid) { $pool->setQualifier('openid', 'eq', $openid, true); } else { $pool->setQualifier('password', 'eq', md5($password), true); } } } $replier = is_null($comment['replier']) ? NULL : $comment['replier']; $pool->setAttribute('name', $name, true); $pool->setAttribute('homepage', $homepage, true); $pool->setAttribute('secret', $comment['secret']); $pool->setAttribute('comment', $comment0, true); $pool->setAttribute('ip', $comment['ip'], true); $pool->setAttribute('written', Timestamp::getUNIXtime()); $pool->setAttribute('isfiltered', $comment['isfiltered']); $pool->setAttribute('replier', $replier); $pool->setQualifier('blogid', 'eq', $blogid); $pool->setQualifier('id', 'eq', $comment['id']); $result = $pool->update(); if ($result) { CacheControl::flushCommentRSS($comment['entry']); // Assume blogid = current blogid. CacheControl::flushDBCache('comment'); return true; } else { return false; } }
function sendTrackback($blogid, $entryId, $url) { importlib('model.blog.entry'); importlib('model.blog.keyword'); $context = Model_Context::getInstance(); $entry = getEntry($blogid, $entryId); if (is_null($entry)) { return false; } $link = $context->getProperty('uri.default') . "/" . $entryId; $title = htmlspecialchars($entry['title']); $entry['content'] = getEntryContentView($blogid, $entryId, $entry['content'], $entry['contentformatter'], getKeywordNames($blogid)); $excerpt = str_tag_on(Utils_Unicode::lessen(removeAllTags(stripHTML($entry['content'])), 255)); $blogTitle = $context->getProperty('blog.title'); $isNeedConvert = strpos($url, '/rserver.php?') !== false || strpos($url, 'blog.naver.com/tb') !== false || strpos($url, 'news.naver.com/tb/') !== false || strpos($url, 'blog.empas.com') !== false || strpos($url, 'blog.yahoo.com') !== false || strpos($url, 'www.blogin.com/tb/') !== false || strpos($url, 'cytb.cyworld.nate.com') !== false || strpos($url, 'www.cine21.com/Movies/tb.php') !== false; if ($isNeedConvert) { $title = Utils_Unicode::convert($title, 'EUC-KR'); $excerpt = Utils_Unicode::convert($excerpt, 'EUC-KR'); $blogTitle = Utils_Unicode::convert($blogTitle, 'EUC-KR'); $content = "url=" . rawurlencode($link) . "&title=" . rawurlencode($title) . "&blog_name=" . rawurlencode($blogTitle) . "&excerpt=" . rawurlencode($excerpt); $request = new HTTPRequest('POST', $url); $request->contentType = 'application/x-www-form-urlencoded; charset=euc-kr'; $isSuccess = $request->send($content); } else { $content = "url=" . rawurlencode($link) . "&title=" . rawurlencode($title) . "&blog_name=" . rawurlencode($blogTitle) . "&excerpt=" . rawurlencode($excerpt); $request = new HTTPRequest('POST', $url); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; $isSuccess = $request->send($content); } if ($isSuccess && checkResponseXML($request->responseText) === 0) { $trackbacklog = new TrackbackLog(); $trackbacklog->entry = $entryId; $trackbacklog->url = Utils_Unicode::lessenAsEncoding($url, 255); $trackbacklog->add(); return true; } return false; }
function truncate($content, $size = 50, $final = "…", $stripHTML = false, $preserveEOL = false) { $hasn = false; if ($stripHTML) { $content = str_replace("\"", "'", stripHTML(str_replace("\n", "", $content), $preserveEOL)); if ($preserveEOL) { $content = str_replace("<br/>", "\n", $content); $hasn = strpos($content, "\n") !== false; } } // avoids amp codes being cut $len = strlen($content); $amp = strpos($content, '&', $size - 5 >= 0 && $size - 5 < $len ? $size - 5 : 0); if ($amp > 0 && $amp <= $size) { $ampf = strpos($content, ';', $amp); if ($ampf >= $size) { return ($preserveEOL ? str_replace("\n", "<br/>", substr($content, 0, $amp - 1)) : substr($content, 0, $amp - 1)) . ($hasn ? "\n" : "") . $final; } } if ($len > $size) { if ($len <= $size - strlen($final)) { // barelly on the limit return ($preserveEOL ? str_replace("\n", "<br/>", $content) : $content) . $final; } else { // under the limit, cut utf8 to avoid issues return ($preserveEOL ? str_replace("\n", "<br/>", utf8_truncate($content, $size - strlen($final))) : utf8_truncate($content, $size - strlen($final))) . $final . " "; } } else { // not greater return ($preserveEOL ? str_replace("\n", "<br/>", $content) : $content) . ""; } }
function sendTrackback($blogid, $entryId, $url) { global $defaultURL, $blog; requireModel('blog.entry'); requireModel('blog.keyword'); $entry = getEntry($blogid, $entryId); if (is_null($entry)) { return false; } $link = "{$defaultURL}/{$entryId}"; $title = htmlspecialchars($entry['title']); $entry['content'] = getEntryContentView($blogid, $entryId, $entry['content'], $entry['contentformatter'], getKeywordNames($blogid)); $excerpt = str_tag_on(UTF8::lessen(removeAllTags(stripHTML($entry['content'])), 255)); $blogTitle = $blog['title']; $isNeedConvert = strpos($url, '/rserver.php?') !== false || strpos($url, 'blog.naver.com/tb') !== false || strpos($url, 'news.naver.com/tb/') !== false || strpos($url, 'blog.empas.com') !== false || strpos($url, 'blog.yahoo.com') !== false || strpos($url, 'www.blogin.com/tb/') !== false || strpos($url, 'cytb.cyworld.nate.com') !== false || strpos($url, 'www.cine21.com/Movies/tb.php') !== false; if ($isNeedConvert) { $title = UTF8::convert($title, 'EUC-KR'); $excerpt = UTF8::convert($excerpt, 'EUC-KR'); $blogTitle = UTF8::convert($blogTitle, 'EUC-KR'); $content = "url=" . rawurlencode($link) . "&title=" . rawurlencode($title) . "&blog_name=" . rawurlencode($blogTitle) . "&excerpt=" . rawurlencode($excerpt); $request = new HTTPRequest('POST', $url); $request->contentType = 'application/x-www-form-urlencoded; charset=euc-kr'; $isSuccess = $request->send($content); } else { $content = "url=" . rawurlencode($link) . "&title=" . rawurlencode($title) . "&blog_name=" . rawurlencode($blogTitle) . "&excerpt=" . rawurlencode($excerpt); $request = new HTTPRequest('POST', $url); $request->contentType = 'application/x-www-form-urlencoded; charset=utf-8'; $isSuccess = $request->send($content); } if ($isSuccess && checkResponseXML($request->responseText) === 0) { // $url = POD::escapeString(UTF8::lessenAsEncoding($url, 255)); $trackbacklog = new TrackbackLog(); $trackbacklog->entry = $entryId; $trackbacklog->url = POD::escapeString(UTF8::lessenAsEncoding($url, 255)); $trackbacklog->add(); // POD::query("INSERT INTO {$database['prefix']}TrackbackLogs VALUES ($blogid, '', $entryId, '$url', UNIX_TIMESTAMP())"); return true; } return false; }
function getRemoteFeed($url) { global $service, $serviceURL; $xml = fireEvent('GetRemoteFeed', null, $url); if (empty($xml)) { $request = new HTTPRequest($url); $request->referer = $serviceURL; $request->timeout = 3; if (!$request->send()) { return array(2, null, null); } $xml = $request->responseText; } $feed = array('xmlurl' => isset($request) ? $request->url : $url); $xmls = new XMLStruct(); if (!$xmls->open($xml, $service['encoding'])) { if (preg_match_all('/<link .*?rel\\s*=\\s*[\'"]?alternate.*?>/i', $xml, $matches)) { foreach ($matches[0] as $link) { $attributes = Utils_Misc::getAttributesFromString($link); if (isset($attributes['href'])) { $urlInfo = parse_url($url); $rssInfo = parse_url($attributes['href']); $rssURL = false; if (isset($rssInfo['scheme']) && $rssInfo['scheme'] == 'http') { $rssURL = $attributes['href']; } else { if (isset($rssInfo['path'])) { if ($rssInfo['path'][0] == '/') { $rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}{$rssInfo['path']}"; } else { $rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}" . (isset($urlInfo['path']) ? rtrim($urlInfo['path'], '/') : '') . '/' . $rssInfo['path']; } } } if ($rssURL && $url != $rssURL) { return getRemoteFeed($rssURL); } } } } return array(3, null, null); } if ($xmls->getAttribute('/rss', 'version')) { $feed['blogURL'] = $xmls->getValue('/rss/channel/link'); $feed['title'] = $xmls->getValue('/rss/channel/title'); $feed['description'] = $xmls->getValue('/rss/channel/description'); if (Validator::language($xmls->getValue('/rss/channel/language'))) { $feed['language'] = $xmls->getValue('/rss/channel/language'); } else { if (Validator::language($xmls->getValue('/rss/channel/dc:language'))) { $feed['language'] = $xmls->getValue('/rss/channel/dc:language'); } else { $feed['language'] = 'en-US'; } } $feed['modified'] = gmmktime(); } else { if ($xmls->doesExist('/feed')) { $feed['blogURL'] = $xmls->getAttribute('/feed/link', 'href'); $feed['title'] = $xmls->getValue('/feed/title'); $feed['description'] = $xmls->getValue('/feed/tagline'); if (Validator::language($xmls->getAttribute('/feed', 'xml:lang'))) { $feed['language'] = $xmls->getAttribute('/feed', 'xml:lang'); } else { $feed['language'] = 'en-US'; } $feed['modified'] = gmmktime(); } else { if ($xmls->getAttribute('/rdf:RDF', 'xmlns')) { if ($xmls->getAttribute('/rdf:RDF/channel/link', 'href')) { $feed['blogURL'] = $xmls->getAttribute('/rdf:RDF/channel/link', 'href'); } else { if ($xmls->getValue('/rdf:RDF/channel/link')) { $feed['blogURL'] = $xmls->getValue('/rdf:RDF/channel/link'); } else { $feed['blogURL'] = ''; } } $feed['title'] = $xmls->getValue('/rdf:RDF/channel/title'); $feed['description'] = $xmls->getValue('/rdf:RDF/channel/description'); if (Validator::language($xmls->getValue('/rdf:RDF/channel/dc:language'))) { $feed['language'] = $xmls->getValue('/rdf:RDF/channel/dc:language'); } else { if (Validator::language($xmls->getAttribute('/rdf:RDF', 'xml:lang'))) { $feed['language'] = $xmls->getAttribute('/rdf:RDF', 'xml:lang'); } else { $feed['language'] = 'en-US'; } } $feed['modified'] = gmmktime(); } else { return array(3, null, null); } } } $feed['xmlurl'] = POD::escapeString(Utils_Unicode::lessenAsEncoding(Utils_Unicode::correct($feed['xmlurl']))); $feed['blogURL'] = POD::escapeString(Utils_Unicode::lessenAsEncoding(Utils_Unicode::correct($feed['blogURL']))); $feed['title'] = POD::escapeString(Utils_Unicode::lessenAsEncoding(Utils_Unicode::correct($feed['title']))); $feed['description'] = POD::escapeString(Utils_Unicode::lessenAsEncoding(Utils_Unicode::correct(stripHTML($feed['description'])))); $feed['language'] = POD::escapeString(Utils_Unicode::lessenAsEncoding(Utils_Unicode::correct($feed['language']), 255)); return array(0, $feed, $xml); }
function sendOrder($vars, $responsetype) { global $db; $ar = json_decode($vars['Data']['Data'], true, 5); if (empty($ar) || !isset($ar['PONumber']) || !isset($ar['Status']) || empty($ar['Items']) && empty($ar['Units'])) { RestLog("16521 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n"); RestUtils::sendResponse(400, "16521 - Insufficient data provided"); //Internal Server Error return false; } //08.21.2015 ghh - before we get started we need to see if the current dealer //already has a PO in the system matching what they are now sending. If so we're //going to be updating it if its pending or if it hasn't been pulled by the primary //vendor system yet. $query = "select POID, Status from PurchaseOrders where PONumber='{$ar['PONumber']}' and\n\t\t\t\tDealerID={$vars['DealerID']}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16522 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16522 - There was a problem attempting to locate the PO"); //Internal Server Error return false; } //if we have no purchase order at all then we're going to be inserting a new one if ($db->sql_numrows($result) == 0) { $shiptofields = ''; $shiptovals = ''; if ($ar['ShipToAddress1'] != '') { $shiptofields = "ShipToFirstName, ShipToLastName, ShipToCompany,\n\t\t\t\t\t\t\t\tShipToAddress1, ShipToAddress2, ShipToCity, ShipToState,\n\t\t\t\t\t\t\t\tShipToZip, ShipToCountry, ShipToPhone, ShipToEmail,"; if ($ar['ShipToFirstName'] == '') { $shiptovals = "'',"; } else { $shiptovals = "'{$ar['ShipToFirstName']}',"; } if ($ar['ShipToLastName'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToLastName']}',"; } if ($ar['ShipToCompany'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToCompany']}',"; } if ($ar['ShipToAddress1'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToAddress1']}',"; } if ($ar['ShipToAddress2'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToAddress2']}',"; } if ($ar['ShipToCity'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToCity']}',"; } if ($ar['ShipToState'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToState']}',"; } if ($ar['ShipToZip'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToZip']}',"; } if ($ar['ShipToCountry'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToCountry']}',"; } if ($ar['ShipToPhone'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToPhone']}',"; } if ($ar['ShipToEmail'] == '') { $shiptovals .= "'',"; } else { $shiptovals .= "'{$ar['ShipToEmail']}',"; } if ($ar['PaymentMethod'] == '') { $shiptovals .= "1,"; } else { $shiptovals .= "'{$ar['PaymentMethod']}',"; } if ($ar['ShipMethod'] == '') { $shiptovals .= "1,"; } else { $shiptovals .= "'{$ar['ShipMethod']}',"; } } $query = "insert into PurchaseOrders (Status, DealerID, BSVKeyID, PONumber,\n\t\t\t\tDateCreated, {$shiptofields} LastFour,OrderType) values \n\t\t\t\t( {$ar['Status']}, {$vars['DealerID']}, {$vars['BSVKeyID']}, '{$ar['PONumber']}', now(),\n\t\t\t\t{$shiptovals} '{$ar['LastFour']}',{$ar['OrderType']} )\n\t\t\t\t"; } else { //if we do have a purchase order we need to determine if its ok to update it or not //and return error if its not. $row = $db->sql_fetchrow($result); $poid = $row['POID']; //08.21.2015 ghh - if the status is greater than 2 it means the supplier has already //started pulling the order and we can no longer update it. In this case we're going //to die and return error if ($row['Status'] > 2) { RestLog("Purchase has already been pulled by supplier {$ar['PONumber']}\n"); RestUtils::sendResponse(409, "Order has already been pulled by supplier"); //Internal Server Error return false; } //if we reach here then it must be ok to update the purchase order data so will build the //query here $query = "update PurchaseOrders set "; if ($ar['ShipToAddress1'] != '') { if ($ar['ShipToFirstName'] != '') { $query1 .= "ShipToFirstName='{$ar['ShipToFirstName']}',"; } if ($ar['ShipToLastName'] != '') { $query1 .= "ShipToLastName='{$ar['ShipToLastName']}',"; } if ($ar['ShipToCompany'] != '') { $query1 .= "ShipToCompany='{$ar['ShipToCompany']}',"; } if ($ar['ShipToAddress1'] != '') { $query1 .= "ShipToAddress1='{$ar['ShipToAddress1']}',"; } if ($ar['ShipToAddress2'] != '') { $query1 .= "ShipToAddress2='{$ar['ShipToAddress2']}',"; } if ($ar['ShipToCity'] != '') { $query1 .= "ShipToCity='{$ar['ShipToCity']}',"; } if ($ar['ShipToState'] != '') { $query1 .= "ShipToState='{$ar['ShipToState']}',"; } if ($ar['ShipToZip'] != '') { $query1 .= "ShipToZip='{$ar['ShipToZip']}',"; } if ($ar['ShipToCountry'] != '') { $query1 .= "ShipToCountry='{$ar['ShipToCountry']}',"; } if ($ar['ShipToPhone'] != '') { $query1 .= "ShipToPhone='{$ar['ShipToPhone']}',"; } if ($ar['ShipToEmail'] != '') { $query1 .= "ShipToEmail='{$ar['ShipToEmail']}',"; } } if ($ar['PaymentMethod'] != '') { $query1 .= "PaymentMethod={$ar['PaymentMethod']},"; } if ($ar['LastFour'] != '') { $query1 .= "LastFour='{$ar['LastFour']}',"; } if ($ar['ShipMethod'] != '') { $query1 .= "ShipMethod='{$ar['ShipMethod']}',"; } //if we are actually updating the PO then we're also going ot update the //poreceiveddate if ($query1 != '') { $query1 .= " DateLastModified=now() "; $query .= "{$query1} where DealerID={$vars['DealerID']} and PONumber='{$ar['PONumber']}'"; } else { $query = ''; } } //08.21.2015 ghh - now we execute either of the two queries above to update or insert //the purchase order itself. if ($query != '') { if (!($result = $db->sql_query($query))) { RestLog("Error 16523 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16523 - There was a problem attempting to insert/update the PO"); return false; } } //if we don't already have a poid then we must have done an insert so we'll grab it now if (!$poid > 0) { $poid = $db->sql_nextid($result); } ####################################################PARTS########################################### //now that the purchase order has been updated we'll next start taking a look //at the items and units arrays //08.21.2015 rch - we need to loop through each item that is passed in and evaluate whether or not //we are inserting the po or updating the po $i = 0; foreach ($ar['Items'] as $value => $key) { //08.21.2015 rch - first we need to see if the item is already on the order $query = "select POItemID, Quantity \n\t\t\t\t\tfrom PurchaseOrderItems\n\t\t\t\t\twhere POID='{$poid}' and ItemNumber = '{$key['ItemNumber']}'\n\t\t\t\t\tand VendorID = '{$key['VendorID']}'"; if (!($result = $db->sql_query($query))) { RestLog("Error 16524 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16524 - There was an error locating purchase order items"); return false; } //08.21.2015 rch - we want to make sure that we have a partnumber and vendorid //before attempting to insert. if ($key['ItemNumber'] != '' && $key['VendorID'] != '') { //08.21.2015 ghh - before we bother inserting the item we're going to first grab some //details from items so we can build up our response. $query = "select ItemID, NLA, CloseOut, PriceCode, Category, SupersessionID, \n\t\t\t\t\tMSRP, Cost\n\t\t\t\t\tfrom\n\t\t\t\t\tItems where ItemNumber='{$key['ItemNumber']}' and VendorID={$key['VendorID']}"; if (!($itemresult = $db->sql_query($query))) { RestLog("Error 16526 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16526 - There was an error locating the order item"); return false; } $itemrow = $db->sql_fetchrow($itemresult); if ($db->sql_numrows($itemresult) == 0) { RestLog("Error 16545 The ItemNumber or VendorID you sent are not valid"); RestUtils::sendResponse(500, "16545 - The Item Number or VendorID passed are invalid"); return false; } //now lets see if we can calculate the cost for the current dealer $cost = getItemCost($itemrow['ItemID'], $vars['DealerID'], $itemrow['PriceCode'], $itemrow['Cost'], $itemrow['MSRP']); } else { RestLog("{$row['PONumber']} is missing a vendor id\n"); RestUtils::sendResponse(409, "{$key['ItemNumber']} is missing a vendor id"); return false; } //08.21.2015 rch - if we enter here,the partnumber does not exist on the po if ($db->sql_numrows($result) == 0) { //08.21.2015 ghh - make sure the non required fields have a value if ($key['FillStatus'] == '') { $key['FillStatus'] = 0; } if ($key['OrderType'] == '') { $key['OrderType'] = 2; } $query = "insert into PurchaseOrderItems (POItemID,POID,ItemNumber,Quantity,\n\t\t\t\t\t FillStatus,ItemID,VendorID) values ( '','{$poid}','{$key['ItemNumber']}',{$key['Qty']},\n\t\t\t\t\t {$key['FillStatus']},{$itemrow['ItemID']}, {$key['VendorID']})"; } else { //08.21.2015 rch - if we enter here,the item is already in the table and just needs to be //updated $row = $db->sql_fetchrow($result); //08.21.2015 rch - here we are updating the purchase order items table $query = "update PurchaseOrderItems set "; if ($key['Qty'] != '') { $query1 = "Quantity={$key['Qty']}"; } if ($query1 != '') { $query .= "{$query1} where POItemID={$row['POItemID']}"; } else { $query = ''; } } //08.21.2015 rch - now we need to execute the query if ($query != '') { if (!($result = $db->sql_query($query))) { RestLog("Error 16525 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16525 - There was a problem attempting to insert/update the PO"); //Internal Server Error return false; } //08.24.2015 ghh - update the PO with the current time for last modified date $query = "update PurchaseOrders set DateLastModified=now() where POID = {$poid}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16548 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16548 - There was a problem updating the last modified date"); //Internal Server Error return false; } } //08.21.2015 ghh - now we need to figure out what our current inventory is //minus any items already on orders so that we pass back a fairly reasonable //backorder response $query = "select (ifnull(sum(p1.Quantity), 0) - ifnull(sum(p2.QtyShipped),0)) as qty \n\t\t\t\t\tfrom PurchaseOrderItems p1 \n\t\t\t\t\tleft outer join PurchaseOrderShipped p2 on p1.POItemID=p2.POItemID \n\t\t\t\t\twhere ItemID={$itemrow['ItemID']}"; if (!($qtyresult = $db->sql_query($query))) { RestLog("Error 16529 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16529 - There was an error getting total on order"); return false; } $qtyrow = $db->sql_fetchrow($qtyresult); $qtyonorder = $qtyrow['qty']; $query = "select sum( Qty ) as Qty from ItemStock where ItemID={$itemrow['ItemID']}"; if (!($qtyresult = $db->sql_query($query))) { RestLog("Error 16530 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16530 - There was an error getting total stock qty"); return false; } $qtyrow = $db->sql_fetchrow($qtyresult); $qtyinstock = $qtyrow['Qty']; //08.21.2015 ghh - now we have all of our return information and have updated or //inserted into the items list for the purchase order so we only need to build our //response now. $items[$i]['VendorID'] = $key['VendorID']; $items[$i]['ItemNumber'] = $key['ItemNumber']; $items[$i]['Superseded'] = $itemrow['SupersessionID']; $items[$i]['NLA'] = $itemrow['NLA']; $items[$i]['Closeout'] = $itemrow['CloseOut']; $items[$i]['MSRP'] = $itemrow['MSRP']; $items[$i]['Cost'] = $cost; if ($qtyinstock - $qtyonorder < 0) { $items[$i]['BackorderQty'] = abs($qtyinstock - $qtyonorder); } else { $items[$i]['BackorderQty'] = 0; } $i++; } $rst['PONumber'] = $ar['PONumber']; $rst['InternalID'] = $poid; $rst['DealerKey'] = $vars['DealerKey']; $rst['Items'] = $items; ########################################UNITS################################### //08.25.2015 ghh - this section deals with unit purchase orders $i = 0; foreach ($ar['Units'] as $value => $key) { $key['ModelNumberNoFormat'] = preg_replace('/[^a-zA-Z0-9]/', '', $key['ModelNumber']); //strip formatting. //08.21.2015 rch - first we need to see if the item is already on the order $query = "select POUnitID\n\t\t\t\t\tfrom PurchaseOrderUnits\n\t\t\t\t\twhere POID='{$poid}' and ModelNumber = '{$key['ModelNumber']}'\n\t\t\t\t\tand VendorID = '{$key['VendorID']}'"; if (!($result = $db->sql_query($query))) { RestLog("Error 16549 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16549 - There was an error locating purchase order unit"); return false; } //08.21.2015 rch - we want to make sure that we have a partnumber and vendorid //before attempting to insert. if ($key['ModelNumberNoFormat'] != '' && $key['VendorID'] != '') { if (isset($key['Year'])) { $year = $key['Year']; } else { $year = 0; } //08.21.2015 ghh - before we bother inserting the item we're going to first grab some //details from items so we can build up our response. $query = "select ModelID, NLA, CloseOut, Cost, OrderCode \n\t\t\t\t\tMSRP from UnitModel \n\t\t\t\t\twhere ModelNumberNoFormat='{$key['ModelNumberNoFormat']}' and VendorID={$key['VendorID']}\n\t\t\t\t\tand Year={$year}"; if (!($unitresult = $db->sql_query($query))) { RestLog("Error 16560 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16560 - There was an error locating the order model"); return false; } $unitrow = $db->sql_fetchrow($unitresult); if ($db->sql_numrows($unitresult) == 0) { RestLog("Error 16561 The Unit Model you sent is not valid"); RestUtils::sendResponse(500, "16561 - The Model Number or VendorID passed are invalid"); return false; } //now lets see if we can calculate the cost for the current dealer $cost = getUnitCost($unitrow['ModelID'], $vars['DealerID'], $unitrow['Cost']); } else { RestLog("Error 16563 {$row['PONumber']} is missing a vendor id\n"); RestUtils::sendResponse(409, "Error 16563 {$key['ModelNumber']} is missing a vendor id"); return false; } //08.25.2015 ghh - if we have less line items on the PO than the qty we need then //we're going to insert a few more rows until they match. if ($db->sql_numrows($result) < $key['Qty']) { for ($i = 0; $i < $key['Qty'] - $db->sql_numrows($result); $i++) { $query = "insert into PurchaseOrderUnits (POID,ModelNumber,\n\t\t\t\t\t ModelID,OrderCode,Year, Colors, VendorID, Cost) values \n\t\t\t\t\t ( '{$poid}','{$key['ModelNumber']}',{$unitrow['ModelID']},'{$unitrow['OrderCode']}',\n\t\t\t\t\t {$year},'{$key['Colors']}', {$key['VendorID']}, '{$cost}')"; if (!($tmpresult = $db->sql_query($query))) { RestLog("Error 16564 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16564 - There was an error trying to add the unit to the order"); return false; } } //08.25.2015 ghh - update the PO with the current time for last modified date $query = "update PurchaseOrders set DateLastModified=now() where POID = {$poid}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16565 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16565 - There was a problem updating the last modified date"); //Internal Server Error return false; } } else { if ($db->sql_numrows($result) > $key['Qty']) { $qtytoremove = $db->sql_numrows($result) - $key['Qty']; $query = "select POUnitID from PurchaseOrderUnits where POID={$poid}\n\t\t\t\t\t\tand ModelID={$unitrow['ModelID']} limit {$qtytoremove}"; if (!($tmpresult = $db->sql_query($query))) { RestLog("Error 16566 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16566 - There was a problem deleting changed models"); //Internal Server Error return false; } while ($tmprow = $db->sql_fetchrow($tmpresult)) { $query = "delete from PurchaseOrderUnits where POUnitID={$tmprow['POUnitID']}"; if (!($tmp2result = $db->sql_query($query))) { RestLog("Error 16567 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16567 - There was a problem deleting changed models"); //Internal Server Error return false; } } //08.25.2015 ghh - update the PO with the current time for last modified date $query = "update PurchaseOrders set DateLastModified=now() where POID = {$poid}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16568 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16568 - There was a problem updating the last modified date"); //Internal Server Error return false; } } } //08.25.2015 ghh - first lets grab total qty for the current model $query = "select sum(Qty) as Qty from UnitModelStock where ModelID={$unitrow['ModelID']}"; if (!($qtyresult = $db->sql_query($query))) { RestLog("Error 16570 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16570 - There was an error getting total instock"); return false; } $tmprow = $db->sql_fetchrow($qtyresult); $stockqty = $tmprow['Qty']; $query = "select count(POUnitID) as Qty from PurchaseOrderUnits \n\t\t\t\twhere ModelID={$unitrow['ModelID']} and SerialVin is null"; if (!($qtyresult = $db->sql_query($query))) { RestLog("Error 16571 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16571 - There was an error getting total instock"); return false; } $tmprow = $db->sql_fetchrow($qtyresult); $orderqty = $tmprow['Qty']; //08.21.2015 ghh - now we have all of our return information and have updated or //inserted into the items list for the purchase order so we only need to build our //response now. $units[$i]['VendorID'] = $key['VendorID']; $units[$i]['ModelNumber'] = $key['ModelNumber']; $units[$i]['NLA'] = $unitrow['NLA']; $units[$i]['Closeout'] = $unitrow['CloseOut']; $units[$i]['MSRP'] = $unitrow['MSRP']; $units[$i]['Cost'] = $cost; if ($stockqty - $onorderqty < 0) { $units[$i]['BackorderQty'] = abs($stockqty - $onorderqty); } else { $units[$i]['BackorderQty'] = 0; } $i++; } $rst['Units'] = $units; RestLog("Successful Request\n"); //08.10.2012 naj - return code 200 OK. RestUtils::sendResponse(200, json_encode(stripHTML($rst))); return true; }
function FM_default_summary($blogid, $id, $content, $keywords = array(), $useAbsolutePath = false) { if (!$blog['publishWholeOnRSS']) { $content = Utils_Unicode::lessen(removeAllTags(stripHTML($content)), 255); } return $content; }
function getInventory($vars, $responsetype) { global $db; $ar = $vars; if (empty($ar) || !isset($ar['VendorID']) || !isset($ar['ItemNumber'])) { RestLog("16575 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n"); RestUtils::sendResponse(400, "16575 - Insufficient data provided"); //Internal Server Error return false; } //now we grab inventory records for the requested item and build up our package to return //to the dealer //08.26.2015 rch - Moving ItemStock,Warehouses,DaysToFullfill to left outer joins //to account for not stocking an item or not putting in warehouse //08.28.2015 ghh - added Weight $query = "select Items.ItemID, Items.MSRP, NLA, CloseOut,\n\t\t\t\tPriceCode, Cost, MAP, Category, WarehouseName, \n\t\t\t\tWarehouseState, Qty, DaysToArrive, Weight\n\t\t\t\tManufItemNumber, ManufName, SupersessionID\n\t\t\t\tfrom Items\n\t\t\t\tleft outer join ItemStock on ItemStock.ItemID = Items.ItemID \n\t\t\t\tleft outer join Warehouses on Warehouses.WarehouseID = ItemStock.WarehouseID\n\t\t\t\tleft outer join DaysToFullfill on DaysToFullfill.WarehouseID = ItemStock.WarehouseID\n\t\t\t\twhere Items.ItemNumber='{$ar['ItemNumber']}' and\n\t\t\t\tItems.VendorID={$ar['VendorID']} and\n\t\t\t\tDaysToFullfill.DealerID={$ar['DealerID']} order by DaysToArrive"; if (!($result = $db->sql_query($query))) { RestLog("Error 16576 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16576 - There was a problem getting inventory information."); //Internal Server Error return false; } $i = 0; $itemid = 0; while ($row = $db->sql_fetchrow($result)) { //grabbing our details on first run through as no sense in grabbing //more than once. if ($itemid == 0) { $itemid = $row['ItemID']; $OrigManufName = $row['ManufName']; $OrigManufNumber = $row['ManufItemNumber']; $NLA = $row['NLA']; $CloseOut = $row['CloseOut']; $MSRP = $row['MSRP']; $Category = $row['Category']; $MAP = $row['MAP']; $Weight = $row['Weight']; //08.28.2015 ghh - } $rst[$i]['WarehouseName'] = $row['WarehouseName']; $rst[$i]['WarehouseState'] = $row['WarehouseState']; $rst[$i]['Qty'] = $row['Qty']; $rst[$i]['DaysToArrive'] = $row['DaysToArrive']; $i++; } if ($itemid > 0) { $item['Warehouses'] = $rst; $item['MSRP'] = $MSRP; if ($itemid > 0) { $item['Cost'] = getItemCost($itemid, $ar['DealerID'], $row['PriceCode'], $row['Cost'], $row['MSRP']); } //08.25.2015 ghh - if BSV asked for full detail then we're also going to send back //images data and other items of interest if ($row['SupersessionID'] > 0) { $query = "select ItemNumber from Items where ItemID={$row['SupersessionID']}"; if (!($tmpresult = $db->sql_query($query))) { RestLog("Error 16578 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16578 - There was a problem retrieving the supersession number"); //Internal Server Error return false; } $tmprow = $db->sql_fetchrow($tmpresult); $item['SupersessionNumber'] = $tmprow['ItemNumber']; } $item['OrigManufName'] = $ManufName; $item['OrigManufNumber'] = $ManufItemNumber; $item['NLA'] = $NLA; $item['Category'] = $Category; $item['MAP'] = $MAP; //08.25.2015 ghh - now we're getting a list of images that may exist for this //item $query = "select * from ItemImages where ItemID={$itemid}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16577 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16577 - There was a problem retrieving a list of images"); //Internal Server Error return false; } $i = 0; while ($row = $db->sql_fetchrow($result)) { $img[$i]['ImageURL'] = $row['ImageURL']; $img[$i]['ImageSize'] = $row['ImageSize']; $i++; } $item['Images'] = $img; } else { RestLog("Error 16635 The item number being requested doesn't exist\n"); RestUtils::sendResponse(500, "16635 - The Item you requested was not found."); //Internal Server Error return false; } RestLog("Successful Request\n"); //08.10.2012 naj - return code 200 OK. RestUtils::sendResponse(200, json_encode(stripHTML($item))); return true; }
function stripHTML($data) { $find = array("<br>", " "); $replace = array("\n", " "); if (is_array($data)) { foreach ($data as $key => $value) { if (is_array($value)) { $data[$key] = stripHTML($value); } else { $data[$key] = str_replace($find, $replace, $value); } } return $data; } else { return str_replace($find, $replace, $data); } }
function getModel($vars, $responsetype) { global $db; $ar = $vars; if (empty($ar) || !isset($ar['VendorID']) || !isset($ar['ModelNumber']) || !isset($ar['Year'])) { RestLog("16579 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n"); RestUtils::sendResponse(400, "16579 - Insufficient data provided"); //Internal Server Error return false; } $ar['ModelNumberNoFormat'] = preg_replace('/[^a-zA-Z0-9]/', '', $ar['ModelNumber']); //strip formatting. //now we grab inventory records for the requested item and build up our package to return //to the dealer $query = "select ModelID, OrderCode, Colors, ModelName, VehicleTypeID, NLA, CloseOut,\n\t\t\t\t\tCost, MSRP, MAP, Description from UnitModel where VendorID=\n\t\t\t\t\t{$ar['VendorID']} and ModelNumberNoFormat='{$ar['ModelNumberNoFormat']}' and\n\t\t\t\t\tYear={$ar['Year']}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16581 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16581 - There was a problem getting model information."); //Internal Server Error return false; } $row = $db->sql_fetchrow($result); $unit['OrderCode'] = $row['OrderCode']; $unit['Colors'] = $row['Colors']; $unit['ModelName'] = $row['ModelName']; $unit['NLA'] = $row['NLA']; $unit['CloseOut'] = $row['CloseOut']; $unit['Cost'] = getUnitCost($row['ModelID'], $ar['DealerID'], $row['Cost']); $unit['MSRP'] = $row['MSRP']; $unit['MAP'] = $row['MAP']; $unit['Description'] = $row['Description']; $modelid = $row['ModelID']; if ($modelid > 0) { //08.25.2015 ghh - now we grab unit inventory information $query = "select Warehouses.WarehouseName, Warehouses.WarehouseState,\n\t\t\t\t\tQty, DaysToArrive \n\t\t\t\t\tfrom Warehouses, UnitModelStock, DaysToFullfill\n\t\t\t\t\twhere Warehouses.WarehouseID=UnitModelStock.WarehouseID and\n\t\t\t\t\tUnitModelStock.ModelID={$row['ModelID']} and\n\t\t\t\t\tUnitModelStock.WarehouseID=DaysToFullfill.WarehouseID and\n\t\t\t\t\tDaysToFullfill.DealerID={$ar['DealerID']} order by DaysToArrive"; if (!($result = $db->sql_query($query))) { RestLog("Error 16582 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16582 - There was a problem getting model warehouse information."); //Internal Server Error return false; } $i = 0; while ($row = $db->sql_fetchrow($result)) { $rst[$i]['WarehouseName'] = $row['WarehouseName']; $rst[$i]['WarehouseState'] = $row['WarehouseState']; $rst[$i]['Qty'] = $row['Qty']; $rst[$i]['DaysToArrive'] = $row['DaysToArrive']; $i++; } $unit['Warehouses'] = $rst; //08.25.2015 ghh - now we're getting a list of images that may exist for this //item $query = "select * from UnitModelImages where ModelID={$modelid}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16583 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16583 - There was a problem retrieving a list of images"); //Internal Server Error return false; } $i = 0; while ($row = $db->sql_fetchrow($result)) { $img[$i]['ImageURL'] = $row['ImageURL']; $img[$i]['ImageSize'] = $row['ImageSize']; $i++; } $unit['Images'] = $img; } RestLog("Successful Request\n"); RestUtils::sendResponse(200, json_encode(stripHTML($unit))); return true; }
function createGroup($name, $userIDs, $ownerID, $classID) { $name = stripHTML(mysql_real_escape_string($name)); $query = "INSERT INTO groups VALUES (NULL, '{$name}', {$classID})"; // print "query1: $query<br />"; mysql_query("LOCK TABLES groups WRITE"); $result = mysql_query($query, $this->link); if (!$result) { die('Invalid query (createGroup): ' . mysql_error()); } // get 'id' of newly created group $groupID = mysql_insert_id(); mysql_query("UNLOCK TABLES"); $groupOwners = $this->getClassInstructorsAndTAs($groupID); // get TAs associated with section group belongs to // print_r($groupOwners); foreach ($groupOwners as $owner) { $query = "INSERT INTO groupOwners VALUES ({$groupID}, {$owner})"; $result = mysql_query($query, $this->link); //print "query2: $query<br />"; if (!$result) { die('Invalid query (createGroup): ' . mysql_error()); } } if (!is_null($userIDs)) { foreach ($userIDs as $userID) { $query = "INSERT INTO groupMembers VALUES ({$groupID}, {$userID})"; $result = mysql_query($query, $this->link); //print "query3: $query<br />"; if (!$result) { die('Invalid query (createUserGroup): ' . mysql_error()); } } } return $groupID; }
function updateComment($blogid, $comment, $password) { global $database, $user; $openid = Acl::getIdentity('openid'); if (!doesHaveOwnership()) { // if filtered, only block and not send to trash if (!Filter::isAllowed($comment['homepage'])) { if (Filter::isFiltered('ip', $comment['ip'])) { return 'blocked'; } if (Filter::isFiltered('name', $comment['name'])) { return 'blocked'; } if (Filter::isFiltered('url', $comment['homepage'])) { return 'blocked'; } if (Filter::isFiltered('content', $comment['comment'])) { return 'blocked'; } if (!fireEvent('ModifyingComment', true, $comment)) { return 'blocked'; } } } $comment['homepage'] = stripHTML($comment['homepage']); $comment['name'] = UTF8::lessenAsEncoding($comment['name'], 80); $comment['homepage'] = UTF8::lessenAsEncoding($comment['homepage'], 80); $comment['comment'] = UTF8::lessenAsEncoding($comment['comment'], 65535); $setPassword = ''; if ($user !== null) { $comment['replier'] = getUserId(); $name = POD::escapeString($user['name']); $setPassword = '******'\','; $homepage = POD::escapeString($user['homepage']); if (empty($homepage) && $openid) { $homepage = POD::escapeString($openid); } } else { $name = POD::escapeString($comment['name']); if ($comment['password'] !== true) { $setPassword = '******'' . (empty($comment['password']) ? '' : md5($comment['password'])) . '\', '; } $homepage = POD::escapeString($comment['homepage']); } $comment0 = POD::escapeString($comment['comment']); $guestcomment = false; if (POD::queryExistence("SELECT *\n\t\tFROM {$database['prefix']}Comments\n\t\tWHERE blogid = {$blogid}\n\t\t\tAND id = {$comment['id']}\n\t\t\tAND replier IS NULL")) { $guestcomment = true; } $wherePassword = ''; if (!doesHaveOwnership()) { if ($guestcomment == false) { if (!doesHaveMembership()) { return false; } $wherePassword = '******' . getUserId(); } else { if (empty($password) && $openid) { $wherePassword = '******'' . $openid . '\''; } else { $wherePassword = '******'' . md5($password) . '\''; } } } $replier = is_null($comment['replier']) ? 'NULL' : "'{$comment['replier']}'"; $result = POD::query("UPDATE {$database['prefix']}Comments\n\t\t\t\tSET\n\t\t\t\t\tname = '{$name}',\n\t\t\t\t\t{$setPassword}\n\t\t\t\t\thomepage = '{$homepage}',\n\t\t\t\t\tsecret = {$comment['secret']},\n\t\t\t\t\tcomment = '{$comment0}',\n\t\t\t\t\tip = '{$comment['ip']}',\n\t\t\t\t\twritten = UNIX_TIMESTAMP(),\n\t\t\t\t\tisfiltered = {$comment['isfiltered']},\n\t\t\t\t\treplier = {$replier}\n\t\t\t\tWHERE blogid = {$blogid}\n\t\t\t\t\tAND id = {$comment['id']} {$wherePassword}"); if ($result) { CacheControl::flushCommentRSS($comment['entry']); // Assume blogid = current blogid. CacheControl::flushDBCache('comment'); return true; } else { return false; } }
function MT_Cover_getRecentEntries($parameters) { global $database, $blog, $service, $serviceURL, $suri, $configVal, $defaultURL, $skin; requireModel("blog.entry"); requireModel("blog.tag"); $data = Setting::fetchConfigVal($configVal); $data['coverMode'] = !isset($data['coverMode']) ? 1 : $data['coverMode']; if (Misc::isMetaBlog() != true) { $data['coverMode'] = 1; } $data['screenshot'] = !isset($data['screenshot']) ? 1 : $data['screenshot']; $data['screenshotSize'] = !isset($data['screenshotSize']) ? 90 : $data['screenshotSize']; $data['paging'] = !isset($data['paging']) ? '2' : $data['paging']; $data['contentLength'] = !isset($data['contentLength']) ? 250 : $data['contentLength']; if (isset($parameters['preview'])) { // preview mode $retval = '표지에 최신 글 목록을 추가합니다.'; return htmlspecialchars($retval); } $entryLength = isset($parameters['entryLength']) ? $parameters['entryLength'] : 10; if (!is_dir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail")) { @mkdir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail"); @chmod(__TEXTCUBE_CACHE_DIR__ . "/thumbnail", 0777); } if (!is_dir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . getBlogId())) { @mkdir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . getBlogId()); @chmod(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . getBlogId(), 0777); } if (!is_dir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . getBlogId() . "/coverPostThumbnail/")) { @mkdir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . getBlogId() . "/coverPostThumbnail/"); @chmod(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . getBlogId() . "/coverPostThumbnail/", 0777); } $page = $data['paging'] == '1' && !empty($_GET['page']) ? intval($_GET['page']) : 1; $cache = new PageCache(); $cache->name = 'MT_Cover_RecentPS'; if ($cache->load()) { //If successful loads $cache->contents = unserialize($cache->contents); // If coverpage is single mode OR coverpage is coverblog and cache is not expired, return cache contents. if (($data['coverMode'] == 1 || $data['coverMode'] == 2) && array_key_exists($page, $cache->contents) && Timestamp::getUNIXtime() - $cache->dbContents < 300) { return $cache->contents[$page]; } } if (Misc::isMetaBlog() == true && doesHaveOwnership() && $service['type'] != 'single') { $visibility = 'AND e.visibility > 1 AND (c.visibility > 1 OR e.category = 0)'; } else { $visibility = doesHaveOwnership() ? '' : 'AND e.visibility > 1 AND (c.visibility > 1 OR e.category = 0)'; } $multiple = $data['coverMode'] == 2 ? '' : 'e.blogid = ' . getBlogId() . ' AND'; $privateBlogId = POD::queryColumn("SELECT blogid \n\t\tFROM {$database['prefix']}BlogSettings\n\t\tWHERE name = 'visibility'\n\t\tAND value < 2"); if (!empty($privateBlogId)) { $privateBlogs = ' AND e.blogid NOT IN (' . implode(',', $privateBlogId) . ')'; } else { $privateBlogs = ''; } list($entries, $paging) = Paging::fetch("SELECT e.blogid, e.id, e.userid, e.title, e.content, e.slogan, e.category, e.published, e.contentformatter, c.label\n\t\tFROM {$database['prefix']}Entries e\n\t\tLEFT JOIN {$database['prefix']}Categories c ON e.blogid = c.blogid AND e.category = c.id\n\t\tWHERE {$multiple} e.draft = 0 {$visibility} AND e.category >= 0 {$privateBlogs}\n\t\tORDER BY published DESC", $page, $entryLength); $html = ''; foreach ((array) $entries as $entry) { $tagLabelView = ""; $blogid = $data['coverMode'] == 2 ? $entry['blogid'] : getBlogId(); $entryTags = getTags($blogid, $entry['id']); $defaultURL = getDefaultURL($blogid); if (sizeof($entryTags) > 0) { $tags = array(); foreach ($entryTags as $entryTag) { $tags[$entryTag['name']] = "<a href=\"{$defaultURL}/tag/" . (Setting::getBlogSettingGlobal('useSloganOnTag', true) ? URL::encode($entryTag['name'], $service['useEncodedURL']) : $entryTag['id']) . '">' . htmlspecialchars($entryTag['name']) . '</a>'; } $tagLabelView = "<div class=\"post_tags\"><span>TAG : </span>" . implode(",\r\n", array_values($tags)) . "</div>"; } if (empty($entry['category'])) { $entry['label'] = _text('분류없음'); $entry['link'] = "{$defaultURL}/category"; } else { $entry['link'] = "{$defaultURL}/category/" . (Setting::getBlogSettingGlobal('useSloganOnCategory', true) ? URL::encode($entry['label'], $service['useEncodedURL']) : $entry['category']); } $permalink = "{$defaultURL}/" . (Setting::getBlogSettingGlobal('useSloganOnPost', true) ? "entry/" . URL::encode($entry['slogan'], $service['useEncodedURL']) : $entry['id']); $html .= '<div class="coverpost">' . CRLF; if ($imageName = MT_Cover_getAttachmentExtract($entry['content'])) { if (($tempImageSrc = MT_Cover_getImageResizer($blogid, $imageName, $data['screenshotSize'])) && $data['screenshot'] == 1) { $html .= '<div class="img_preview"><a href="' . $permalink . '"><img src="' . $tempImageSrc . '" alt="" /></a></div>' . CRLF; } } $html .= ' <div class="content_box">'; $html .= ' <h2><a href="' . $permalink . '">' . htmlspecialchars($entry['title']) . '</a></h2>' . CRLF; $html .= ' <div class="post_info">' . CRLF; $html .= ' <span class="category"><a href="' . htmlspecialchars($entry['link']) . '">' . htmlspecialchars($entry['label']) . '</a></span>' . CRLF; $html .= ' <span class="date">' . Timestamp::format5($entry['published']) . '</span>' . CRLF; $html .= ' <span class="author"><span class="preposition">by </span>' . User::getName($entry['userid']) . '</span>' . CRLF; $html .= ' </div>' . CRLF; $html .= ' <div class="post_content">' . htmlspecialchars(Utils_Unicode::lessenAsEm(removeAllTags(stripHTML($entry['content'])), $data['contentLength'])) . '</div>' . CRLF; $html .= $tagLabelView; $html .= ' <div class="clear"></div>' . CRLF; $html .= ' </div>'; $html .= '</div>' . CRLF; } if ($data['paging'] == '1') { $paging['page'] = $page; $paging['total'] = POD::queryCell("SELECT COUNT(*) FROM {$database['prefix']}Entries e WHERE {$multiple} e.draft = 0 {$visibility} AND e.category >= 0"); $html .= getPagingView($paging, $skin->paging, $skin->pagingItem) . CRLF; $html .= '<script type="text/javascript">' . CRLF; $html .= '//<![CDATA[' . CRLF; if ($paging['page'] > 1) { $html .= 'var prevURL = "' . $paging['url'] . '?page=' . ($paging['page'] - 1) . '"' . CRLF; } if ($paging['page'] < $paging['total']) { $html .= 'var nextURL = "' . $paging['url'] . '?page=' . ($paging['page'] + 1) . '"' . CRLF; } $html .= '//]]>' . CRLF; $html .= '</script>'; } $target = $html; $cache->contents[$page] = $target; $cache->contents = serialize($cache->contents); $cache->dbContents = Timestamp::getUNIXtime(); $cache->update(); unset($cache); return $target; }
function sendEmail($messageid, $email, $hash, $htmlpref = 0, $rssitems = array(), $forwardedby = array()) { global $strThisLink, $PoweredByImage, $PoweredByText, $cached, $website; if ($email == "") { return 0; } #0013076: different content when forwarding 'to a friend' if (FORWARD_ALTERNATIVE_CONTENT) { $forwardContent = sizeof($forwardedby) > 0; $messagedata = loadMessageData($messageid); } else { $forwardContent = 0; } if (empty($cached[$messageid])) { $domain = getConfig("domain"); $message = Sql_query("select * from {$GLOBALS["tables"]["message"]} where id = {$messageid}"); $cached[$messageid] = array(); $message = Sql_fetch_array($message); if (ereg("([^ ]+@[^ ]+)", $message["fromfield"], $regs)) { # if there is an email in the from, rewrite it as "name <email>" $message["fromfield"] = ereg_replace($regs[0], "", $message["fromfield"]); $cached[$messageid]["fromemail"] = $regs[0]; # if the email has < and > take them out here $cached[$messageid]["fromemail"] = ereg_replace("<", "", $cached[$messageid]["fromemail"]); $cached[$messageid]["fromemail"] = ereg_replace(">", "", $cached[$messageid]["fromemail"]); # make sure there are no quotes around the name $cached[$messageid]["fromname"] = ereg_replace('"', "", ltrim(rtrim($message["fromfield"]))); } elseif (ereg(" ", $message["fromfield"], $regs)) { # if there is a space, we need to add the email $cached[$messageid]["fromname"] = $message["fromfield"]; $cached[$messageid]["fromemail"] = "listmaster@{$domain}"; } else { $cached[$messageid]["fromemail"] = $message["fromfield"] . "@{$domain}"; ## makes more sense not to add the domain to the word, but the help says it does ## so let's keep it for now $cached[$messageid]["fromname"] = $message["fromfield"] . "@{$domain}"; } # erase double spacing while (ereg(" ", $cached[$messageid]["fromname"])) { $cached[$messageid]["fromname"] = eregi_replace(" ", " ", $cached[$messageid]["fromname"]); } ## this has weird effects when used with only one word, so take it out for now # $cached[$messageid]["fromname"] = eregi_replace("@","",$cached[$messageid]["fromname"]); $cached[$messageid]["fromname"] = trim($cached[$messageid]["fromname"]); $cached[$messageid]["to"] = $message["tofield"]; #0013076: different content when forwarding 'to a friend' $cached[$messageid]["subject"] = $forwardContent ? stripslashes($messagedata["forwardsubject"]) : $message["subject"]; $cached[$messageid]["replyto"] = $message["replyto"]; #0013076: different content when forwarding 'to a friend' $cached[$messageid]["content"] = $forwardContent ? stripslashes($messagedata["forwardmessage"]) : $message["message"]; if (USE_MANUAL_TEXT_PART && !$forwardContent) { $cached[$messageid]["textcontent"] = $message["textmessage"]; } else { $cached[$messageid]["textcontent"] = ''; } #0013076: different content when forwarding 'to a friend' $cached[$messageid]["footer"] = $forwardContent ? stripslashes($messagedata["forwardfooter"]) : $message["footer"]; $cached[$messageid]["htmlformatted"] = $message["htmlformatted"]; $cached[$messageid]["sendformat"] = $message["sendformat"]; if ($message["template"]) { $req = Sql_Fetch_Row_Query("select template from {$GLOBALS["tables"]["template"]} where id = {$message["template"]}"); $cached[$messageid]["template"] = stripslashes($req[0]); $cached[$messageid]["templateid"] = $message["template"]; # dbg("TEMPLATE: ".$req[0]); } else { $cached[$messageid]["template"] = ''; $cached[$messageid]["templateid"] = 0; } ## @@ put this here, so it can become editable per email sent out at a later stage $cached[$messageid]["html_charset"] = getConfig("html_charset"); ## @@ need to check on validity of charset if (!$cached[$messageid]["html_charset"]) { $cached[$messageid]["html_charset"] = 'iso-8859-1'; } $cached[$messageid]["text_charset"] = getConfig("text_charset"); if (!$cached[$messageid]["text_charset"]) { $cached[$messageid]["text_charset"] = 'iso-8859-1'; } } # else # dbg("Using cached {$cached[$messageid]["fromemail"]}"); if (VERBOSE) { output($GLOBALS['I18N']->get('sendingmessage') . ' ' . $messageid . ' ' . $GLOBALS['I18N']->get('withsubject') . ' ' . $cached[$messageid]["subject"] . ' ' . $GLOBALS['I18N']->get('to') . ' ' . $email); } # erase any placeholders that were not found # $msg = ereg_replace("\[[A-Z ]+\]","",$msg); #0011857: forward to friend, retain attributes if ($hash == 'forwarded' && defined('KEEPFORWARDERATTRIBUTES') && KEEPFORWARDERATTRIBUTES) { $user_att_values = getUserAttributeValues($forwardedby['email']); } else { $user_att_values = getUserAttributeValues($email); } $userdata = Sql_Fetch_Assoc_Query(sprintf('select * from %s where email = "%s"', $GLOBALS["tables"]["user"], $email)); $url = getConfig("unsubscribeurl"); $sep = ereg('\\?', $url) ? '&' : '?'; $html["unsubscribe"] = sprintf('<a href="%s%suid=%s">%s</a>', $url, $sep, $hash, $strThisLink); $text["unsubscribe"] = sprintf('%s%suid=%s', $url, $sep, $hash); $html["unsubscribeurl"] = sprintf('%s%suid=%s', $url, $sep, $hash); $text["unsubscribeurl"] = sprintf('%s%suid=%s', $url, $sep, $hash); #0013076: Blacklisting posibility for unknown users $url = getConfig("blacklisturl"); $sep = ereg('\\?', $url) ? '&' : '?'; $html["blacklist"] = sprintf('<a href="%s%semail=%s">%s</a>', $url, $sep, $email, $strThisLink); $text["blacklist"] = sprintf('%s%semail=%s', $url, $sep, $email); $html["blacklisturl"] = sprintf('%s%semail=%s', $url, $sep, $email); $text["blacklisturl"] = sprintf('%s%semail=%s', $url, $sep, $email); #0013076: Problem found during testing: mesage part must be parsed correctly as well. if ($forwardContent) { $html["unsubscribe"] = $html["blacklist"]; $text["unsubscribe"] = $text["blacklist"]; } $url = getConfig("subscribeurl"); $sep = ereg('\\?', $url) ? '&' : '?'; $html["subscribe"] = sprintf('<a href="%s">%s</a>', $url, $strThisLink); $text["subscribe"] = sprintf('%s', $url); $html["subscribeurl"] = sprintf('%s', $url); $text["subscribeurl"] = sprintf('%s', $url); #?mid=1&id=1&uid=a9f35f130593a3d6b89cfe5cfb32a0d8&p=forward&email=michiel%40tincan.co.uk& $url = getConfig("forwardurl"); $sep = ereg('\\?', $url) ? '&' : '?'; $html["forward"] = sprintf('<a href="%s%suid=%s&mid=%d">%s</a>', $url, $sep, $hash, $messageid, $strThisLink); $text["forward"] = sprintf('%s%suid=%s&mid=%d', $url, $sep, $hash, $messageid); $html["forwardurl"] = sprintf('%s%suid=%s&mid=%d', $url, $sep, $hash, $messageid); $text["forwardurl"] = $text["forward"]; $url = getConfig("forwardurl"); # make sure there are no newlines, otherwise they get turned into <br/>s $html["forwardform"] = sprintf('<form method="get" action="%s" name="forwardform" class="forwardform"><input type=hidden name="uid" value="%s" /><input type=hidden name="mid" value="%d" /><input type=hidden name="p" value="forward" /><input type=text name="email" value="" class="forwardinput" /><input name="Send" type="submit" value="%s" class="forwardsubmit"/></form>', $url, $hash, $messageid, $GLOBALS['strForward']); $text["signature"] = "\n\n--\nPowered by PHPlist, www.phplist.com --\n\n"; $url = getConfig("preferencesurl"); $sep = ereg('\\?', $url) ? '&' : '?'; $html["preferences"] = sprintf('<a href="%s%suid=%s">%s</a>', $url, $sep, $hash, $strThisLink); $text["preferences"] = sprintf('%s%suid=%s', $url, $sep, $hash); $html["preferencesurl"] = sprintf('%s%suid=%s', $url, $sep, $hash); $text["preferencesurl"] = sprintf('%s%suid=%s', $url, $sep, $hash); /* We request you retain the signature below in your emails including the links. This not only gives respect to the large amount of time given freely by the developers but also helps build interest, traffic and use of PHPlist, which is beneficial to it's future development. You can configure how the credits are added to your pages and emails in your config file. Michiel Dethmers, Tincan Ltd 2003, 2004, 2005, 2006 */ if (!EMAILTEXTCREDITS) { $html["signature"] = $PoweredByImage; #'<div align="center" id="signature"><a href="http://www.phplist.com"><img src="powerphplist.png" width=88 height=31 title="Powered by PHPlist" alt="Powered by PHPlist" border="0"></a></div>'; # oops, accidentally became spyware, never intended that, so take it out again :-) $html["signature"] = preg_replace('/src=".*power-phplist.png"/', 'src="powerphplist.png"', $html["signature"]); } else { $html["signature"] = $PoweredByText; } $content = $cached[$messageid]["content"]; if (preg_match("/##LISTOWNER=(.*)/", $content, $regs)) { $listowner = $regs[1]; $content = ereg_replace($regs[0], "", $content); } else { $listowner = 0; } ## Fetch external content if ($GLOBALS["has_pear_http_request"] && preg_match("/\\[URL:([^\\s]+)\\]/i", $content, $regs)) { while (isset($regs[1]) && strlen($regs[1])) { $url = $regs[1]; if (!preg_match('/^http/i', $url)) { $url = 'http://' . $url; } $remote_content = fetchUrl($url, $userdata); if ($remote_content) { $content = eregi_replace(preg_quote($regs[0]), $remote_content, $content); $cached[$messageid]["htmlformatted"] = strip_tags($content) != $content; } else { logEvent("Error fetching URL: {$regs['1']} to send to {$email}"); return 0; } preg_match("/\\[URL:([^\\s]+)\\]/i", $content, $regs); } } #~Bas 0008857 // @@ Switched off for now, needs rigid testing, or config setting // $content = mailto2href($content); // $content = encodeLinks($content); ## Fill text and html versions depending on given versions. if ($cached[$messageid]["htmlformatted"]) { if (!$cached[$messageid]["textcontent"]) { $textcontent = stripHTML($content); } else { $textcontent = $cached[$messageid]["textcontent"]; } $htmlcontent = $content; } else { # $textcontent = $content; if (!$cached[$messageid]["textcontent"]) { $textcontent = $content; } else { $textcontent = $cached[$messageid]["textcontent"]; } $htmlcontent = parseText($content); } $defaultstyle = getConfig("html_email_style"); $adddefaultstyle = 0; if ($cached[$messageid]["template"]) { # template used $htmlmessage = eregi_replace("\\[CONTENT\\]", $htmlcontent, $cached[$messageid]["template"]); } else { # no template used $htmlmessage = $htmlcontent; $adddefaultstyle = 1; } $textmessage = $textcontent; ## Parse placeholders #0013076: Blacklisting posibility for unknown users foreach (array("forwardform", "subscribe", "preferences", "unsubscribe", "signature", 'blacklist') as $item) { if (eregi('\\[' . $item . '\\]', $htmlmessage, $regs)) { $htmlmessage = eregi_replace('\\[' . $item . '\\]', $html[$item], $htmlmessage); // unset($html[$item]); //ASK: Why was this done? It breaks placeholders in the footer } if (eregi('\\[' . $item . '\\]', $textmessage, $regs)) { $textmessage = eregi_replace('\\[' . $item . '\\]', $text[$item], $textmessage); // unset($text[$item]); } } #0013076: Blacklisting posibility for unknown users foreach (array("forward", "forwardurl", "subscribeurl", "preferencesurl", "unsubscribeurl", 'blacklisturl') as $item) { if (eregi('\\[' . $item . '\\]', $htmlmessage, $regs)) { $htmlmessage = eregi_replace('\\[' . $item . '\\]', $html[$item], $htmlmessage); } if (eregi('\\[' . $item . '\\]', $textmessage, $regs)) { $textmessage = eregi_replace('\\[' . $item . '\\]', $text[$item], $textmessage); } } if ($hash != 'forwarded') { $text['footer'] = $cached[$messageid]["footer"]; $html['footer'] = $cached[$messageid]["footer"]; } else { #0013076: different content when forwarding 'to a friend' if (FORWARD_ALTERNATIVE_CONTENT) { $text['footer'] = stripslashes($messagedata["forwardfooter"]); } else { $text['footer'] = getConfig('forwardfooter'); } $html['footer'] = $text['footer']; } $text["footer"] = eregi_replace("\\[SUBSCRIBE\\]", $text["subscribe"], $text['footer']); $html["footer"] = eregi_replace("\\[SUBSCRIBE\\]", $html["subscribe"], $html['footer']); $text["footer"] = eregi_replace("\\[PREFERENCES\\]", $text["preferences"], $text["footer"]); $html["footer"] = eregi_replace("\\[PREFERENCES\\]", $html["preferences"], $html["footer"]); $text["footer"] = eregi_replace("\\[FORWARD\\]", $text["forward"], $text["footer"]); $html["footer"] = eregi_replace("\\[FORWARD\\]", $html["forward"], $html["footer"]); $html["footer"] = eregi_replace("\\[FORWARDFORM\\]", $html["forwardform"], $html["footer"]); if (sizeof($forwardedby) && isset($forwardedby['email'])) { $htmlmessage = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $htmlmessage); $textmessage = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $textmessage); $html["footer"] = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $html["footer"]); $text["footer"] = eregi_replace("\\[FORWARDEDBY]", $forwardedby["email"], $text["footer"]); $text["footer"] = eregi_replace("\\[BLACKLIST\\]", $text["blacklist"], $text['footer']); $html["footer"] = eregi_replace("\\[BLACKLIST\\]", $html["blacklist"], $html['footer']); $text["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $text["blacklist"], $text['footer']); $html["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $html["blacklist"], $html['footer']); } else { $text["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $text["unsubscribe"], $text['footer']); $html["footer"] = eregi_replace("\\[UNSUBSCRIBE\\]", $html["unsubscribe"], $html['footer']); } $html["footer"] = '<div class="emailfooter">' . nl2br($html["footer"]) . '</div>'; if (eregi("\\[FOOTER\\]", $htmlmessage)) { $htmlmessage = eregi_replace("\\[FOOTER\\]", $html["footer"], $htmlmessage); } elseif ($html["footer"]) { $htmlmessage = addHTMLFooter($htmlmessage, '<br /><br />' . $html["footer"]); } if (eregi("\\[SIGNATURE\\]", $htmlmessage)) { $htmlmessage = eregi_replace("\\[SIGNATURE\\]", $html["signature"], $htmlmessage); } elseif ($html["signature"]) { $htmlmessage .= '<br />' . $html["signature"]; } if (eregi("\\[FOOTER\\]", $textmessage)) { $textmessage = eregi_replace("\\[FOOTER\\]", $text["footer"], $textmessage); } else { $textmessage .= "\n\n" . $text["footer"]; } if (eregi("\\[SIGNATURE\\]", $textmessage)) { $textmessage = eregi_replace("\\[SIGNATURE\\]", $text["signature"], $textmessage); } else { $textmessage .= "\n" . $text["signature"]; } # $req = Sql_Query(sprintf('select filename,data from %s where template = %d', # $GLOBALS["tables"]["templateimage"],$cached[$messageid]["templateid"])); $htmlmessage = eregi_replace("\\[USERID\\]", $hash, $htmlmessage); $textmessage = eregi_replace("\\[USERID\\]", $hash, $textmessage); $htmlmessage = preg_replace("/\\[USERTRACK\\]/i", '<img src="' . $GLOBALS['scheme'] . '://' . $website . $GLOBALS["pageroot"] . '/ut.php?u=' . $hash . '&m=' . $messageid . '" width="1" height="1" border="0">', $htmlmessage, 1); $htmlmessage = eregi_replace("\\[USERTRACK\\]", '', $htmlmessage); if ($listowner) { $att_req = Sql_Query("select name,value from {$GLOBALS["tables"]["adminattribute"]},{$GLOBALS["tables"]["admin_attribute"]} where {$GLOBALS["tables"]["adminattribute"]}.id = {$GLOBALS["tables"]["admin_attribute"]}.adminattributeid and {$GLOBALS["tables"]["admin_attribute"]}.adminid = {$listowner}"); while ($att = Sql_Fetch_Array($att_req)) { $htmlmessage = preg_replace("#\\[LISTOWNER." . strtoupper(preg_quote($att["name"])) . "\\]#", $att["value"], $htmlmessage); } } if (is_array($GLOBALS["default_config"])) { foreach ($GLOBALS["default_config"] as $key => $val) { if (is_array($val)) { $htmlmessage = eregi_replace("\\[{$key}\\]", getConfig($key), $htmlmessage); $textmessage = eregi_replace("\\[{$key}\\]", getConfig($key), $textmessage); } } } ## RSS if (ENABLE_RSS && sizeof($rssitems)) { $rssentries = array(); $request = join(",", $rssitems); $texttemplate = getConfig("rsstexttemplate"); $htmltemplate = getConfig("rsshtmltemplate"); $textseparatortemplate = getConfig("rsstextseparatortemplate"); $htmlseparatortemplate = getConfig("rsshtmlseparatortemplate"); $req = Sql_Query("select * from {$GLOBALS["tables"]["rssitem"]} where id in ({$request}) order by list,added"); $curlist = ""; while ($row = Sql_Fetch_array($req)) { if ($curlist != $row["list"]) { $row["listname"] = ListName($row["list"]); $curlist = $row["list"]; $rssentries["text"] .= parseRSSTemplate($textseparatortemplate, $row); $rssentries["html"] .= parseRSSTemplate($htmlseparatortemplate, $row); } $data_req = Sql_Query("select * from {$GLOBALS["tables"]["rssitem_data"]} where itemid = {$row["id"]}"); while ($data = Sql_Fetch_Array($data_req)) { $row[$data["tag"]] = $data["data"]; } $rssentries["text"] .= stripHTML(parseRSSTemplate($texttemplate, $row)); $rssentries["html"] .= parseRSSTemplate($htmltemplate, $row); } $htmlmessage = eregi_replace("\\[RSS\\]", $rssentries["html"], $htmlmessage); $textmessage = eregi_replace("\\[RSS\\]", $rssentries["text"], $textmessage); } if (is_array($userdata)) { foreach ($userdata as $name => $value) { if (eregi("\\[" . $name . "\\]", $htmlmessage, $regs)) { $htmlmessage = eregi_replace("\\[" . $name . "\\]", $value, $htmlmessage); } if (eregi("\\[" . $name . "\\]", $textmessage, $regs)) { $textmessage = eregi_replace("\\[" . $name . "\\]", $value, $textmessage); } } } $destinationemail = ''; if (is_array($user_att_values)) { foreach ($user_att_values as $att_name => $att_value) { if (eregi("\\[" . $att_name . "\\]", $htmlmessage, $regs)) { # the value may be a multiline textarea field $htmlatt_value = str_replace("\n", "<br/>\n", $att_value); $htmlmessage = eregi_replace("\\[" . $att_name . "\\]", $htmlatt_value, $htmlmessage); } if (eregi("\\[" . $att_name . "\\]", $textmessage, $regs)) { $textmessage = eregi_replace("\\[" . $att_name . "\\]", $att_value, $textmessage); } # @@@ undocumented, use alternate field for real email to send to if (isset($GLOBALS["alternate_email"]) && strtolower($att_name) == strtolower($GLOBALS["alternate_email"])) { $destinationemail = $att_value; } } } if (!$destinationemail) { $destinationemail = $email; } if (!ereg('@', $destinationemail) && isset($GLOBALS["expand_unqualifiedemail"])) { $destinationemail .= $GLOBALS["expand_unqualifiedemail"]; } if (eregi("\\[LISTS\\]", $htmlmessage)) { $lists = ""; $listsarr = array(); $req = Sql_Query(sprintf('select list.name from %s as list,%s as listuser where list.id = listuser.listid and listuser.userid = %d', $GLOBALS["tables"]["list"], $GLOBALS["tables"]["listuser"], $user_system_values["id"])); while ($row = Sql_Fetch_Row($req)) { array_push($listsarr, $row[0]); } $lists_html = join('<br/>', $listsarr); $lists_text = join("\n", $listsarr); $htmlmessage = ereg_replace("\\[LISTS\\]", $lists_html, $htmlmessage); $textmessage = ereg_replace("\\[LISTS\\]", $lists_text, $textmessage); } ## click tracking # for now we won't click track forwards, as they are not necessarily users, so everything would fail if (CLICKTRACK && $hash != 'forwarded') { $urlbase = ''; # let's leave this for now /* if (preg_match('/<base href="(.*)"([^>]*)>/Umis',$htmlmessage,$regs)) { $urlbase = $regs[1]; } else { $urlbase = ''; } # print "URLBASE: $urlbase<br/>"; */ # convert html message # preg_match_all('/<a href="?([^> "]*)"?([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links); preg_match_all('/<a(.*)href=["\'](.*)["\']([^>]*)>(.*)<\\/a>/Umis', $htmlmessage, $links); # to process the Yahoo webpage with base href and link like <a href=link> we'd need this one # preg_match_all('/<a href=([^> ]*)([^>]*)>(.*)<\/a>/Umis',$htmlmessage,$links); $clicktrack_root = sprintf('%s://%s/lt.php', $GLOBALS["scheme"], $website . $GLOBALS["pageroot"]); for ($i = 0; $i < count($links[2]); $i++) { $link = cleanUrl($links[2][$i]); $link = str_replace('"', '', $link); if (preg_match('/\\.$/', $link)) { $link = substr($link, 0, -1); } $linkid = 0; # print "LINK: $link<br/>"; if ((preg_match('/^http|ftp/', $link) || preg_match('/^http|ftp/', $urlbase)) && $link != 'http://www.phplist.com' && !strpos($link, $clicktrack_root)) { # take off personal uids $url = cleanUrl($link, array('PHPSESSID', 'uid')); # $url = preg_replace('/&uid=[^\s&]+/','',$link); # if (!strpos('http:',$link)) { # $link = $urlbase . $link; # } $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward) values(%d,%d,"%s","%s")', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $url, addslashes($link))); $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s" ', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $link)); $linkid = $req[0]; $masked = "H|{$linkid}|{$messageid}|" . $userdata['id'] ^ XORmask; $masked = urlencode(base64_encode($masked)); $newlink = sprintf('<a%shref="%s://%s/lt.php?id=%s" %s>%s</a>', $links[1][$i], $GLOBALS["scheme"], $website . $GLOBALS["pageroot"], $masked, $links[3][$i], $links[4][$i]); $htmlmessage = str_replace($links[0][$i], $newlink, $htmlmessage); } } # convert Text message # first find occurances of our top domain, to avoid replacing them later # hmm, this is no point, it's not just *our* topdomain, but any if (0) { preg_match_all('#(https?://' . $GLOBALS['website'] . '/?)\\s+#mis', $textmessage, $links); # preg_match_all('#(https?://[a-z0-9\./\#\?&:@=%\-]+)#ims',$textmessage,$links); # preg_match_all('!(https?:\/\/www\.[a-zA-Z0-9\.\/#~\?+=&%@-_]+)!mis',$textmessage,$links); for ($i = 0; $i < count($links[1]); $i++) { # not entirely sure why strtolower was used, but it seems to break things http://mantis.tincan.co.uk/view.php?id=4406 # $link = strtolower(cleanUrl($links[1][$i])); $link = cleanUrl($links[1][$i]); if (preg_match('/\\.$/', $link)) { $link = substr($link, 0, -1); } $linkid = 0; if (preg_match('/^http|ftp/', $link) && $link != 'http://www.phplist.com' && !strpos($link, $clicktrack_root)) { $url = cleanUrl($link, array('PHPSESSID', 'uid')); $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward) values(%d,%d,"%s","%s")', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $url, $link)); $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s" ', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $link)); $linkid = $req[0]; $masked = "T|{$linkid}|{$messageid}|" . $userdata['id'] ^ XORmask; $masked = urlencode(base64_encode($masked)); $newlink = sprintf('%s://%s/lt.php?id=%s', $GLOBALS["scheme"], $website . $GLOBALS["pageroot"], $masked); $textmessage = str_replace($links[0][$i], '<' . $newlink . '>', $textmessage); } } } #now find the rest # @@@ needs to expand to find complete urls like: #http://user:password@www.web-site.com:1234/document.php?parameter=something&otherpar=somethingelse#anchor # or secure #https://user:password@www.website.com:2345/document.php?parameter=something%20&otherpar=somethingelse#anchor preg_match_all('#(https?://[^\\s\\>\\}\\,]+)#mis', $textmessage, $links); # preg_match_all('#(https?://[a-z0-9\./\#\?&:@=%\-]+)#ims',$textmessage,$links); # preg_match_all('!(https?:\/\/www\.[a-zA-Z0-9\.\/#~\?+=&%@-_]+)!mis',$textmessage,$links); ## sort the results in reverse order, so that they are replaced correctly rsort($links[1]); $newlinks = array(); for ($i = 0; $i < count($links[1]); $i++) { $link = cleanUrl($links[1][$i]); if (preg_match('/\\.$/', $link)) { $link = substr($link, 0, -1); } $linkid = 0; if (preg_match('/^http|ftp/', $link) && $link != 'http://www.phplist.com') { # && !strpos($link,$clicktrack_root)) { $url = cleanUrl($link, array('PHPSESSID', 'uid')); $req = Sql_Query(sprintf('insert ignore into %s (messageid,userid,url,forward) values(%d,%d,"%s","%s")', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $url, $link)); $req = Sql_Fetch_Row_Query(sprintf('select linkid from %s where messageid = %s and userid = %d and forward = "%s" ', $GLOBALS['tables']['linktrack'], $messageid, $userdata['id'], $link)); $linkid = $req[0]; $masked = "T|{$linkid}|{$messageid}|" . $userdata['id'] ^ XORmask; $masked = urlencode(base64_encode($masked)); $newlinks[$linkid] = sprintf('%s://%s/lt.php?id=%s', $GLOBALS["scheme"], $website . $GLOBALS["pageroot"], $masked); # print $links[0][$i] .' -> '.$newlink.'<br/>'; $textmessage = str_replace($links[1][$i], '[%%%' . $linkid . '%%%]', $textmessage); } } foreach ($newlinks as $linkid => $newlink) { $textmessage = str_replace('[%%%' . $linkid . '%%%]', $newlink, $textmessage); } } # if (eregi("\\[LISTS\\]", $htmlmessage)) { $lists = ""; $listsarr = array(); $req = Sql_Query(sprintf('select list.name from %s as list,%s as listuser where list.id = listuser.listid and listuser.userid = %d', $tables["list"], $tables["listuser"], $user_system_values["id"])); while ($row = Sql_Fetch_Row($req)) { array_push($listsarr, $row[0]); } $lists_html = join('<br/>', $listsarr); $lists_text = join("\n", $listsarr); $htmlmessage = ereg_replace("\\[LISTS\\]", $lists_html, $htmlmessage); $textmessage = ereg_replace("\\[LISTS\\]", $lists_text, $textmessage); } #0011996: forward to friend - personal message if (FORWARD_PERSONAL_NOTE_SIZE && ($hash = 'forwarded' && !empty($forwardedby['personalNote']))) { $htmlmessage = nl2br($forwardedby['personalNote']) . '<br/>' . $htmlmessage; $textmessage = $forwardedby['personalNote'] . "\n" . $textmessage; } ## remove any existing placeholders $htmlmessage = eregi_replace("\\[[A-Z\\. ]+\\]", "", $htmlmessage); $textmessage = eregi_replace("\\[[A-Z\\. ]+\\]", "", $textmessage); ## check that the HTML message as proper <head> </head> and <body> </body> tags # some readers fail when it doesn't if (!preg_match("#<body.*</body>#ims", $htmlmessage)) { $htmlmessage = '<body>' . $htmlmessage . '</body>'; } if (!preg_match("#<head>.*</head>#ims", $htmlmessage)) { if (!$adddefaultstyle) { $defaultstyle = ""; } $htmlmessage = '<head> <meta content="text/html;charset=' . $cached[$messageid]["html_charset"] . '" http-equiv="Content-Type"> <title></title>' . $defaultstyle . '</head>' . $htmlmessage; } if (!preg_match("#<html>.*</html>#ims", $htmlmessage)) { $htmlmessage = '<html>' . $htmlmessage . '</html>'; } # particularly Outlook seems to have trouble if it is not \r\n # reports have come that instead this creates lots of trouble # this is now done in the global sendMail function, so it is not # necessary here # if (USE_CARRIAGE_RETURNS) { # $htmlmessage = preg_replace("/\r?\n/", "\r\n", $htmlmessage); # $textmessage = preg_replace("/\r?\n/", "\r\n", $textmessage); # } ## build the email if (!PHPMAILER) { $mail = new html_mime_mail(array('X-Mailer: PHPlist v' . VERSION, "X-MessageId: {$messageid}", "X-ListMember: {$email}", "Precedence: bulk", "List-Help: <" . $text["preferences"] . ">", "List-Unsubscribe: <" . $text["unsubscribe"] . ">", "List-Subscribe: <" . getConfig("subscribeurl") . ">", "List-Owner: <mailto:" . getConfig("admin_address") . ">")); } else { $mail = new PHPlistMailer($messageid, $destinationemail); if ($forwardedby) { $mail->add_timestamp(); } #$mail->IsSMTP(); } list($dummy, $domaincheck) = split('@', $destinationemail); $text_domains = explode("\n", trim(getConfig("alwayssendtextto"))); if (in_array($domaincheck, $text_domains)) { $htmlpref = 0; if (VERBOSE) { output($GLOBALS['I18N']->get('sendingtextonlyto') . " {$domaincheck}"); } } list($dummy, $domaincheck) = split('@', $email); $text_domains = explode("\n", trim(getConfig("alwayssendtextto"))); if (in_array($domaincheck, $text_domains)) { $htmlpref = 0; if (VERBOSE) { output("Sending text only to {$domaincheck}"); } } # so what do we actually send? switch ($cached[$messageid]["sendformat"]) { case "HTML": // # send html to users who want it and text to everyone else // if ($htmlpref) { // Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = $messageid"); // if (ENABLE_RSS && sizeof($rssitems)) // updateRSSStats($rssitems,"ashtml"); // # dbg("Adding HTML ".$cached[$messageid]["templateid"]); // $mail->add_html($htmlmessage,"",$cached[$messageid]["templateid"]); // addAttachments($messageid,$mail,"HTML"); // } else { // Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid"); // if (ENABLE_RSS && sizeof($rssitems)) // updateRSSStats($rssitems,"astext"); // $mail->add_text($textmessage); // addAttachments($messageid,$mail,"text"); // } // break; // # send html to users who want it and text to everyone else // if ($htmlpref) { // Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = $messageid"); // if (ENABLE_RSS && sizeof($rssitems)) // updateRSSStats($rssitems,"ashtml"); // # dbg("Adding HTML ".$cached[$messageid]["templateid"]); // $mail->add_html($htmlmessage,"",$cached[$messageid]["templateid"]); // addAttachments($messageid,$mail,"HTML"); // } else { // Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = $messageid"); // if (ENABLE_RSS && sizeof($rssitems)) // updateRSSStats($rssitems,"astext"); // $mail->add_text($textmessage); // addAttachments($messageid,$mail,"text"); // } // break; case "both": case "text and HTML": # send one big file to users who want html and text to everyone else if ($htmlpref) { Sql_Query("update {$GLOBALS["tables"]["message"]} set ashtml = ashtml + 1 where id = {$messageid}"); if (ENABLE_RSS && sizeof($rssitems)) { updateRSSStats($rssitems, "ashtml"); } # dbg("Adding HTML ".$cached[$messageid]["templateid"]); $mail->add_html($htmlmessage, $textmessage, $cached[$messageid]["templateid"]); addAttachments($messageid, $mail, "HTML"); } else { Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}"); if (ENABLE_RSS && sizeof($rssitems)) { updateRSSStats($rssitems, "astext"); } $mail->add_text($textmessage); addAttachments($messageid, $mail, "text"); } break; case "PDF": # send a PDF file to users who want html and text to everyone else if (ENABLE_RSS && sizeof($rssitems)) { updateRSSStats($rssitems, "astext"); } if ($htmlpref) { Sql_Query("update {$GLOBALS["tables"]["message"]} set aspdf = aspdf + 1 where id = {$messageid}"); $pdffile = createPdf($textmessage); if (is_file($pdffile) && filesize($pdffile)) { $fp = fopen($pdffile, "r"); if ($fp) { $contents = fread($fp, filesize($pdffile)); fclose($fp); unlink($pdffile); $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <embed src="message.pdf" width="450" height="450" href="message.pdf"></embed> </body> </html>'; # $mail->add_html($html,$textmessage); # $mail->add_text($textmessage); $mail->add_attachment($contents, "message.pdf", "application/pdf"); } } addAttachments($messageid, $mail, "HTML"); } else { Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}"); $mail->add_text($textmessage); addAttachments($messageid, $mail, "text"); } break; case "text and PDF": if (ENABLE_RSS && sizeof($rssitems)) { updateRSSStats($rssitems, "astext"); } # send a PDF file to users who want html and text to everyone else if ($htmlpref) { Sql_Query("update {$GLOBALS["tables"]["message"]} set astextandpdf = astextandpdf + 1 where id = {$messageid}"); $pdffile = createPdf($textmessage); if (is_file($pdffile) && filesize($pdffile)) { $fp = fopen($pdffile, "r"); if ($fp) { $contents = fread($fp, filesize($pdffile)); fclose($fp); unlink($pdffile); $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <embed src="message.pdf" width="450" height="450" href="message.pdf"></embed> </body> </html>'; # $mail->add_html($html,$textmessage); $mail->add_text($textmessage); $mail->add_attachment($contents, "message.pdf", "application/pdf"); } } addAttachments($messageid, $mail, "HTML"); } else { Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}"); $mail->add_text($textmessage); addAttachments($messageid, $mail, "text"); } break; case "text": default: # send as text if (ENABLE_RSS && sizeof($rssitems)) { updateRSSStats($rssitems, "astext"); } Sql_Query("update {$GLOBALS["tables"]["message"]} set astext = astext + 1 where id = {$messageid}"); $mail->add_text($textmessage); addAttachments($messageid, $mail, "text"); break; } $mail->build_message(array("html_charset" => $cached[$messageid]["html_charset"], "html_encoding" => HTMLEMAIL_ENCODING, "text_charset" => $cached[$messageid]["text_charset"], "text_encoding" => TEXTEMAIL_ENCODING)); if (!TEST) { if ($hash != 'forwarded' || !sizeof($forwardedby)) { $fromname = $cached[$messageid]["fromname"]; $fromemail = $cached[$messageid]["fromemail"]; $subject = $cached[$messageid]["subject"]; } else { $fromname = ''; $fromemail = $forwardedby['email']; $subject = $GLOBALS['strFwd'] . ': ' . $cached[$messageid]["subject"]; } if (!$mail->send("", $destinationemail, $fromname, $fromemail, $subject)) { logEvent("Error sending message {$messageid} to {$email} ({$destinationemail})"); return 0; } else { return 1; } } return 0; }
function display() { global $app; $params = $app->getParams(); $rsws_document =& JFactory::getDocument(); $rsws_document->addStyleSheet(JURI::root() . 'components/com_rsmonials/css/style.css'); // Custom Style $rsws_custom_style = '.RSWS_testi_block {'; $rsws_testimonial_block_border = fetchParamStyle('testimonial_block_border'); if ($rsws_testimonial_block_border) { $rsws_custom_style .= ' border: ' . $rsws_testimonial_block_border . ';'; } $rsws_testimonial_block_background_color = fetchParamStyle('testimonial_block_background_color'); if ($rsws_testimonial_block_background_color) { $rsws_custom_style .= ' background-color: ' . $rsws_testimonial_block_background_color . ';'; } $rsws_testimonial_block_rounded_corner = fetchParamStyle('testimonial_block_rounded_corner'); $rsws_testimonial_block_rounded_corner_radius = fetchParamStyle('testimonial_block_rounded_corner_radius'); if (!$rsws_testimonial_block_rounded_corner_radius) { $rsws_testimonial_block_rounded_corner_radius = '10'; } if ($rsws_testimonial_block_rounded_corner == 'true') { $rsws_custom_style .= ' -moz-border-radius:' . $rsws_testimonial_block_rounded_corner_radius . 'px; -webkit-border-radius:' . $rsws_testimonial_block_rounded_corner_radius . 'px; behavior:url(border-radius.htc);'; } $rsws_testimonial_block_enable_gradient = fetchParamStyle('testimonial_block_enable_gradient'); $rsws_testimonial_block_gradient_start_color = fetchParamStyle('testimonial_block_gradient_start_color'); $rsws_testimonial_block_gradient_end_color = fetchParamStyle('testimonial_block_gradient_end_color'); if ($rsws_testimonial_block_enable_gradient == 'true') { $rsws_custom_style .= ' filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="' . $rsws_testimonial_block_gradient_start_color . '", endColorstr="' . $rsws_testimonial_block_gradient_end_color . '"); background: -webkit-gradient(linear, left top, left bottom, from(' . $rsws_testimonial_block_gradient_start_color . '), to(' . $rsws_testimonial_block_gradient_end_color . ')); background: -moz-linear-gradient(top, ' . $rsws_testimonial_block_gradient_start_color . ', ' . $rsws_testimonial_block_gradient_end_color . ');'; } $rsws_custom_style .= '}'; // $rsws_document->addStyleDeclaration($rsws_custom_style); headerT(); //echo '<div><br /><hr align="center" width="100%" size="1" noshade="noshade" class="RSWS_hr_color" /><br /></div>'; if ($params->def('rsm_show_what') != '2') { $database =& JFactory::getDBO(); if (fetchParam('show_pagination') == 'true') { $database->setQuery("select count(*) as tot from `#__" . RSWEBSOLS_TABLE_PREFIX . "` where `status`='1'"); $dataTesti = $database->loadObject(); $totalTesti = $dataTesti->tot; $paginationStore = fetchParam('pagination'); $itemEachPage = $paginationStore > 0 ? fetchParam('pagination') : 10; $totalTestiPage = ceil($totalTesti / $itemEachPage); if ($_REQUEST['page'] > 0) { $currPage = $_REQUEST['page']; } else { $currPage = 1; } $lStart = ($currPage - 1) * $itemEachPage; $lEnd = $itemEachPage; $database->setQuery("select * from `#__" . RSWEBSOLS_TABLE_PREFIX . "` where `status`='1' order by `date` desc, `id` desc limit " . $lStart . ", " . $lEnd . ""); } else { $database->setQuery("select * from `#__" . RSWEBSOLS_TABLE_PREFIX . "` where `status`='1' order by `date` desc, `id` desc"); } $items = $database->loadObjectList(); if (count($items) > 0) { $rsws_qis = fetchParamStyle('testimonial_block_quotation_image_style'); $rsws_noimg = fetchParamStyle('testimonial_block_default_image'); $rsws_imgpos = fetchParamStyle('testimonial_block_image_position'); $rsws_imgmax = fetchParamStyle('testimonial_block_image_display_width'); $rsws_dshow = fetchParamStyle('testimonial_block_show_date'); if ($rsws_qis == '0') { $left_quote = ''; $right_quote = ''; } else { if ($rsws_qis == '1') { $left_quote = '<span class="RSWS_left_quote"><img src="components/com_rsmonials/images/quote-left.png" /></span>'; $right_quote = '<span class="RSWS_right_quote"><img src="components/com_rsmonials/images/quote-right.png" /></span>'; } else { $left_quote = '<span class="RSWS_left_quote"><img src="components/com_rsmonials/images/quote_left.png" /></span>'; $right_quote = '<span class="RSWS_right_quote"><img src="components/com_rsmonials/images/quote_right.png" /></span>'; } } if ($rsws_noimg == '1') { $rsws_noimg = '<img class="RSWS_testi_img" src="' . JURI::root() . 'components/com_rsmonials/images/default_user_0.png" style="width:' . $rsws_imgmax . 'px;" />'; } else { if ($rsws_noimg == '2') { $rsws_noimg = '<img class="RSWS_testi_img" src="' . JURI::root() . 'components/com_rsmonials/images/default_user_1.png" style="width:' . $rsws_imgmax . 'px;" />'; } else { if ($rsws_noimg == '3') { $rsws_noimg = '<img class="RSWS_testi_img" src="' . JURI::root() . 'components/com_rsmonials/images/default_user_2.png" style="width:' . $rsws_imgmax . 'px;" />'; } else { $rsws_noimg = ''; } } } $rsws_alt_cntr = 1; foreach ($items as $item) { $dateExp = explode('-', $item->date); $timestamp = mktime(12, 0, 0, $dateExp[1], $dateExp[2], $dateExp[0]); $dateConfig =& JFactory::getConfig(); $siteLang = $dateConfig->getValue('config.language'); setlocale(LC_ALL, $siteLang); $dateView = strftime("%d %B %Y", $timestamp); //$dateView = date('d F Y', $timestamp); $extra = ""; $extra2 = ""; if (trim($item->about) != "") { if ($extra != "") { $extra .= ", "; } else { $extra .= "<br />"; } $extra .= stripHTML($item->about); } if (trim($item->location) != "") { if ($extra != "") { $extra .= ", "; } else { $extra .= "<br />"; } $extra .= stripHTML($item->location); } if (trim($item->website) != "") { $extra2 .= "<br />" . stripHTML($item->website); } ?> <div class="RSWS_testi_block"> <?php $rsws_testi_cont = '<div class="RSWS_testimonial">' . $left_quote . '<span>' . stripHTML($item->comment) . '</span>' . $right_quote . '</div>'; $rsws_testi_subcont = '<div> </div><div class="RSWS_testmonial_subtext">'; if ($rsws_dshow != 'false') { $rsws_testi_subcont .= '<em>' . JText::_('RSM_TXT_POSTING_DATE') . ': ' . $dateView . '<br />'; } $rsws_testi_subcont .= '' . JText::_('RSM_TXT_POSTED_BY') . ': ' . stripHTML($item->fname) . ' ' . stripHTML($item->lname) . $extra . $extra2 . '</em></div>'; if (fetchParam('show_image') == 'true') { $testi_pic_file = ''; if (file_exists(JPATH_ROOT . DS . 'images' . DS . 'com_rsmonials' . DS . $item->id . '.gif')) { $testi_pic_file = '<img class="RSWS_testi_img" src="' . JURI::root() . 'images/com_rsmonials/' . $item->id . '.gif" style="width:' . $rsws_imgmax . 'px;" />'; } else { if (file_exists(JPATH_ROOT . DS . 'images' . DS . 'com_rsmonials' . DS . $item->id . '.png')) { $testi_pic_file = '<img class="RSWS_testi_img" src="' . JURI::root() . 'images/com_rsmonials/' . $item->id . '.png" style="width:' . $rsws_imgmax . 'px;" />'; } else { if (file_exists(JPATH_ROOT . DS . 'images' . DS . 'com_rsmonials' . DS . $item->id . '.jpg')) { $testi_pic_file = '<img class="RSWS_testi_img" src="' . JURI::root() . 'images/com_rsmonials/' . $item->id . '.jpg" style="width:' . $rsws_imgmax . 'px;" />'; } else { if (file_exists(JPATH_ROOT . DS . 'images' . DS . 'com_rsmonials' . DS . $item->id . '.jpeg')) { $testi_pic_file = '<img class="RSWS_testi_img" src="' . JURI::root() . 'images/com_rsmonials/' . $item->id . '.jpeg" style="width:' . $rsws_imgmax . 'px;" />'; } else { $testi_pic_file = $rsws_noimg; } } } } echo '<table width="100%" cellpadding="0" cellspacing="0" border="0" class="RSWS_testi_main"><tr>'; if ($rsws_imgpos == '3') { if ($rsws_alt_cntr % 2 == 0) { echo '<td valign="top" align="left">' . $rsws_testi_cont . $rsws_testi_subcont . '</td><td align="right" valign="top" style="width:' . ($testi_pic_file == '' ? 0 : $rsws_imgmax + 20) . 'px;">' . $testi_pic_file . '</td>'; } else { echo '<td valign="top" align="left" style="width:' . ($testi_pic_file == '' ? 0 : $rsws_imgmax + 20) . 'px;">' . $testi_pic_file . '</td><td valign="top" align="left">' . $rsws_testi_cont . $rsws_testi_subcont . '</td>'; } } else { if ($rsws_imgpos == '2') { echo '<td valign="top" align="left">' . $rsws_testi_cont . $rsws_testi_subcont . '</td><td valign="top" align="right" style="width:' . ($testi_pic_file == '' ? 0 : $rsws_imgmax + 20) . 'px;">' . $testi_pic_file . '</td>'; } else { echo '<td valign="top" align="left" style="width:' . ($testi_pic_file == '' ? 0 : $rsws_imgmax + 20) . 'px;">' . $testi_pic_file . '</td><td valign="top" align="left">' . $rsws_testi_cont . $rsws_testi_subcont . '</td>'; } } echo '</tr></table>'; } else { echo $rsws_testi_cont . $rsws_testi_subcont; } ?> </div> <!--<div> <br /> <hr align="center" width="100%" size="1" noshade="noshade" class="RSWS_hr_color" /> <br /> </div>--> <?php $rsws_alt_cntr++; } if (fetchParam('show_pagination') == 'true') { ?> <div class="RSWS_pagination_text" style="text-align:<?php echo fetchParam('pagination_alignment'); ?> ;"> <br /> <?php if ($currPage > 1) { ?> <a href="index.php?option=<?php echo $_REQUEST['option']; ?> &page=1" title="<?php echo JText::_('RSM_TXT_PAGINATION_START'); ?> "><?php echo JText::_('RSM_TXT_PAGINATION_START'); ?> </a> <?php } else { echo JText::_('RSM_TXT_PAGINATION_START'); } ?> <?php if ($currPage > 1) { ?> <a href="index.php?option=<?php echo $_REQUEST['option']; ?> &page=<?php echo $currPage - 1; ?> " title="<?php echo JText::_('RSM_TXT_PAGINATION_PREV'); ?> "><?php echo JText::_('RSM_TXT_PAGINATION_PREV'); ?> </a> <?php } else { echo JText::_('RSM_TXT_PAGINATION_PREV'); } ?> <?php for ($i = 1; $i <= $totalTestiPage; $i++) { if ($currPage == $i) { echo ' <strong>' . $i . '</strong> '; } else { echo ' <a href="index.php?option=' . $_REQUEST['option'] . '&page=' . $i . '">' . $i . '</a> '; } } ?> <?php if ($currPage < $totalTestiPage) { ?> <a href="index.php?option=<?php echo $_REQUEST['option']; ?> &page=<?php echo $currPage + 1; ?> " title="<?php echo JText::_('RSM_TXT_PAGINATION_NEXT'); ?> "><?php echo JText::_('RSM_TXT_PAGINATION_NEXT'); ?> </a> <?php } else { echo JText::_('RSM_TXT_PAGINATION_NEXT'); } ?> <?php if ($currPage < $totalTestiPage) { ?> <a href="index.php?option=<?php echo $_REQUEST['option']; ?> &page=<?php echo $totalTestiPage; ?> " title="<?php echo JText::_('RSM_TXT_PAGINATION_LAST'); ?> "><?php echo JText::_('RSM_TXT_PAGINATION_LAST'); ?> </a> <?php } else { echo JText::_('RSM_TXT_PAGINATION_LAST'); } ?> <br /><br /> <?php echo JText::sprintf('RSM_TXT_PAGINATION_PAGE_OUTOF_TOTAL', $currPage, $totalTestiPage); ?> </div> <div><br /></div> <div><br /></div> <?php } } else { ?> <div> <p> <span class="RSWS_left_quote"><img src="components/com_rsmonials/images/lrs.gif" /></span> <span class="RSWS_testimonial"><?php echo JText::_('RSM_TXT_NO_TESTI'); ?> </span> <span class="RSWS_right_quote"><img src="components/com_rsmonials/images/rrs.gif" /></span> </p> </div> <div> <br /> <hr align="center" width="100%" size="1" noshade="noshade" class="RSWS_hr_color" /> <br /> </div> <?php } } footerT(); }
function getEntryContentView($blogid, $id, $content, $formatter, $keywords = array(), $type = 'Post', $useAbsolutePath = true, $bRssMode = false) { $context = Model_Context::getInstance(); importlib('model.blog.attachment'); importlib('model.blog.keyword'); importlib('blogskin'); $context = Model_Context::getInstance(); $cacheKey = 'entry-' . $id . '-' . $type . ($bRssMode ? 'format' : 'summarize') . ($useAbsolutePath ? 'absoultePath' : 'relativePath') . $context->getProperty('blog.displaymode', 'desktop'); $cache = pageCache::getInstance(); $cache->reset($cacheKey); if (!defined('__TEXTCUBE_NO_ENTRY_CACHE__') && $cache->load()) { // If cached content exists. $view = $cache->contents; } else { // No cache is found. $content = fireEvent('Format' . $type . 'Content', $content, $id); $func = $bRssMode ? 'summarizeContent' : 'formatContent'; $view = $func($blogid, $id, $content, $formatter, $keywords, $useAbsolutePath); if ($context->getProperty('blog.displaymode', 'desktop') == 'mobile') { $view = stripHTML($view, array('a', 'abbr', 'acronym', 'address', 'b', 'blockquote', 'br', 'caption', 'cite', 'code', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'iframe', 'img', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 's', 'samp', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'u', 'ul', 'var')); } if (!$useAbsolutePath) { $view = avoidFlashBorder($view); } if (!empty($keywords) && is_array($keywords)) { $view = bindKeywords($keywords, $view); } // image resampling if (Setting::getBlogSettingGlobal('resamplingDefault') == true) { preg_match_all("@<img.+src=['\"](.+)['\"](.*)/?>@Usi", $view, $images, PREG_SET_ORDER); $view = preg_replace("@<img.+src=['\"].+['\"].*/?>@Usi", '[#####_#####_#####_image_#####_#####_#####]', $view); $contentWidth = Utils_Misc::getContentWidth(); if (count($images) > 0) { for ($i = 0; $i < count($images); $i++) { if (strtolower(Utils_Misc::getFileExtension($images[$i][1])) == 'gif') { $view = preg_replace('@\\[#####_#####_#####_image_#####_#####_#####\\]@', $images[$i][0], $view, 1); continue; } $attributes = preg_match('/(style="cursor: pointer;" onclick="open_img\\((.[^"]+)\\); return false;")/si', $images[$i][2], $matches) ? ' ' . $matches[1] : ''; $attributes .= preg_match('/(alt="([^"]*)")/si', $images[$i][2], $matches) ? ' ' . $matches[1] : ' alt="resize"'; $attributes .= preg_match('/(title="([^"]*)")/si', $images[$i][2], $matches) ? $title = ' ' . $matches[1] : ''; $tempFileName = array_pop(explode('/', $images[$i][1])); if (preg_match('/(.+)\\.w(\\d{1,})\\-h(\\d{1,})\\.(.+)/', $tempFileName, $matches)) { $tempFileName = $matches[1] . '.' . $matches[4]; } $newImage = $images[$i][0]; if (file_exists(__TEXTCUBE_ATTACH_DIR__ . "/{$blogid}/{$tempFileName}")) { $tempAttributes = Utils_Misc::getAttributesFromString($images[$i][2]); $tempOriginInfo = getimagesize(__TEXTCUBE_ATTACH_DIR__ . "/{$blogid}/{$tempFileName}"); if (isset($tempAttributes['width']) && $tempOriginInfo[0] > $tempAttributes['width']) { $image = Utils_Image::getInstance(); list($tempImageURL, $tempImageWidth, $tempImageHeight, $tempImageSrc) = $image->getImageResizer($tempFileName, array('width' => $tempAttributes['width'])); $newImage = "<img src=\"{$tempImageURL}\" width=\"{$tempImageWidth}\" height=\"{$tempImageHeight}\"{$attributes}/>"; } } $view = preg_replace('@\\[#####_#####_#####_image_#####_#####_#####\\]@', $newImage, $view, 1); } } } $cache->contents = $view; $cache->update(); } $cache->reset(); $view = fireEvent('View' . $type . 'Content', $view, $id); return $view; }
function sendMail($mailto, $subject, &$mail, $mailfrom = "", $header = "", $isHTML = true, $attach = "") { # mailto = destination mail, accepts extended version (name <mail>) and comma delimited list # subject = subject line # mail = template with the fill mail >>>OBJECT<<< # mailfrom = "from" mail # header (optional) = headers, you might or might not fill a Content-Type # isHTML = if true, adds proper Content-Type # attach = filename for attachment $subject = str_replace("\n", "", $subject); // bye exploit $subject = str_replace("\r", "", $subject); // bye exploit if (preg_match('!\\S!u', $subject) !== 0) { $subject = '=?UTF-8?B?' . base64_encode($subject) . '?='; } if ($mailfrom == "" && strpos($mailto, ",") === false) { $mailfrom = $mailto; } // no mailfrom, use mailti if ($header != "" && $header[strlen($header) - 1] != "\n") { $header .= "\n"; } // add \n at the end of the last line of pre-defined header $mailfrom = str_replace("\n", "", $mailfrom); // bye exploit if (strpos(strtoupper($header), "RETURN-PATH:") === false && isMail($mailfrom, true)) { // no R-P, add if possible $header .= "Return-path: {$mailfrom}\n"; } if (strpos(strtoupper($header), "REPLY-TO:") === false && isMail($mailfrom, true)) { // no R-T, add if possible $header .= "Reply-To: {$mailfrom}\n"; } if (strpos(strtoupper($header), "FROM:") === false && isMail($mailfrom, true)) { // no FROM, add if possible $header .= "From: {$mailfrom}\n"; } if ($isHTML || $attach != "") { // HTML mode with attachment $isHTML = true; $bound = "--=XYZ_" . md5(date("dmYis")) . "_ZYX"; $bnext = "--=NextPart_XYZ_" . md5(date("dm")) . ".E0_PART"; $header .= "Content-Type:multipart/" . ($attach != "" ? "mixed" : "alternative") . "; boundary=\"{$bound}\"\n"; } else { // not HTML nor with attachment $header .= "Content-Type:text/plain; charset=utf-8\n"; } $header .= "MIME-Version: 1.0\n"; $header .= "x-mailer: PresciaMailer\n"; $mail->assign("IP", CONS_IP); $mail->assign("HOUR", date("H:i")); $mail->assign("DATA", date("d/m/Y")); $mail->assign("DATE", date("m/d/Y")); $corpo = $mail->techo(); if ($attach != "" && is_file($attach)) { // deal with attachment //Open file and convert to base64 $fOpen = fopen($attach, "rb"); $fAtach = fread($fOpen, filesize($attach)); $ext = explode(".", $attach); $ext = array_pop($ext); $fAtach = base64_encode($fAtach); fclose($fOpen); $fAtach = chunk_split($fAtach); $corpoplain = preg_replace("/( ){2,}/", " ", cleanHTML($corpo)); // Add multipart message $sBody = "This is a multipart MIME message.\n\n"; $sBody .= "--{$bound}\n"; $sBody .= "Content-Type: multipart/alternative; boundary=\"{$bnext}\"\n\n\n"; $sBody .= "--{$bnext}\n" . "Content-Type: text/plain; charset=utf-8\n\n" . $corpoplain . "\n\n" . "--{$bnext}\n"; $sBody .= "Content-Type:text/html; charset=utf-8\n\n"; $sBody .= "{$corpo} \n\n"; $sBody .= "--{$bnext}--\n\n"; $sBody .= "--{$bound}\n"; $fname = explode("/", str_replace("\\", "/", $attach)); $sBody .= "Content-Disposition: attachment; filename=" . array_pop($fname) . "\n"; if (!function_exists("getMime")) { include_once CONS_PATH_INCLUDE . "getMime.php"; } $sBody .= "Content-Type: " . getMime($ext) . "\n"; $sBody .= "Content-Transfer-Encoding: base64\n\n{$fAtach}\n"; $sBody .= "--{$bound}--\n\n"; } else { if ($isHTML) { $corpoplain = preg_replace("/( ){2,}/", " ", stripHTML($corpo)); $sBody = "This is a multipart MIME message.\n\n"; $sBody .= "--{$bound}\n" . "Content-Type: text/plain; charset=utf-8\n\n" . $corpoplain . "\n\n" . "--{$bound}\n" . "Content-Type: text/html; charset=utf-8\n\n" . $corpo . "\n\n" . "--{$bound}--\n"; } else { $sBody = $corpo; } } if (substr($subject, 0, 3) == "NS:") { $sBody .= chr(0); } // Newsletter character flag if (preg_match('@^([^<]*)<([^>]*)>(.?)$@i', $mailfrom, $matches) == 1) { $mailfrom = $matches[2]; } // removes expanded mail mode $ok = false; // will return false ONLY if ALL submissions fail $mailto = explode(",", $mailto); foreach ($mailto as $mt) { $mt = trim($mt); // Subject: =?UTF-8?B?".base64_encode($subject)."?= if (!@mail($mt, $subject, $sBody, $header, '-f' . $mailfrom)) { $ok = @mail($mt, $subject, $sBody, $header, '-r' . $mailfrom) || $ok; } else { $ok = true; } } return $ok; }
public function fill($ignoreParents = true) { // fills out the database $fillOutTo = 10; $added = 0; $files = listFiles(CONS_PATH_SYSTEM . "plugins/bi_dev/payload/", "@.*\\.(jpg|gif|png)@"); if (count($files) == 0) { echo "No files to fill at " . CONS_PATH_SYSTEM . "plugins/bi_dev/payload/"; return false; } foreach ($this->parent->modules as $mname => &$module) { if (defined("CONS_AUTH_USERMODULE")) { if ($mname == CONS_AUTH_USERMODULE || $mname == CONS_AUTH_GROUPMODULE) { continue; } // do not add user/groups } if (count($module->keys) > 1 && !$module->linker) { continue; } // do not multi-key items that are not linkers #TODO: allow this if ($mname == "contentman" || $mname == "seo" || $mname == "stats") { continue; } // don't meddle with contentman, stats or seo $ignoreMe = false; $hasParent = false; if (!$module->options[CONS_MODULE_SYSTEM]) { for ($i = 0; $i < $fillOutTo; $i++) { $dataToAdd = array(); if ($ignoreMe) { continue; } foreach ($module->fields as $fname => &$field) { $randToggle = rand(0, 9) < 5; if ($field[CONS_XML_TIPO] == CONS_TIPO_LINK && $ignoreParents) { // do not add, we will add first fields which do not need parent $dataToAdd = array(); $ignoreMe = true; continue; } if ((!isset($field[CONS_XML_MANDATORY]) || $field[CONS_XML_MANDATORY] === false) && $randToggle) { continue; } // do not add this optional switch ($field[CONS_XML_TIPO]) { case CONS_TIPO_DATE: $dataToAdd[$fname] = date("Y-m-d"); break; case CONS_TIPO_DATETIME: $dataToAdd[$fname] = date("Y-m-d H:m:s"); break; case CONS_TIPO_ENUM: preg_match("@ENUM \\(([^)]*)\\).*@", $field[CONS_XML_SQL], $regs); $enums = explode(",", $regs[1]); $randAdd = rand(0, count($enums) - 1); $dataToAdd[$fname] = $enums[$randAdd]; break; case CONS_TIPO_FLOAT: $dataToAdd[$fname] = rand(0, 100) / 10; break; case CONS_TIPO_INT: $dataToAdd[$fname] = rand(0, 100); break; case CONS_TIPO_LINK: $hasParent = true; $rmodule = $this->parent->loaded($field[CONS_XML_MODULE]); # TODO: this won't work for multikeys $dataToAdd[$fname] = $this->parent->dbo->fetch("SELECT " . $rmodule->keys[0] . " FROM " . $rmodule->dbname . " ORDER BY RAND() LIMIT 1"); break; case CONS_TIPO_OPTIONS: $dataToAdd[$fname] = ""; for ($c = 0; $c < 20; $c++) { $dataToAdd[$fname] .= "" . rand(0, 1); } break; case CONS_TIPO_TEXT: if (isset($field[CONS_XML_CUSTOM])) { $dataToAdd[$fname] = ""; } else { if (!isset($field[CONS_XML_HTML]) || $field[CONS_XML_HTML] === false) { $dataToAdd[$fname] = stripHTML($this->lorem); } else { $dataToAdd[$fname] = $this->lorem; } } break; case CONS_TIPO_VC: if (isset($field[CONS_XML_SPECIAL]) && $field[CONS_XML_SPECIAL] == "mail") { $dataToAdd[$fname] = "*****@*****.**"; } else { $dataToAdd[$fname] = substr(stripHTML($this->lorem), rand(0, 100), rand(0, 100)); } break; case CONS_TIPO_UPLOAD: $randAdd = rand(0, count($files) - 1); $_FILES[$fname] = array('error' => 0, 'tmp_name' => CONS_PATH_SYSTEM . "plugins/bi_dev/payload/" . $files[$randAdd], 'virtual' => true, 'name' => $files[$randAdd]); $dataToAdd[$fname] = 'y'; break; } // switch } // foreach field if (!$ignoreParents && !$hasParent) { continue; } // already added if (!$ignoreMe && count($dataToAdd) > 0) { if ($module->runAction(CONS_ACTION_INCLUDE, $dataToAdd, true, false)) { $added++; } } } // for i } // not system } // foreach module if ($ignoreParents) { $added += $this->fill(false); } // now add the one which need links return $added; }
function MT_Cover_getRecentEntries($parameters) { global $skin; $context = Model_Context::getInstance(); $data = $context->getProperty('plugin.config'); importlib("model.blog.entry"); importlib("model.blog.tag"); $data['coverMode'] = !isset($data['coverMode']) ? 1 : $data['coverMode']; if (Utils_Misc::isMetaBlog() != true) { $data['coverMode'] = 1; } $data['screenshot'] = !isset($data['screenshot']) ? 1 : $data['screenshot']; $data['screenshotSize'] = !isset($data['screenshotSize']) ? 90 : $data['screenshotSize']; $data['paging'] = !isset($data['paging']) ? '2' : $data['paging']; $data['contentLength'] = !isset($data['contentLength']) ? 250 : $data['contentLength']; if (isset($parameters['preview'])) { // preview mode $retval = '표지에 최신 글 목록을 추가합니다.'; return htmlspecialchars($retval); } $entryLength = isset($parameters['entryLength']) ? $parameters['entryLength'] : 10; if (!is_dir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail")) { @mkdir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail"); @chmod(__TEXTCUBE_CACHE_DIR__ . "/thumbnail", 0777); } if (!is_dir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . $context->getProperty('blog.id'))) { @mkdir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . $context->getProperty('blog.id')); @chmod(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . $context->getProperty('blog.id'), 0777); } if (!is_dir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . $context->getProperty('blog.id') . "/coverPostThumbnail/")) { @mkdir(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . $context->getProperty('blog.id') . "/coverPostThumbnail/"); @chmod(__TEXTCUBE_CACHE_DIR__ . "/thumbnail/" . $context->getProperty('blog.id') . "/coverPostThumbnail/", 0777); } $page = $data['paging'] == '1' && !empty($_GET['page']) ? intval($_GET['page']) : 1; $cache = new PageCache(); $cache->name = 'MT_Cover_RecentPS'; if ($cache->load()) { //If successful loads $cache->contents = unserialize($cache->contents); // If coverpage is single mode OR coverpage is coverblog and cache is not expired, return cache contents. if (($data['coverMode'] == 1 || $data['coverMode'] == 2) && array_key_exists($page, $cache->contents) && Timestamp::getUNIXtime() - $cache->dbContents < 300) { return $cache->contents[$page]; } } $pool = DBModel::getInstance(); $pool->reset("BlogSettings"); $pool->setQualifier("name", "eq", 'visibility', true); $pool->setQualifier("value", "<", 2); $privateBlogId = $pool->getCell("blogid"); $pool->reset("Entries"); $pool->join("Categories", "left", array(array("e.blogid", "eq", "c.blogid"), array("e.category", "eq", "c.id"))); $pool->setQualifier("e.draft", "eq", 0); $pool->setQualifier("e.category", "beq", 0); if ($privateBlogId) { $pool->setQualifier("e.blogid", "hasnoneof", $privateBlogId); } if (Utils_Misc::isMetaBlog() == true && doesHaveOwnership() && $context->getProperty('service.type', 'single') != 'single') { $pool->setQualifier("e.visibility", ">", 1); $pool->setQualifierSet(array("c.visibility", ">", 1), "OR", array("e.category", "eq", 0)); } else { if (!doesHaveOwnership()) { $pool->setQualifier("e.visibility", ">", 1); $pool->setQualifierSet(array("c.visibility", ">", 1), "OR", array("e.category", "eq", 0)); } } if ($data['coverMode'] != 2) { $pool->setQualifier("e.blogid", "eq", $context->getProperty("blog.id")); } list($entries, $paging) = Paging::fetch($pool, $page, $entryLength); $html = ''; foreach ((array) $entries as $entry) { $tagLabelView = ""; $blogid = $data['coverMode'] == 2 ? $entry['blogid'] : $context->getProperty('blog.id'); $entryTags = getTags($blogid, $entry['id']); $defaultURL = getDefaultURL($blogid); if (sizeof($entryTags) > 0) { $tags = array(); foreach ($entryTags as $entryTag) { $tags[$entryTag['name']] = "<a href=\"{$defaultURL}/tag/" . (Setting::getBlogSettingGlobal('useSloganOnTag', true) ? URL::encode($entryTag['name'], $service['useEncodedURL']) : $entryTag['id']) . '">' . htmlspecialchars($entryTag['name']) . '</a>'; } $tagLabelView = "<div class=\"post_tags\"><span>TAG : </span>" . implode(",\r\n", array_values($tags)) . "</div>"; } if (empty($entry['category'])) { $entry['label'] = _text('분류없음'); $entry['link'] = "{$defaultURL}/category"; } else { $entry['link'] = "{$defaultURL}/category/" . (Setting::getBlogSettingGlobal('useSloganOnCategory', true) ? URL::encode($entry['label'], $service['useEncodedURL']) : $entry['category']); } $permalink = "{$defaultURL}/" . (Setting::getBlogSettingGlobal('useSloganOnPost', true) ? "entry/" . URL::encode($entry['slogan'], $context->getProperty('service.useEncodedURL', false)) : $entry['id']); $html .= '<div class="coverpost">' . CRLF; if ($imageName = MT_Cover_getAttachmentExtract($entry['content'])) { if (($tempImageSrc = MT_Cover_getImageResizer($blogid, $imageName, $data['screenshotSize'])) && $data['screenshot'] == 1) { $html .= '<div class="img_preview"><a href="' . $permalink . '"><img src="' . $tempImageSrc . '" alt="" /></a></div>' . CRLF; } } $html .= ' <div class="content_box">'; $html .= ' <h2><a href="' . $permalink . '">' . htmlspecialchars($entry['title']) . '</a></h2>' . CRLF; $html .= ' <div class="post_info">' . CRLF; $html .= ' <span class="category"><a href="' . htmlspecialchars($entry['link']) . '">' . htmlspecialchars($entry['label']) . '</a></span>' . CRLF; $html .= ' <span class="date">' . Timestamp::format5($entry['published']) . '</span>' . CRLF; $html .= ' <span class="author"><span class="preposition">by </span>' . User::getName($entry['userid']) . '</span>' . CRLF; $html .= ' </div>' . CRLF; $html .= ' <div class="post_content">' . htmlspecialchars(Utils_Unicode::lessenAsEm(removeAllTags(stripHTML($entry['content'])), $data['contentLength'])) . '</div>' . CRLF; $html .= $tagLabelView; $html .= ' <div class="clear"></div>' . CRLF; $html .= ' </div>'; $html .= '</div>' . CRLF; } if ($data['paging'] == '1') { $paging['page'] = $page; $paging['total'] = POD::queryCell("SELECT COUNT(*) FROM {$database['prefix']}Entries e WHERE {$multiple} e.draft = 0 {$visibility} AND e.category >= 0"); $html .= Paging::getPagingView($paging, $skin->paging, $skin->pagingItem) . CRLF; $html .= '<script type="text/javascript">' . CRLF; $html .= '//<![CDATA[' . CRLF; if ($paging['page'] > 1) { $html .= 'var prevURL = "' . $paging['url'] . '?page=' . ($paging['page'] - 1) . '"' . CRLF; } if ($paging['page'] < $paging['total']) { $html .= 'var nextURL = "' . $paging['url'] . '?page=' . ($paging['page'] + 1) . '"' . CRLF; } $html .= '//]]>' . CRLF; $html .= '</script>'; } $target = $html; $cache->contents[$page] = $target; $cache->contents = serialize($cache->contents); $cache->dbContents = Timestamp::getUNIXtime(); $cache->update(); unset($cache); return $target; }
if ($handle) { $count = 0; /////////////////////// // loop through line by line, and do any text processing required while (($line = fgets($handle, 4096)) !== false) { $exploded_tab_array = explode("\t", trim($line)); //echo "<pre>"; //var_dump($exploded_tab_array); //echo '</pre><br>'; //assign some reference variables $link = $exploded_tab_array[0]; $condition = $exploded_tab_array[1]; $brand = $exploded_tab_array[2]; $title = stripHTML($exploded_tab_array[3]); $title = str_replace(',', '', $title); $description = stripHTML($exploded_tab_array[4]); $description = str_replace(',', '', $description); $image_link = $exploded_tab_array[5]; $product_type = $exploded_tab_array[6]; $google_product_category = $exploded_tab_array[7]; //str_replace($SE_categories, $Google_categories, $product_type); $price = $exploded_tab_array[8]; $availability = $exploded_tab_array[9]; $expiration_date = $exploded_tab_array[10]; $itemid = $exploded_tab_array[11]; $mpn = $exploded_tab_array[12]; $gtin = $exploded_tab_array[13]; $color = $exploded_tab_array[14]; $size = $exploded_tab_array[15]; $shipping_weight = $exploded_tab_array[16]; $shipping = '';
function getOrderStatus($vars, $responsetype) { global $db; $ar = safetycheck($vars, $responsetype); if (!isset($ar) || !$ar['InternalID'] > 0) { RestLog("16587 - Insufficient data provided for creating order \n" . print_r($vars, true) . "\n"); RestUtils::sendResponse(400, "16587 - Insufficient data provided"); //Internal Server Error return false; } //08.26.2015 ghh - to insure a dealer can't get a status on another dealers //orders we need to make sure we include their internal id plus their dealerid $query = "select * from PurchaseOrders where POID={$ar['InternalID']} and\n\t\t\t\tDealerID={$ar['DealerID']}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16588 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16588 - There was a problem locating the order"); //Internal Server Error return false; } //08.26.2015 ghh - if no order was found then return if ($db->sql_numrows($result) == 0) { RestLog("Error 16589 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16589 - There was a problem locating the order"); //Internal Server Error return false; } //08.26.2015 ghh - now we grab what we need from the PO in order to return it //to the caller $row = $db->sql_fetchrow($result); $rst['InternalID'] = $row['POID']; $rst['PONumber'] = $row['PONumber']; $rst['Discount'] = $row['Discount']; $rst['ExpectedDelivery'] = $row['ExpectedDeliveryDate']; $rst['PayByDiscAmt'] = $row['PaybyDiscountAmount']; $rst['PayByDiscPercent'] = $row['PaybyDiscountPercent']; $rst['PayByDiscDate'] = $row['PaybyDiscountDate']; $rst['Status'] = $row['Status']; //08.26.2015 ghh - now we're going to start grabbing shipping information $query = "select distinct( BoxID )\n\t\t\tfrom PurchaseOrderItems a, PurchaseOrderShipped b \n\t\t\twhere b.POItemID=a.POItemID and a.POID={$ar['InternalID']}"; if (!($result = $db->sql_query($query))) { RestLog("Error 16590 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16590 - There was a problem locating the order"); //Internal Server Error return false; } //now we loop through our boxes and grab related items $i = 0; while ($row = $db->sql_fetchrow($result)) { //as we loop through each item, we need to gra $query = "select a.POItemID, a.BoxID, a.QtyShipped, a.Cost, b.ItemNumber, \n\t\t\t\t\tb.VendorID, b.Quantity, b.SupersessionID, b.CrossreferenceID,\n\t\t\t\t\tc.WarehouseID, c.TrackingNumber, c.VendorInvoiceNumber,\n\t\t\t\t\tc.DueDate, c.ShipVendorID, c.ShipDate, c.ShipCost, c.BoxNumber\n\t\t\t\t\tfrom PurchaseOrderShipped a, PurchaseOrderItems b, ShippedBoxes c\n\t\t\t\t\twhere a.POItemID=b.POItemID and b.POID={$ar['InternalID']} and\n\t\t\t\t\ta.BoxID={$row['BoxID']} order by BoxID, ItemNumber"; if (!($boxresult = $db->sql_query($query))) { RestLog("Error 16591 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16591 - There was a problem getting list of shipped boxes"); //Internal Server Error return false; } //now loop through boxes and their items and lets build up our box //array $shipvendorid = 0; $boxid = 0; $j = 0; $items = array(); while ($boxrow = $db->sql_fetchrow($boxresult)) { //08.26.2015 ghh - we only enter the main box section when //we actually change boxes since we don't want to repeat this if ($boxid != $boxrow['BoxID']) { $boxid = $boxrow['BoxID']; $box[$i]['BoxNumber'] = $boxrow['BoxNumber']; $box[$i]['ShipVendor'] = getShipVendorName($boxrow['ShipVendorID']); $box[$i]['ShipVendor'] = $shippingvendor; $box[$i]['TrackingNumber'] = $boxrow['TrackingNumber']; $box[$i]['VendorInvoice'] = $boxrow['VendorInvoice']; $box[$i]['DueDate'] = $boxrow['DueDate']; $box[$i]['ShipCost'] = $boxrow['ShipCost']; $box[$i]['ShipDate'] = $boxrow['ShipDate']; } //now we build up our list of items $items[$j]['VendorID'] = $boxrow['VendorID']; $items[$j]['ItemNumber'] = $boxrow['ItemNumber']; $items[$j]['QtyShipped'] = $boxrow['QtyShipped']; $items[$j]['Cost'] = $boxrow['Cost']; //this deals with supersession data and would only be supplied if the supplier //elected to ship the super part instead of the original one ordered. if ($boxrow['SupersessionID'] > 0) { $query = "select ItemNumber from Items where ItemID={$boxrow['SupersessionID']}"; if (!($superresult = $db->sql_query($query))) { RestLog("Error 16597 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16597 - There was a problem getting supersession number"); //Internal Server Error return false; } $superrow = $db->sql_fetchrow($superresult); $items[$j]['SuppersessionNumber'] = $superrow['ItemNumber']; } //this grabs crossreference information if it was entered and would only be //entered if the supplier elected to ship a different vendors part than what //was ordered if ($boxrow['CrossReferenceID'] > 0) { $query = "select ItemNumber, VendorID from Items \n\t\t\t\t\t\t\twhere ItemID={$boxrow['CrossreferenceID']}"; if (!($crossresult = $db->sql_query($query))) { RestLog("Error 16598 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16598 - There was a problem getting supersession number"); //Internal Server Error return false; } $crossrow = $db->sql_fetchrow($crossresult); $items[$j]['CrossRefNumber'] = $crossrow['ItemNumber']; $items[$j]['CrossRefVendorID'] = $crossrow['VendorID']; } $j++; } //08.26.2015 ghh - now we need to save our items into our box $box[$i]['Items'] = $items; $i++; } //now that we're done looping through boxes we need to save them as part of the return //array $rst['Boxes'] = $box; ##########################################UNITS############################################################### //now we're going to grab a list of units that may have been shipped so we can send that //information back as well. $query = "select * from PurchaseOrderUnits where POID={$ar['InternalID']} and\n\t\t\t\tShipDate is not null"; if (!($result = $db->sql_query($query))) { RestLog("Error 16599 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16599 - There was a problem getting supersession number"); //Internal Server Error return false; } $i = 0; while ($row = $db->sql_fetchrow($result)) { $units[$i]['VendorID'] = $row['VendorID']; $units[$i]['ModelNumber'] = $row['ModelNumber']; //need to lookup up ship vendor name to send back $units[$i]['ShipVendor'] = getShipVendorName($row['ShipVendorID']); $units[$i]['TrackingNumber'] = $row['TrackingNumber']; $units[$i]['OrderCode'] = $row['OrderCode']; $units[$i]['Year'] = $row['Year']; $units[$i]['Colors'] = $row['Colors']; $units[$i]['Details'] = $row['Details']; $units[$i]['Serial-VIN'] = $row['SerialVIN']; $units[$i]['Cost'] = $row['Cost']; $units[$i]['ShipCharge'] = $row['ShipCharge']; $units[$i]['ShipDate'] = $row['ShipDate']; $units[$i]['EstShipDate'] = $row['EstShipDate']; $i++; } $rst['Units'] = $units; ###############################BACKORDERS############################## //lastly we're going to go grab the list of backorders that might exist so that we //can return them as well. $query = "select b.*, a.ItemNumber, a.VendorID\n\t\t\t\tfrom PurchaseOrderItems a, PurchaseOrderBackOrder b\n\t\t\t\twhere a.POID={$ar['InternalID']} and\n\t\t\t\ta.POItemID=b.POItemID"; if (!($result = $db->sql_query($query))) { RestLog("Error 16602 in query: {$query}\n" . $db->sql_error()); RestUtils::sendResponse(500, "16602 - There was a problem getting backorder information"); //Internal Server Error return false; } $i = 0; while ($row = $db->sql_fetchrow($result)) { $back[$i]['ItemNumber'] = $row['ItemID']; $back[$i]['VendorID'] = $row['VendorID']; $back[$i]['QtyPending'] = $row['QtyPending']; $back[$i]['EstShipDate'] = $row['EstShipDate']; $back[$i]['ShipNote'] = $row['ShipNote']; $i++; } $rst['Backorders'] = $back; RestLog("Successful Request\n"); RestUtils::sendResponse(200, json_encode(stripHTML($rst))); return true; }
function FM_default_summary($blogid, $id, $content, $keywords = array(), $useAbsolutePath = false) { $context = Model_Context::getInstance(); if (!$context->getProperty('blog.publishWholeOnRSS')) { $content = Utils_Unicode::lessen(removeAllTags(stripHTML($content)), 255); } return $content; }
/** * defaultStripOutput : default ouput strip function */ function defaultStripOutput($text) { if ($text !== '') { // replace line breaking tags with whitespace $text = stripLineBreaking($text); // strip modx sensitive tags $text = stripTags($text); // strip Jscripts $text = stripJscripts($text); // strip html tags. Tags should be correctly ended $text = stripHTML($text); } return $text; }