-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.php
517 lines (441 loc) · 18.4 KB
/
helper.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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
<?php
/**
* @package Module B-Related Content
* @version $Id:
* @author Yair Lahav
* @copyright (C) 2014 - Yair Lahav
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
// no direct access
defined('_JEXEC') or die('Restricted access');
class modBRelatedContentHelper {
/**
* Picks $numberArticles related content random articles from the chosen categories.
* @return Array $rows On success returns an array with the random articles, otherwise returns -1
*/
public static function getArticles( &$params ) {
$jinput = JFactory::getApplication()->input;
// var_dump($jinput);
$option = $jinput->get("option", "", "data");
// echo "option = ", $option . "<br>";
// echo "itemId = ", $itemId . "<br>";
$items = json_decode(str_replace("|bb|", "\"", $params->get('relations')));
// Look for a mach...
$match = false;
foreach ($items as $item) {
switch($item->type) {
case 'article':
if ($option == 'com_content') {
$id = $jinput->get("id", "", "data");
$checkList = split(",", $item->ids);
foreach ($checkList as $checkId) {
if ($checkId == $id) {
$match = true;
}
}
}
break;
case 'category':
if ($option == 'com_content') {
$view = $jinput->get("view", "", "data");
$id = $jinput->get("id", "", "data");
if ($view == 'category') {
$checkList = split(",", $item->ids);
foreach ($checkList as $checkId) {
if ($checkId == $id) {
$match = true;
}
}
} elseif ($view == "article") {
// we need to convert the id to the category id
$cid = modBRelatedContentHelper::getCtegory($id);
if ($cid != -1) {
$checkList = split(",", $item->ids);
foreach ($checkList as $checkId) {
if ($checkId == $cid) {
$match = true;
}
}
}
}
}
break;
case 'menu':
$itemId = $jinput->get("Itemid", "", "data");
$checkList = split(",", $item->ids);
foreach ($checkList as $checkId) {
if ($checkId == $itemId) {
$match = true;
}
}
break;
case 'hikashop':
if ($option == 'com_hikashop') {
$cid = -1;
$ctrl = $jinput->get("ctrl", "", "data");
if ($ctrl == "category") {
$cid = $jinput->get("cid", "", "data");
} elseif ($ctrl == "product") {
$cid = $jinput->get("category_pathway", "", "data");
}
if ($cid != -1) {
$checkList = split(",", $item->ids);
foreach ($checkList as $checkId) {
if ($checkId == $cid) {
$match = true;
}
}
}
}
// $checkList = split(",", $item->ids);
// foreach ($checkList as $checkId) {
// if ($checkId == $itemId) {
// $match = true;
// }
// }
break;
default:
echo "unknown: " . $item->type;
}
if ($match) {
$params->set('category', split(",", $item->dids));
$params->set('numberArticles', $item->number);
break;
}
}
if (!$match) { // Use default value
$params->set('category', split(",", $params->get('defualtcategory')));
$params->set('numberArticles', $params->get('defualnumber'));
}
// Converts numberArticles to a number.
$numberArticles = intval($params->get('numberArticles'));
$numberArticlesK2 = intval($params->get('numberArticlesK2'));
if($numberArticles < 0 || $numberArticlesK2 < 0 || ($numberArticlesK2 <= 0 && $numberArticles <= 0))
return -3;
// Checks if there is any selected category.
if($numberArticles > 0 && count($params->get('category')) <= 0)
return -2;
if($numberArticlesK2 > 0 && count($params->get('categoryk2')) <= 0)
return -2;
if($params->get('category'))
$categories = implode(",", $params->get('category'));
if($params->get('categoryk2'))
$k2categories = implode(",", $params->get('categoryk2'));
if($params->get('excludeAccessLevel')) {
$excludeAccessLevel = implode(",", $params->get('excludeAccessLevel'));
if($excludeAccessLevel)
$queryExclude = "AND access not in (". $excludeAccessLevel . ") ";
}
else {
$queryExclude = "";
$excludeAccessLevel = "";
}
// Sets the timezone to match the Joomla configuration file
$app = JFactory::getApplication();
date_default_timezone_set ($app->getCfg('offset'));
if(count($params->get('category')) > 0) {
// The selected articles are published and have valid publish and unpublish dates
$query = "SELECT *, 'Joomla' as type ".
"FROM #__content ".
"WHERE catid in ";
// Selects articles from the subcategories.
if($params->get('subcategories'))
$query .= "( SELECT id FROM #__categories WHERE (parent_id in (".$categories.") OR id in (" .$categories .")) ".$queryExclude." )";
else
$query .= "( ".$categories." ) ";
$query .= "AND state = '1' ";
// Disables time restrictions and selects articles without checking if the dates are correct.
if(!$params->get('timerestrictions'))
$query .= "AND (publish_up <= '".date('Y-m-d H:i:s')."' OR publish_up = '0000-00-00 00:00:00') ".
"AND (publish_down >= '".date('Y-m-d H:i:s')."' OR publish_down = '0000-00-00 00:00:00') ";
$query .= $queryExclude;
$query .= "ORDER BY ".$params->get('ordering')." " .$params->get('orderDirection'). " ".
"LIMIT " . $numberArticles;
$db = JFactory::getDBO();
$db->setQuery($query);
$rows = $db->loadObjectList();
}
if($excludeAccessLevel) {
$queryExcludeCat = "AND c.access not in (". $excludeAccessLevel . ") ";
$queryExcludeItm = "AND i.access not in (". $excludeAccessLevel . ") ";
}
else {
$queryExcludeCat = "";
$queryExcludeItm = "";
}
if($params->get('categoryk2') && count($params->get('categoryk2')) > 0) {
// The selected articles are published and have valid publish and unpublish dates
$query = "SELECT i.*, 'K2' as type, c.alias as categoryalias ".
"FROM #__k2_items as i ".
"LEFT JOIN #__k2_categories c ON c.id = i.catid ".
"WHERE catid in ";
// Selects articles from the subcategories.
if($params->get('subcategoriesk2'))
$query .= "( SELECT id FROM #__k2_categories WHERE (parent in (".$k2categories.") OR id in (" .$k2categories .")) ".$queryExcludeCat." ) ";
else
$query .= "( ".$k2categories." ) ";
$query .= "AND i.published = '1' ";
// Disables time restrictions and selects articles without checking if the dates are correct.
if(!$params->get('timerestrictions'))
$query .= "AND (i.publish_up <= '".date('Y-m-d H:i:s')."' OR i.publish_up = '0000-00-00 00:00:00') ".
"AND (i.publish_down >= '".date('Y-m-d H:i:s')."' OR i.publish_down = '0000-00-00 00:00:00') ";
$query .= $queryExcludeItm;
if($params->get('ordering') == "rand()")
$ordering = $params->get('ordering');
else
$ordering = "i." . $params->get('ordering');
$query .= "ORDER BY ".$ordering." " .$params->get('orderDirection')." ".
"LIMIT " . $numberArticlesK2;
$db = JFactory::getDBO();
$db->setQuery($query);
$k2rows = $db->loadObjectList();
}
if(!isset($rows) && count($k2rows) > 0)
return $k2rows;
else
if(!isset($k2rows) && count($rows) > 0)
return $rows;
if(count($rows) > 0 && count($k2rows) > 0)
return array_merge($rows, $k2rows);
else
return 0;
}
/**
* Gets the correct URL for a given $article.
* @return String $url The URL to the $article
*/
public static function getUrl( &$article, $addCurrentID, $useContentCatRouter) {
$id = $article->id;
if($article->type == 'Joomla') {
$link = "index.php?option=com_content&view=article&id=".$id;
if($addCurrentID) {
// Adds the Itemid of the active menu item.
$app = JFactory::getApplication();
$menu = $app->getMenu();
$activeItemid = $menu->getActive()->id;
$url = $link . "&Itemid=" . $activeItemid;
}
else {
// Checks if there is a menu item linked to $article and applies its ItemID to the URL.
$query = "SELECT * FROM #__menu WHERE link = '". $link ."'";
$db = JFactory::getDBO();
$db->setQuery($query);
$rows = $db->loadObject();
if(isset($rows))
$url = $link . "&Itemid=" .$rows->id;
else {
// There is no menu item linked to $article. Checks if needs to use com_content > category > router
if($useContentCatRouter) {
// Fix for Menu Item "Articles > Category Blog"
$app = JFactory::getApplication();
$menu = $app->getMenu();
$activeMenuItem = $menu->getActive();
// components/com_content/views/category/view.html.php
require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
$slug = $article->alias ? ($article->id . ':' . $article->alias) : $article->id;
$url = JRoute::_(ContentHelperRoute::getArticleRoute($slug, $article->catid));
}
else
$url = $link;
}
}
return $url;
}
// Possible bug here. This $link may need the &Itemid to work properly
elseif($article->type == 'K2') {
// Copied from mod_k2_content - helper.php - readmode link
require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');
$link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($article->id.':'.urlencode($article->alias), $article->catid.':'.urlencode($article->categoryalias))));
return $link;
}
}
/**
* Counts the number of characters in a String with HTML tags, ignoring the HTML tags.
*
* Thanks to Søren Løvborg for sharing this solution here: http://stackoverflow.com/a/1193598/1687176
*
* @param $maxLength The lenght of the substring
* @param $html The String to be cutted
* @return String $str A substring of $html that still is a valid HTML String
*/
public static function substr_HTML($maxLength, $html, $isUtf8=true) {
$printedLength = 0;
$position = 0;
$tags = array();
$resultStr = "";
// For UTF-8, we need to count multibyte sequences as one character.
$re = $isUtf8
? '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;|[\x80-\xFF][\x80-\xBF]*}'
: '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}';
while ($printedLength < $maxLength && preg_match($re, $html, $match, PREG_OFFSET_CAPTURE, $position)) {
list($tag, $tagPosition) = $match[0];
// Print text leading up to the tag.
$str = substr($html, $position, $tagPosition - $position);
if ($printedLength + strlen($str) > $maxLength) {
$resultStr = $resultStr . substr($str, 0, $maxLength - $printedLength);
$printedLength = $maxLength;
break;
}
$resultStr = $resultStr . $str;
$printedLength += strlen($str);
if ($printedLength >= $maxLength) break;
if ($tag[0] == '&' || ord($tag) >= 0x80) {
// Pass the entity or UTF-8 multibyte sequence through unchanged.
$resultStr = $resultStr . $tag;
$printedLength++;
}
else {
// Handle the tag.
$tagName = $match[1][0];
if ($tag[1] == '/') {
// This is a closing tag.
$openingTag = array_pop($tags);
assert($openingTag == $tagName); // check that tags are properly nested.
$resultStr = $resultStr . $tag;
}
else if ($tag[strlen($tag) - 2] == '/') {
// Self-closing tag.
$resultStr = $resultStr . $tag;
}
else {
// Opening tag.
$resultStr = $resultStr . $tag;
$tags[] = $tagName;
}
}
// Continue after the tag.
$position = $tagPosition + strlen($tag);
}
// Print any remaining text.
if ($printedLength < $maxLength && $position < strlen($html))
$resultStr = $resultStr . substr($html, $position, $maxLength - $printedLength);
// Close any open tags.
while (!empty($tags)) {
//printf('</%s>', array_pop($tags));
$resultStr = $resultStr . "</" . array_pop($tags) . ">";
}
return $resultStr;
}
/**
* A handy function to get the position of nth occurance of a substring in a string
*
* Thanks for webKami for sharing this function
* http://www.webkami.com/programming/php/php-function-str-nth-pos/php-function-str-nth-pos-1-0-0.php
*/
public static function strposnth($haystack, $needle, $nth=1, $insenstive=0) {
//if its case insenstive, convert strings into lower case
if ($insenstive) {
$haystack=strtolower($haystack);
$needle=strtolower($needle);
}
//count number of occurances
$count=substr_count($haystack,$needle);
//first check if the needle exists in the haystack, return false if it does not
//also check if asked nth is within the count, return false if it doesnt
if ($count<1 || $nth > $count) return false;
//run a loop to nth number of accurance
//start $pos from -1, cause we are adding 1 into it while searchig
//so the very first iteration will be 0
for($i=0,$pos=0,$len=0;$i<$nth;$i++) {
//get the position of needle in haystack
//provide starting point 0 for first time ($pos=0, $len=0)
//provide starting point as position + length of needle for next time
$pos=strpos($haystack,$needle,$pos+$len);
//check the length of needle to specify in strpos
//do this only first time
if ($i==0) $len=strlen($needle);
}
//return the number
return $pos;
}
/**
* Writes a detailed log file to be used in bug report
* @param $opt the type of output to be logged: 1=settings 2=article 3=url 4=html
* @param $data the output to be logged
*/
public static function logThis($opt = 1, $data = "") {
$filename = "tmp".DS."mod_b_related_content-debuglogfile.txt";
$timestamp = "Timestamp: ".date('Y-m-d H:i:s') . "\n";
$log = "";
if($opt == 1)
$log = "LOG TYPE: MODULE SETTINGS\n" . $timestamp . $data . "\n\n";
elseif($opt == 2)
$log = "LOG TYPE: ARTICLE\n" . $data . "\n\n";
elseif($opt == 3)
$log = "LOG TYPE: URL\n" . $data . "\n\n";
// This might be useful later
elseif($opt == 4)
$log = "LOG TYPE: HTML\n" . $data . "\n\n";
elseif($opt == 5)
$log = "LOG TYPE: K2 IMAGE\n" . $data . "\n\n";
file_put_contents($filename, $log, FILE_APPEND | LOCK_EX);
chmod($filename, 0775);
}
/**
* Gets the path and filename of a K2 article
*
* This code was copied from mod_k2_content - helper.php - class modK2ContentHelper - function getItems()
* and adjusted to fit this module needs
*/
public static function getK2ArticleImage($item, $size) {
$componentParams = JComponentHelper::getParams('com_k2');
//Images
$date = JFactory::getDate($item->modified);
$timestamp = '?t='.$date->toUnix();
if($size == "XSmall") {
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XS.jpg')) {
$item->image = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_XS.jpg';
if ($componentParams->get('imageTimestamp'))
$item->image .= $timestamp;
}
}
elseif($size == "Small") {
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_S.jpg')) {
$item->image = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_S.jpg';
if ($componentParams->get('imageTimestamp'))
$item->image .= $timestamp;
}
}
elseif($size == "Medium") {
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_M.jpg')) {
$item->image = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_M.jpg';
if ($componentParams->get('imageTimestamp'))
$item->image .= $timestamp;
}
}
elseif($size == "Large") {
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_L.jpg')) {
$item->image = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_L.jpg';
if ($componentParams->get('imageTimestamp'))
$item->image .= $timestamp;
}
}
elseif($size == "XLarge") {
if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XL.jpg')) {
$item->image = JURI::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_XL.jpg';
if ($componentParams->get('imageTimestamp'))
$item->image .= $timestamp;
}
}
/*
if($params->get('logfile'))
$this->logThis(1, $item->image);
*/
if(isset($item->image))
return $item->image;
else
return null;
}
static function getCtegory($id) {
$query = "SELECT id, catid FROM #__content WHERE id = '" . $id . "' AND state = '1';";
$db = JFactory::getDBO();
$db->setQuery($query);
$result = $db->loadObject();
if(isset($result)) {
return $result->catid;
} else {
return -1;
}
}
}
?>