[go: up one dir, main page]

Menu

[r5]: / lib / common.lib.php  Maximize  Restore  History

Download this file

804 lines (704 with data), 26.2 kB

  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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
<?php
if(!defined('__PRAGYAN_CMS'))
{
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo "<h1>403 Forbidden<h1><h4>You are not authorized to access the page.</h4>";
echo '<hr/>'.$_SERVER['SERVER_SIGNATURE'];
exit(1);
}
/**
* @package pragyan
* @file common.lib.php
* @brief Contains functions which are common to many tasks and very frequently used.
* @author Abhishek <i.abhi27[at]gmail.com>.
* @copyright (c) 2010 Pragyan Team.
* @license http://www.gnu.org/licenses/ GNU Public License.
* For more details, see README
*/
global $sourceFolder,$moduleFolder;
require_once("smarttable.class.php");
/** To connect to the database*/
function connect() {
$dbase = mysql_connect(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD) or die("Could not connect to server");
mysql_select_db(MYSQL_DATABASE) or die("Could not connect to database");
return $dbase;
}
/** To disconnect from the database once query is over*/
function disconnect() {
mysql_close();
}
function prettyurl($str) {
global $urlRequestRoot;
if(strpos("a".$str,"http")==1) if(!strpos("a".$str,hostURL())) return $str;
if(strpos("a".$str,$urlRequestRoot."/cms")) return $str;
$page = (isset($_GET['page']))?$_GET['page']:"/";
$file="";
$ch = (strpos("a".$str,hostURL())==1)?strlen(hostURL()):2;
if(strripos("a".$str,".")>$ch&&($ch==2||strpos("a".$str,hostURL()."/home/")==1)) {
$file= substr($str,strripos($str,"/")+1);
$str = substr($str,0,strripos($str,"/")+1);
}
if(substr($str,0,3)=="../"){
$page = substr($page,0,strripos($page,"/")-1);
$page = substr($page,0,strripos($page,"/")+1);
}
if(strpos($str,"../")) {
$pos = strpos($str,"../");
$page = substr($page,0,strripos($page,"/")-1);
$page = substr($page,0,strripos($page,"/")+1);
$str = substr($str,0,$pos) . substr($str,$pos+3);
}
$str = preg_replace("/^.\//",$urlRequestRoot."/?page=".$page,$str);
$str = preg_replace("/^..\//",$urlRequestRoot."/?page=".$page,$str);
$str = preg_replace("/\+/","&action=",$str);
$str = preg_replace("/^".str_replace("/","\/",hostURL())."\/home/",hostURL()."/?page=",$str);
$str = preg_replace("/^".str_replace("/","\/",$urlRequestRoot)."\/home/","./?page=",$str);
if($file!="")
$str .= "&fileget=".$file;
return $str;
}
function convertUrif($x,$attr) {
$y="";
$z = $x;
$len=strlen($attr);
if($len!=0)
while(1) {
$z=$x;
$count=0;
if(strpos($x,$attr))
$y .= substr($x,$count,strpos($x,$attr)+$len+2);
else
$y .= substr($x,$count);
$count=strpos($x,$attr)+$len+2;
if($count==$len+2) break;
$x = substr($x,$count-1);
if($x[0]!='"'&&$x[0]!="'") {
$x = substr($x,1);
continue;
}
$x = substr($x,1);
//echo "<br>" . substr($x,0,strpos($x,"\"")) . " => " . prettyurl(substr($x,0,strpos($x,"\"")));
$count1=(strpos($x,"\"")==-1||!strpos($x,"\""))?10000:strpos($x,"\"");
$count2=(strpos($x,"'")==-1||!strpos($x,"'"))?10000:strpos($x,"'");
$count=($count1<$count2)?$count1:$count2;
// echo substr($x,0,$count) ." => ". prettyurl(substr($x,0,$count)). "<br>";
$y .= prettyurl(substr($x,0,$count));
$x = substr($x,$count);
}
return $y;
}
function convertUri($x) {
$y="";
$z = $x;
$hsref=array(" href"," action"," src");
foreach($hsref as $href) {
$len=strlen($href);
if($len!=0)
$z=convertUrif($z,$href);
}
return $z;
}
/** Security Functions Begin, by Abhishek (For Usage, read Security Guidelines)**/
/** To escape the database queries for avoiding SQL injection attacks */
function escape($query)
{
if (!get_magic_quotes_gpc()) {
$xquery = mysql_real_escape_string($query);
/// If there's no mysql connection, then the xquery will be false
if($xquery===false)
{
connect();
return escape($query);
}
else return $xquery;
}
return $query;
}
/** Another escape, which is not so secure as previous one, but it should only be used in install script.
Reason being this doesn't require to establish a mysql connection unlike previous one. Can be hacked if
multibyte character set is used (e.g. GBK), highly unlikely though coz I trust the admin! -Abhishek
*/
function nomysql_escape($query)
{
if (!get_magic_quotes_gpc()) {
$query=addslashes($query);
}
return $query;
}
/** To protect against writing dangerous URLs, Returns true if it detects a risk, More improvement to be done */
function URLSecurityCheck($getvars)
{
foreach($getvars as $var=>$val)
{
if(preg_match("/[<>]/",$var) || preg_match("/[<>]/",$val))
return true;
}
return false;
}
/** To prevent XSS attacks */
function safe_html($html)
{
return htmlspecialchars(strip_tags($html));
}
/** Security Functions Ends **/
/** Load Templates into the database */
function reloadTemplates()
{
global $sourceFolder;
global $templateFolder;
$templates=scandir($sourceFolder.'/'.$templateFolder);
$res="<table>";
$temparrr=array();
foreach($templates as $tdir)
{
$tdir=escape($tdir);
if(is_dir($sourceFolder.'/'.$templateFolder.'/'.$tdir) && $tdir[0]!='.' && $tdir!="common")
{
$query="INSERT IGNORE INTO `".MYSQL_DATABASE_PREFIX."templates` (`template_name`) VALUES ('$tdir')";
mysql_query($query);
if(mysql_affected_rows())
$res.="<tr><td>$tdir</td><td><b>Found new template! Installed.</b></td></tr>";
else $res.="<tr><td>$tdir</td><td>OK</td></tr>";
$temparr[]=$tdir;
}
}
$templist=join("','",$temparr);
$query="DELETE FROM `".MYSQL_DATABASE_PREFIX."templates` WHERE `template_name` NOT IN ('$templist')";
mysql_query($query);
if($delc=mysql_affected_rows()>0)
$res.="<tr><td colspan=2>$delc template(s) removed from database</td></tr>";
return $res."</table>";
}
function reloadModules()
{
global $sourceFolder;
global $moduleFolder;
$modules=scandir($sourceFolder.'/'.$moduleFolder);
$res="<table>";
$modarr=array();
foreach($modules as $module)
{
$module=escape($module);
$ext=substr($module,-8);
$module=substr($module,0,-8);
if($ext==".lib.php")
{
$query="INSERT IGNORE INTO `".MYSQL_DATABASE_PREFIX."modules` (`module_name`) VALUES ('$module')";
mysql_query($query);
if(mysql_affected_rows())
$res.="<tr><td>$module</td><td><b>Found new module! Installed.</b></td></tr>";
else $res.="<tr><td>$module</td><td>OK</td></tr>";
$modarr[]=$module;
}
}
$modlist=join("','",$modarr);
$query="DELETE FROM `".MYSQL_DATABASE_PREFIX."modules` WHERE `module_name` NOT IN ('$modlist')";
mysql_query($query);
if($delc=mysql_affected_rows()>0)
$res.="<tr><td colspan=2>$delc module(s) removed from database</td></tr>";
return $res."</table>";
}
/** To retrieve Global Settings from Database */
function getGlobalSettings()
{
$query="SELECT * FROM `".MYSQL_DATABASE_PREFIX."global`";
$result=mysql_query($query);
$globals=array();
while($row=mysql_fetch_array($result))
$globals[$row['attribute']]=$row['value'];
return $globals;
}
/** To set Global Settings in Database */
function setGlobalSettings($globals)
{
foreach($globals as $var => $val)
{
setGlobalSettingByAttribute($var,$val);
}
}
/** To Check if the email provider is not blacklisted */
function check_email($mail)
{
$domain = substr(strstr($mail,'@'),1);
$ip = gethostbyname($domain);
$query = "SELECT * FROM `".MYSQL_DATABASE_PREFIX."blacklist` WHERE `domain` = '$domain' OR `ip`= '$ip'";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if($num_rows)
return 0;
return 1;
}
/** To set Global Settings by attribute in Database */
function setGlobalSettingByAttribute($attribute,$value)
{
if(mysql_num_rows(mysql_query("SELECT `value` FROM `" . MYSQL_DATABASE_PREFIX . "global` WHERE `attribute` = '$attribute'")) != 0)
$query="UPDATE `".MYSQL_DATABASE_PREFIX."global` SET `value`='$value' WHERE `attribute`='$attribute'";
else
$query="INSERT INTO `" . MYSQL_DATABASE_PREFIX . "global`(`attribute`,`value`) VALUES('{$attribute}','{$value}')";
mysql_query($query);
}
/**Used for error handling */
function displayerror($error_desc) {
global $ERRORSTRING;
$ERRORSTRING .= "<div class=\"cms-error\">$error_desc</div>";
}
/**Used for giving info */
function displayinfo($error_desc) {
global $INFOSTRING;
$INFOSTRING .= "<div class=\"cms-info\">$error_desc</div>";
}
/**Used for giving warning*/
function displaywarning($error_desc) {
global $WARNINGSTRING;
$WARNINGSTRING .= "<div class=\"cms-warning\">$error_desc</div>";
}
/**
* Convert an array to a string recursively
* @param $array Array to convert
* @return string containing the array information
*/
function arraytostring($array) {
$text = "array(";
$count=count($array);
$x=0;
foreach ($array as $key=>$value) {
$x++;
if (is_array($value)) {
if(substr($text,-1,1)==')')
$text .= ',';
$text.='"'.$key.'"'."=>".arraytostring($value);
continue;
}
$text.="\"$key\"=>\"$value\"";
if ($count!=$x)
$text.=",";
}
$text.=")";
if(substr($text, -4, 4)=='),),')$text.='))';
return $text;
}
/**
* Determines the User Name of a user, given his/her User Id
* @param $userId User Id of the user, whose User Name is to be determined
* @return string containing the User Name of the user, null representing failure
*/
function getUserName($userId) {
if($userId <= 0) return "Anonymous";
$query = "SELECT `user_name` FROM `".MYSQL_DATABASE_PREFIX."users` WHERE `user_id` = '".$userId."'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
return $row[0];
}
/**
* Determines the Full Name of a user, given his/her User Id
* @param $userId User Id of the user, whose Full Name is to be determined
* @return string containing the Full Name of the user, null representing failure
*/
function getUserFullName($userId) {
if($userId <= 0) return "Anonymous";
$query = "SELECT `user_fullname` FROM `".MYSQL_DATABASE_PREFIX."users` WHERE `user_id` = '".$userId."'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
return $row[0];
}
/**
* Determines the Full Name of a user, given his/her Email ID
* @param $email Email Id of the user, whose Full Name is to be determined
* @return string containing the Full Name of the user, null representing failure
*/
function getUserFullNameFromEmail($email) {
$query = "SELECT `user_fullname` FROM `".MYSQL_DATABASE_PREFIX."users` WHERE `user_email` = '".$email."'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
return $row[0];
}
/**
* Determines the Email-Id of a user, given his/her User Id
* @param $userid User Id of the user, whose E-mail address is to be determined
* @return string containing the e-mail address of the user, null representing failure
*/
function getUserEmail($userId) {
if($userId <= 0) return 'Anonymous';
$query="SELECT `user_email` FROM `".MYSQL_DATABASE_PREFIX."users` WHERE `user_id` = '".$userId."'";
$result = mysql_query($query);
$row= mysql_fetch_row($result);
return $row[0];
}
/**
* Determines the User Id of a user, given his/her E-mail Id
* @param $email E-mail address of the user, whose User Id is to be determined
* @return Integer representing the User Id of the user, null representing failure
*/
function getUserIdFromEmail($email) {
if(strtolower($email) == 'anonymous') return 0;
$query = 'SELECT `user_id` FROM `'.MYSQL_DATABASE_PREFIX."users` WHERE `user_email` = '".$email."'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
return $row[0];
}
/**
* Determines the module type of a given page
* @param $pageid Page id of the page, whose module name is to be determined
* @return String containing the module name of the given page
*/
function getEffectivePageModule($pageId) {
$pagemodule_query = "SELECT `page_module`, `page_modulecomponentid` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`='".$pageId."'";
$pagemodule_result = mysql_query($pagemodule_query);
$pagemodule_row = mysql_fetch_assoc($pagemodule_result);
if($pagemodule_row['page_module']=="link") return (getEffectivePageModule($pagemodule_row['page_modulecomponentid']));
return $pagemodule_row['page_module'];
}
/**
* Gets the next module component id of a given module, which can be used for creating new instances of the same module.
* @param $modulename Name of the module
* @return Integer representing the new module component id
*/
function getNextModuleComponentId($modulename) {
$moduleComponentIdQuery = "SELECT MAX(page_modulecomponentid) FROM `".MYSQL_DATABASE_PREFIX."_pages` WHERE `page_module`='$modulename'";
$moduleComponentIdResult = mysql_query($moduleComponentIdQuery);
if(!$moduleComponentIdResult)
return 0;
$moduleComponentIdRow = mysql_fetch_row($moduleComponentIdResult);
if(!is_null($moduleComponentIdRow[0]))
return $moduleComponentIdRow[0] + 1;
return 1;
}
/**
* Determines the dereferenced Page Id of a given page
* @param $pageid Page id of the page (link) to be dereferenced
* @return Integer indicating the dereferenced page id
*/
function getDereferencedPageId($pageId) {
$pagemodule_query = "SELECT `page_module`, `page_modulecomponentid` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`='".$pageId."'";
$pagemodule_result = mysql_query($pagemodule_query);
$pagemodule_row = mysql_fetch_assoc($pagemodule_result);
if($pagemodule_row['page_module']=="link") {
return getDereferencedPageId($pagemodule_row['page_modulecomponentid']);
}
return $pageId;
}
function getPagePath($pageid) {
$pagepath = '';
while($pageid != 0) {
$pathQuery = "SELECT `page_parentid`, `page_name` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id` = '".$pageid."'";
$pathResult = mysql_query($pathQuery);
$pathResultRow = mysql_fetch_row($pathResult);
$pageid = $pathResultRow[0];
$pagepath = $pathResultRow[1]."/$pagepath";
}
return "/$pagepath";
}
function getPageModule($pageId) {
$pagemodule_query = "SELECT `page_module` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`=".$pageId;
$pagemodule_result = mysql_query($pagemodule_query);
$pagemodule_row = mysql_fetch_assoc($pagemodule_result);
return $pagemodule_row['page_module'];
}
function getPageTitle($pageId) {
$pagemodule_query = "SELECT `page_title` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`='".$pageId."'";
$pagemodule_result = mysql_query($pagemodule_query);
$pagemodule_row = mysql_fetch_assoc($pagemodule_result);
return $pagemodule_row['page_title'];
}
/**
* Determines the page id of the parent of a given page
* @param $pageid Page id of the page, whose parent is to be determined
* @return Integer indicating the page id of the parent page
*/
function getParentPage($pageid) {
$pageparent_query = "SELECT `page_parentid` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`='".$pageid."'";
$pageparent_result = mysql_query($pageparent_query);
$pageparent_row = mysql_fetch_assoc($pageparent_result);
return $pageparent_row['page_parentid'];
}
function getPageInfo($pageid) {
$pageparent_query = "SELECT `page_id`, `page_name`, `page_parentid`, `page_title`, `page_module`, `page_modulecomponentid`, `page_menurank`, `page_inheritedinfoid`, `page_displayinmenu`, `page_displaymenu`, `page_displaysiblingmenu`, `page_menutype`, `page_menudepth`, `page_image`, `page_displayicon` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`='".$pageid."'";
$pageparent_result = mysql_query($pageparent_query);
$pageparent_row = mysql_fetch_assoc($pageparent_result);
return $pageparent_row;
}
function getPageModuleComponentId($pageid) {
$pageparent_query = "SELECT `page_modulecomponentid` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_id`='".$pageid."'";
$pageparent_result = mysql_query($pageparent_query);
$pageparent_row = mysql_fetch_assoc($pageparent_result);
return $pageparent_row['page_modulecomponentid'];
}
function getPageIdFromModuleComponentId($moduleName,$moduleComponentId) {
$moduleid_query = "SELECT `page_id` FROM `".MYSQL_DATABASE_PREFIX."pages` WHERE `page_module` = '".$moduleName."' AND `page_modulecomponentid` = '".$moduleComponentId."'";
$moduleid_result = mysql_query($moduleid_query);
$moduleid_row = mysql_fetch_assoc($moduleid_result);
return $moduleid_row['page_id'];
}
function getModuleComponentIdFromPageId($pageId, $moduleName) {
$moduleIdQuery = 'SELECT `page_modulecomponentid` FROM `' . MYSQL_DATABASE_PREFIX . "pages` WHERE `page_module` = '".$moduleName."' AND `page_id` = '".$pageId."'";
$moduleIdResult = mysql_query($moduleIdQuery);
$moduleIdRow = mysql_fetch_row($moduleIdResult);
return $moduleIdRow[0];
}
/**
*@author boopathi
*@description returns the depth of the page - 0 if the page is a child of /home
*@param pageId
*@return pageDepth
**/
function getPageDepth($pageId) {
$depth = 1;
if(getParentPage($pageId) == 0)
return 0;
else
return $depth + getPageDepth(getParentPage($pageId));
}
function logInfo ($userEmail, $userId, $pageId, $pagePath, $permModule, $permAction, $accessIpAddress) {
if(isRequiredMaintenance()) {
require_once("maintenance.lib.php");
runMaintenance();
}
if($pageId === false) $pageId = -1;
if(isset($_GET['fileget'])) return false;
$updateQuery = "SELECT `log_no` FROM `".MYSQL_DATABASE_PREFIX."log` WHERE `log_no` = 1";
$result = mysql_query($updateQuery);
if(!$result || mysql_num_rows($result) == 0)
$updateQuery = "INSERT INTO `".MYSQL_DATABASE_PREFIX."log` (`log_no`, `user_email`, `user_id`, `page_id`, `page_path`, `perm_module`, `perm_action`, `user_accessipaddress`)
VALUES ( 1 , '".$userEmail."', ".$userId.", ".$pageId.", '".$pagePath."', '".$permModule."', '".$permAction."', '".$accessIpAddress."' );";
else
$updateQuery = "INSERT INTO `".MYSQL_DATABASE_PREFIX."log` (`log_no`, `user_email`, `user_id`, `page_id`, `page_path`, `perm_module`, `perm_action`, `user_accessipaddress`)
( SELECT (MAX(log_no)+1) , '".$userEmail."', ".$userId.", ".$pageId.", '".$pagePath."', '".$permModule."', '".$permAction."', '".$accessIpAddress."' FROM `".MYSQL_DATABASE_PREFIX."log`);";
if(!mysql_query($updateQuery))
displayerror ("Error in logging info.");
return true;
}
#returns true for first access of every 10 day slab
#select date > sub(now, diff(now,first)%10)
function isRequiredMaintenance() {
$requiredQuery = "SELECT log_datetime FROM `".MYSQL_DATABASE_PREFIX."log` WHERE
log_datetime >
SUBDATE( SUBTIME(NOW(),CURTIME()),(
DATEDIFF(
NOW(), (
SELECT MIN(log_datetime) FROM `".MYSQL_DATABASE_PREFIX."log`
)
)
)%10
)
LIMIT 0,1";
$requiredResult = mysql_query($requiredQuery);
if($requiredResult!=NULL && mysql_num_rows($requiredResult) == 0) {
return true;
}
return false;
}
/**
* Replaces the protocol in a url with https://
* @param $url Url to be converted
* @return Converted Url
*/
function convertToHttps($url){
if(!strncasecmp("https://",$url,8))
return $url;
else
return str_replace("http://","https://",$url);
}
/**
* Replaces the protocol in a url with http://
* @param $url Url to be converted
* @return Converted Url
*/
function convertToHttp($url){
if(!strncasecmp("http://",$url,7))
return $url;
else {
$pos = strpos($url, '://');
if($pos >= 0) {
return 'http://' . substr($url, $pos + 3);
}
else return $url;
}
}
function verifyHttps($url){
if(!strncasecmp("https://",$url,7))
return true;
else
return false;
}
function selfURI() {
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function hostURL() {
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$location = substr($_SERVER['SCRIPT_NAME'],0,strpos($_SERVER['SCRIPT_NAME'],"/index.php"));
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$location;
}
/**
* Replaces the action in the url to a new action
*
* @param $url Initial URL
* @param $old Old Action
* @param $new New Action
*
* @return the URL with the new action
* @TODO check for rewrite enabled and handle +action as well as &action=action kind of URLs
* @warning Whats the guarantee it won't convert some word in the URL which matches the Old Action ?
*/
function replaceAction($url,$old,$new) {
$offset = strpos($url,"action=$old");
$url = substr_replace($url,$new,$offset+7,strlen($old));
return $url;
}
function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
function updateUserPassword($user_email,$user_passwd) {
$query = "UPDATE `" . MYSQL_DATABASE_PREFIX . "users` SET `user_password`= '".md5($user_passwd)."' WHERE `" . MYSQL_DATABASE_PREFIX . "users`.`user_email` = '" . $user_email . "'";
mysql_query($query) or die(mysql_error() . " in function updateUserPassword");
}
function getUserInfo($user_email) {
$query = "SELECT `user_id`,`user_password`,`user_name`,`user_activated`,`user_lastlogin`,`user_loginmethod` FROM `" . MYSQL_DATABASE_PREFIX . "users` WHERE `user_email` = '" . $user_email . "'";
$result = mysql_query($query) or die(mysql_error() . " in function getUserInfo : common.lib.php");
return mysql_fetch_assoc($result);
}
/*
@todo should be moved to email.lib.php ,or is it really used ?
*/
class messenger {
var $vars;
function assign_vars($vars) {
$this->vars = (empty($this->vars)) ? $vars : $this->vars + $vars;
}
function mailer($to,$mailtype,$key,$from) {
if(empty($from)) $from="from: ".CMS_TITLE." <".CMS_EMAIL.">";
//init mail template file path
$mail_filepath= MAILPATH."/".LANGUAGE."/email/$mailtype.txt";
$drop_header = '';
if(!file_exists($mail_filepath)) {displayerror(safe_html("NO FILE called $mail_filepath FOUND !"));} //check file
if(($data = @file_get_contents($mail_filepath)) === false) {displayerror("$mail_filepath FILE READ ERROR !");} //read contents
//escape quotes
$body = str_replace ("'", "\'", $data);
//replace the vars in file content with those defined
$body = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . ((isset(\$this->vars['\\1'])) ? \$this->vars['\\1'] : '') . '", $body);
//Make the content parseable
eval("\$body = '$body';");
//Extract the SUBJECT from mail content
$match=array();
if (preg_match('#^(Subject:(.*?))$#m', $body, $match)) {
//Find SUBJECT
$subject = (trim($match[2]) != '') ? trim($match[2]) : $subject ;
$drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
}
if ($drop_header) {
//Remove SUBJECT from BODY of mail
$body = trim(preg_replace('#' . $drop_header . '#s', '', $body));
}
//Debug info
//echo displayinfo($from.' <br> '.$to.' <br> '.$subject.' <br> '.$body);
//Send mail
global $debugSet;
if($debugSet=="on")
{
displayinfo("Vars :".arraytostring($this->vars));
displayinfo("Mail sent to $to from $from with subject $subject and body $body");
}
return mail($to, $subject, $body, $from);
}
}
function getAvailableTemplates()
{
$query="SELECT template_name FROM `".MYSQL_DATABASE_PREFIX."templates`";
$result=mysql_query($query);
$templates=array();
$i=0;
while($row=mysql_fetch_row($result))
{
$templates[$i]=$row[0];
$i++;
}
return $templates;
}
function getAvailableModules()
{
$query="SELECT `module_name` FROM `".MYSQL_DATABASE_PREFIX."modules`";
$result=mysql_query($query);
$templates=array();
$i=0;
while($row=mysql_fetch_row($result))
{
$templates[$i]=$row[0];
$i++;
}
return $templates;
}
function getTableFieldsName($tablename,$exclude="user_profilepic")
{
$query="SELECT * FROM ".MYSQL_DATABASE_PREFIX.$tablename;
$result=mysql_query($query);
$numfields=mysql_num_fields($result);
$fields=array();
$i=0;
$exclist=explode(",",$exclude);
while($i<$numfields)
{
$meta=mysql_fetch_field($result,$i);
if($meta && array_search($meta->name,$exclist)===FALSE)
{
$fields[$i]=$meta->name;
}
$i++;
}
return $fields;
}
function getNextUserId()
{
$query="SELECT max(user_id) FROM ".MYSQL_DATABASE_PREFIX."users";
$result=mysql_query($query);
$row=mysql_fetch_row($result);
return $row[0]+1;
}
function showBreadcrumbSubmenu()
{
$query="SELECT `value` FROM `".MYSQL_DATABASE_PREFIX."global` WHERE `attribute`='breadcrumb_submenu'";
$result = mysql_fetch_row(mysql_query($query));
return $result[0];
}
function getFileActualPath($moduleType,$moduleComponentId,$fileName)
{
$query = "SELECT * FROM `" . MYSQL_DATABASE_PREFIX . "uploads` WHERE `upload_filename`= '". escape($fileName). "' AND `page_module` = '".escape($moduleType)."' AND `page_modulecomponentid` = '".escape($moduleComponentId)."'";
$result = mysql_query($query) or die(mysql_error() . "upload L:85");
$row = mysql_fetch_assoc($result);
/**
* Not checking if filetype adheres to uploadable filetype list beacuse this check can be
* performed in $moduleInstance->getFileAccessPermission.
*/
global $sourceFolder,$uploadFolder;
$upload_fileid = $row['upload_fileid'];
$filename = str_repeat("0", (10 - strlen((string) $upload_fileid))) . $upload_fileid . "_" . $fileName;
$file = $sourceFolder . "/" . $uploadFolder . "/" . $moduleType . "/" . $filename;
return $file;
}
/**
* Checks for presence of the cURL extension for OpenID.
*/
function iscurlinstalled() {
if (in_array ('curl', get_loaded_extensions())) {
return true;
}
else{
return false;
}
}
$curl_message="cURL extention is not enabled/installed on your system. OpenID requires this extention to be loaded. Please enable cURL extention. (This can be done by uncommenting the line \"extension=curl.so\" in your php.ini file). OpenID can't be enabled until you enable cURL.";
function censor_words($text)
{
$query = "SELECT `value` FROM `".MYSQL_DATABASE_PREFIX."global` WHERE `attribute` = 'censor_words'";
$words = mysql_query($query);
$words = mysql_fetch_row($words);
$replace = "<b>CENSORED</b>";
if($words[0]=='')
return $text;
else
$res = preg_replace("/$words[0]/i",$replace,$text);
return $res;
}