summaryrefslogtreecommitdiff
path: root/app/Libraries/Helper.php
blob: 81648877f29e0bc6ce43d6d29163a0d73f6cb839 (plain)
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
<?php
namespace App\Libraries;
use App\Libraries\Helper;
use Carbon\Carbon;

class Helper {
	public static function escapeLike($string){
		$search = array('%', '_');
		$replace   = array('\%', '\_');
		$string = str_replace($search, $replace, $string);
		$string = explode(" ", $string);
		return implode("%", $string);
	}

	public static function formatTimestamp($timestamp) {
		return Carbon::createFromTimestamp($timestamp)->format("Y-m-d");
	}

	public static function makeFeed($model, $title, $cache = 60) {

	    switch($title) {
	    case("new"):
		    $feed_title = 'Newest Articles';
		    $feed_description = 'Newest interesting articles from Wikipedia. Keep exploring.';
		    break;
	    case( "popular"):
		    $feed_title = 'Popular Articles';
		    $feed_description = 'The most popular articles. Keep exploring.';
		    break;
	    case( "mastodon"):
		    $feed_title = 'Feed for Mastodon';
		    $feed_description = 'New articles are published automatically to Mastodon.';
		    break;
	    default:
		    $feed_title = 'Search for: ' . $title;
		    $feed_description = 'All articles for "' . $title . '".';
		    break;
	    }
	    // create new feed
	    $feed = \App::make("feed");

	    // multiple feeds are supported
	    // if you are using caching you should set different cache keys for your feeds

	    // cache the feed for $cache minutes (second parameter is optional)
	    $feed->setCache($cache, 'feed_' . $title);

	    // check if there is cached feed and build new only if is not
	    if (!$feed->isCached())
	    {

	       // set your feed's title, description, link, pubdate and language
	       $feed->title = $feed_title;
	       $feed->description = $feed_description;
	       #$feed->logo = 'http://yoursite.tld/logo.jpg';
	       $feed->link = url('feed/' . $title);
	       $feed->setDateFormat('datetime'); // 'datetime', 'timestamp' or 'carbon'
	       $feed->pubdate = $model[0]->created_at;
	       $feed->lang = 'en';
	       $feed->setShortening(false); // true or false

	       if ( "mastodon" == $title || "mastodon_test" == $title ) {
		       $feed->setTextLimit(500); // maximum length of description text
	       } else {
		       $feed->setTextLimit(100); // maximum length of description text
	       }

	       foreach ($model as $post)
	       {

		       $desc = ($post->excerpt_html);
		       $categories = null;

		       if ( "mastodon" == $title || "mastodon_test" == $title ) {

			       $cat_len= 0;

			       if ( ! $post->getCategories()->get()->isEmpty()  ) {

				       $categories_ar = array("#MostDiscussed");

				       foreach( $post->getCategories()->get() as $cat ) {

					       // uppercase for every word in a possible multi worded hashtag
					       $tmp_cat = ucwords($cat->name);

					       // strip everything after / for brevity
					       if ( false !== strpos($tmp_cat, "/") )
						       $tmp_cat = substr($tmp_cat, 0, strpos($tmp_cat, "/"));

					       // replace any non-alphanumeric character except underscore, because
					       // it's not allowed to be used in a hashtag
					       $tmp_cat = preg_replace("/[^A-Za-z0-9_]/", '', $tmp_cat);

					       // trim just in case
					       $tmp_cat = trim($tmp_cat);

					       // if it's not empty, add it to the hashtag array
					       if ( "" != $tmp_cat )
						       $categories_ar[] = "#". $tmp_cat;
				       }

				       // remove possible duplicates (because stripping after "/")
				       $categories_ar = array_unique($categories_ar);

				       // join to one string
				       $categories = implode(" ", $categories_ar);

				       $cat_counter = $post->getCategories()->get()->count();
				       $cat_len = mb_strlen($categories, "UTF-8");
			       }
			       
			       $link = env('APP_URL') . "/article/" . $post->id;

			       // max desc length is 500 - 23 (Link) - $cat_len - 2 (white spaces)
			       $max_len = 500 - 23 - $cat_len - 2;

				if ( "mastodon_test" == $title ) {
				       $desc = Helper::mastodon_summary($desc, $max_len);
				}else {
				       $desc = Helper::first_sentence($desc, $max_len);
				       #$desc = Helper::mastodon_summary($desc, $max_len);
				}

			       $desc .= " " . $categories;# . $discussions;

			       // set item's title, author, url, pubdate, description, content, enclosure (optional)*
			       $feed->addItem([
					'title' => $desc, // mastofeed.org seems to ignore the description field
					'author' => env('APP_NAME'),
					'url' => $link,
					'link' => $link,
					'pubdate' => $post->created_at,
					'description' => $desc,
					'content' => $desc
			       ]);

		       } else {
			       if ( ! $post->getCategories()->get()->isEmpty()  ) {
				       $categories = "<br>";
				       foreach( $post->getCategories()->get() as $cat ) {
					       $categories .= "<a href='". \URL::to('/topic/' . $cat->name) ."'>". $cat->name . "</a> | ";
				       }
				       $categories = rtrim($categories, " | ");
				       $desc .= "<br>Topics:";
				       $desc .= $categories;
			       }

			       $discussions = "<br>";
			       foreach( $post->getDiscussions()->orderBy('comments', 'desc')->get() as $dis ) {
				       $discussions .= "<a href='" . $dis->source_url . "'>" . $dis->title . "</a> ";
				       $discussions .= $dis->upvotes . " Upvotes | " . $dis->comments . " Comments<br>";
			       }
			       $desc .= "<br><br>Discussions:";
			       $desc .= $discussions;

			   // set item's title, author, url, pubdate, description, content, enclosure (optional)*
			       $feed->addItem([
					'title' => $post->title,
					'author' => env('APP_NAME'),
					'url' => \URL::to($post->url),
					'link' => \URL::to($post->url),
					'pubdate' => $post->created_at,
					'description' => $desc,
					'content' => $desc
			       ]);
		       }
	       }

	    }

	    // first param is the feed format
	    // optional: second param is cache duration (value of 0 turns off caching)
	    // optional: you can set custom cache key with 3rd param as string
	    return $feed->render('atom', $cache, 'feed_' . $title);
	}

	public static function first_sentence($content, $max_len = NULL) {

		$content = html_entity_decode(strip_tags($content));
		$content = ltrim($content);
		$pos = strpos($content, '.');

		if($pos === false) {
			if ( is_null($max_len) ) {
				return $content;
			} else {
				return substr($content, 0, $max_len);
			}
		}
		else {
			return substr($content, 0, $pos+1);
		}

	}

	private static function next_sentence($content, $max_len = NULL) {

		$content = ltrim($content);
		$pos = strpos($content, '.');

		if($pos === false) {
			if ( is_null($max_len) ) {
				return $content;
			} else {
				return substr($content, 0, $max_len);
			}
		} else {
			return substr($content, 0, $pos+1);
		}

	}

	/**
	 * Make sure to toot as much text as possible while still staying below the limit of 500 chars -link (23 chars) - 2 (white spaces) - possible hashtags
	 */
	public static function mastodon_summary($excerpt, $max_len = 475){

		/**
		 * Strip HTML from Wikipedia excerpt
		 */
		$excerpt = ltrim(html_entity_decode(strip_tags($excerpt)));

		/**
		 * The toot to be returned
		 */
		$content = "";

		/**
		 * https://stackoverflow.com/questions/16377437/split-a-text-into-sentences
		 */
		$sentences = preg_split('/(?<=[.?!])\s+(?=[a-z])/i', $excerpt);
		echo "<pre>";
		echo "-----------------------";
		var_dump($excerpt);
		var_dump($sentences);

		for ( $i = 0; $i < count($sentences); $i++ ) {
			#if ( mb_strlen($content) < $max_len && (mb_strlen($content) + mb_strlen($sentences) ) {
			if ( mb_strlen($content) < $max_len && (mb_strlen($content) + mb_strlen($sentences) ) < $max_len ){

				//var_dump(rtrim(ltrim($sentences[$i])));
				$content .= rtrim(ltrim($sentences[$i]));
				var_dump("ok", $max_len);

				$max_len = $max_len - mb_strlen($sentences[$i]);
				var_dump("ok", $max_len);

			} else {
				var_dump("fail", mb_strlen($content), $max_len);
				break;
			}
		}
		return $content;

		echo "<pre>";
		while ( mb_strlen($content) < $max_len ) {

			/**
			 * Get next sentence
			 */
			$next_sentence = Helper::next_sentence($excerpt, $max_len);
			var_dump($next_sentence);

			if ( "" == $next_sentence ) {
				break;
			}

			/**
			 * Check if $content + $next_sentence is still under $max_len
			 */
			if ( (mb_strlen($content) + mb_strlen($next_sentence)) < $max_len ) {

				/**
				 * add text
				 */
				$content .= $next_sentence;

				/**
				 * Recalc $max_len
				 */
				$max_len = $max_len - mb_strlen($next_sentence);

				/**
				 * Remove sentence from excerpt
				 */
				$excerpt = substr($excerpt, mb_strlen($next_sentence));

			} else {
				break;
			}
		}

		return $content;
	}
}