forked from silverstripe/silverstripe-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBText.php
260 lines (226 loc) · 7.86 KB
/
DBText.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php
namespace SilverStripe\ORM\FieldType;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\NullableField;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\DB;
use InvalidArgumentException;
/**
* Represents a variable-length string of up to 16 megabytes, designed to store raw text
*
* Example definition via {@link DataObject::$db}:
* <code>
* static $db = array(
* "MyDescription" => "Text",
* );
* </code>
*
* @see DBHTMLText
* @see DBHTMLVarchar
* @see Varchar
*/
class DBText extends DBString
{
private static $casting = array(
"BigSummary" => "Text",
"ContextSummary" => "HTMLFragment", // Always returns HTML as it contains formatting and highlighting
"FirstParagraph" => "Text",
"FirstSentence" => "Text",
"LimitSentences" => "Text",
"Summary" => "Text",
);
/**
* (non-PHPdoc)
* @see DBField::requireField()
*/
public function requireField()
{
$charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset');
$collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation');
$parts = [
'datatype' => 'mediumtext',
'character set' => $charset,
'collate' => $collation,
'default' => $this->defaultVal,
'arrayValue' => $this->arrayValue
];
$values = [
'type' => 'text',
'parts' => $parts
];
DB::require_field($this->tableName, $this->name, $values);
}
/**
* Limit sentences, can be controlled by passing an integer.
*
* @param int $maxSentences The amount of sentences you want.
* @return string
*/
public function LimitSentences($maxSentences = 2)
{
if (!is_numeric($maxSentences)) {
throw new InvalidArgumentException("Text::LimitSentence() expects one numeric argument");
}
$value = $this->Plain();
if (!$value) {
return "";
}
// Do a word-search
$words = preg_split('/\s+/u', $value);
$sentences = 0;
foreach ($words as $i => $word) {
if (preg_match('/(!|\?|\.)$/', $word) && !preg_match('/(Dr|Mr|Mrs|Ms|Miss|Sr|Jr|No)\.$/i', $word)) {
$sentences++;
if ($sentences >= $maxSentences) {
return implode(' ', array_slice($words, 0, $i + 1));
}
}
}
// Failing to find the number of sentences requested, fallback to a logical default
if ($maxSentences > 1) {
return $value;
} else {
// If searching for a single sentence (and there are none) just do a text summary
return $this->Summary(20);
}
}
/**
* Return the first string that finishes with a period (.) in this text.
*
* @return string
*/
public function FirstSentence()
{
return $this->LimitSentences(1);
}
/**
* Builds a basic summary, up to a maximum number of words
*
* @param int $maxWords
* @param string $add
* @return string
*/
public function Summary($maxWords = 50, $add = '...')
{
// Get plain-text version
$value = $this->Plain();
if (!$value) {
return '';
}
// Split on sentences (don't remove period)
$sentences = array_filter(array_map(function ($str) {
return trim($str);
}, preg_split('@(?<=\.)@', $value)));
$wordCount = count(preg_split('#\s+#u', $sentences[0]));
// if the first sentence is too long, show only the first $maxWords words
if ($wordCount > $maxWords) {
return implode(' ', array_slice(explode(' ', $sentences[0]), 0, $maxWords)) . $add;
}
// add each sentence while there are enough words to do so
$result = '';
do {
// Add next sentence
$result .= ' ' . array_shift($sentences);
// If more sentences to process, count number of words
if ($sentences) {
$wordCount += count(preg_split('#\s+#u', $sentences[0]));
}
} while ($wordCount < $maxWords && $sentences && trim($sentences[0]));
return trim($result);
}
/**
* Get first paragraph
*
* @return string
*/
public function FirstParagraph()
{
$value = $this->Plain();
if (empty($value)) {
return '';
}
// Split paragraphs and return first
$paragraphs = preg_split('#\n{2,}#', $value);
return reset($paragraphs);
}
/**
* Perform context searching to give some context to searches, optionally
* highlighting the search term.
*
* @param int $characters Number of characters in the summary
* @param string $keywords Supplied string ("keywords"). Will fall back to 'Search' querystring arg.
* @param bool $highlight Add a highlight <mark> element around search query?
* @param string $prefix Prefix text
* @param string $suffix Suffix text
* @return string HTML string with context
*/
public function ContextSummary(
$characters = 500,
$keywords = null,
$highlight = true,
$prefix = "... ",
$suffix = "..."
) {
if (!$keywords) {
// Use the default "Search" request variable (from SearchForm)
$keywords = isset($_REQUEST['Search']) ? $_REQUEST['Search'] : '';
}
// Get raw text value, but XML encode it (as we'll be merging with HTML tags soon)
$text = nl2br(Convert::raw2xml($this->Plain()));
$keywords = Convert::raw2xml($keywords);
// Find the search string
$position = empty($keywords) ? 0 : (int) mb_stripos($text, $keywords);
// We want to search string to be in the middle of our block to give it some context
$position = max(0, $position - ($characters / 2));
if ($position > 0) {
// We don't want to start mid-word
$position = max(
(int) mb_strrpos(mb_substr($text, 0, $position), ' '),
(int) mb_strrpos(mb_substr($text, 0, $position), "\n")
);
}
$summary = mb_substr($text, $position, $characters);
$stringPieces = explode(' ', $keywords);
if ($highlight) {
// Add a span around all key words from the search term as well
if ($stringPieces) {
foreach ($stringPieces as $stringPiece) {
if (mb_strlen($stringPiece) > 2) {
// Maintain case of original string
$summary = preg_replace(
'/' . preg_quote($stringPiece, '/') . '/i',
'<mark>$0</mark>',
$summary
);
}
}
}
}
$summary = trim($summary);
// Add leading / trailing '...' if trimmed on either end
if ($position > 0) {
$summary = $prefix . $summary;
}
if (strlen($text) > ($characters + $position)) {
$summary = $summary . $suffix;
}
return $summary;
}
public function scaffoldFormField($title = null, $params = null)
{
if (!$this->nullifyEmpty) {
// Allow the user to select if it's null instead of automatically assuming empty string is
return new NullableField(new TextareaField($this->name, $title));
} else {
// Automatically determine null (empty string)
return new TextareaField($this->name, $title);
}
}
public function scaffoldSearchField($title = null)
{
return new TextField($this->name, $title);
}
}