CodingPhpTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. <?php
  2. /* Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. * or see https://www.gnu.org/
  17. */
  18. /**
  19. * \file test/phpunit/SqlTest.php
  20. * \ingroup test
  21. * \brief PHPUnit test
  22. * \remarks To run this script as CLI: phpunit filename.php
  23. */
  24. global $conf,$user,$langs,$db;
  25. //define('TEST_DB_FORCE_TYPE','mysql'); // This is to force using mysql driver
  26. //require_once 'PHPUnit/Autoload.php';
  27. require_once dirname(__FILE__).'/../../htdocs/master.inc.php';
  28. require_once dirname(__FILE__).'/../../htdocs/core/lib/security.lib.php';
  29. require_once dirname(__FILE__).'/../../htdocs/core/lib/security2.lib.php';
  30. if (! defined('NOREQUIREUSER')) {
  31. define('NOREQUIREUSER', '1');
  32. }
  33. if (! defined('NOREQUIREDB')) {
  34. define('NOREQUIREDB', '1');
  35. }
  36. if (! defined('NOREQUIRESOC')) {
  37. define('NOREQUIRESOC', '1');
  38. }
  39. if (! defined('NOREQUIRETRAN')) {
  40. define('NOREQUIRETRAN', '1');
  41. }
  42. if (! defined('NOCSRFCHECK')) {
  43. define('NOCSRFCHECK', '1');
  44. }
  45. if (! defined('NOTOKENRENEWAL')) {
  46. define('NOTOKENRENEWAL', '1');
  47. }
  48. if (! defined('NOREQUIREMENU')) {
  49. define('NOREQUIREMENU', '1'); // If there is no menu to show
  50. }
  51. if (! defined('NOREQUIREHTML')) {
  52. define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
  53. }
  54. if (! defined('NOREQUIREAJAX')) {
  55. define('NOREQUIREAJAX', '1');
  56. }
  57. if (! defined("NOLOGIN")) {
  58. define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
  59. }
  60. if (empty($user->id)) {
  61. print "Load permissions for admin user nb 1\n";
  62. $user->fetch(1);
  63. $user->getrights();
  64. }
  65. $conf->global->MAIN_DISABLE_ALL_MAILS=1;
  66. /**
  67. * Class for PHPUnit tests
  68. *
  69. * @backupGlobals disabled
  70. * @backupStaticAttributes enabled
  71. * @remarks backupGlobals must be disabled to have db,conf,user and lang not erased.
  72. */
  73. class CodingPhpTest extends PHPUnit\Framework\TestCase
  74. {
  75. protected $savconf;
  76. protected $savuser;
  77. protected $savlangs;
  78. protected $savdb;
  79. /**
  80. * Constructor
  81. * We save global variables into local variables
  82. *
  83. * @return SecurityTest
  84. */
  85. public function __construct()
  86. {
  87. parent::__construct();
  88. //$this->sharedFixture
  89. global $conf,$user,$langs,$db;
  90. $this->savconf=$conf;
  91. $this->savuser=$user;
  92. $this->savlangs=$langs;
  93. $this->savdb=$db;
  94. print __METHOD__." db->type=".$db->type." user->id=".$user->id;
  95. //print " - db ".$db->db;
  96. print "\n";
  97. }
  98. /**
  99. * setUpBeforeClass
  100. *
  101. * @return void
  102. */
  103. public static function setUpBeforeClass()
  104. {
  105. global $conf,$user,$langs,$db;
  106. $db->begin(); // This is to have all actions inside a transaction even if test launched without suite.
  107. print __METHOD__."\n";
  108. }
  109. /**
  110. * tearDownAfterClass
  111. *
  112. * @return void
  113. */
  114. public static function tearDownAfterClass()
  115. {
  116. global $conf,$user,$langs,$db;
  117. $db->rollback();
  118. print __METHOD__."\n";
  119. }
  120. /**
  121. * Init phpunit tests
  122. *
  123. * @return void
  124. */
  125. protected function setUp()
  126. {
  127. global $conf,$user,$langs,$db;
  128. $conf=$this->savconf;
  129. $user=$this->savuser;
  130. $langs=$this->savlangs;
  131. $db=$this->savdb;
  132. print __METHOD__."\n";
  133. }
  134. /**
  135. * End phpunit tests
  136. *
  137. * @return void
  138. */
  139. protected function tearDown()
  140. {
  141. print __METHOD__."\n";
  142. }
  143. /**
  144. * testSql
  145. *
  146. * @return string
  147. */
  148. public function testPHP()
  149. {
  150. global $conf,$user,$langs,$db;
  151. $conf=$this->savconf;
  152. $user=$this->savuser;
  153. $langs=$this->savlangs;
  154. $db=$this->savdb;
  155. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  156. $filesarray = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, '\.php', null, 'fullname', SORT_ASC, 0, 0, '', 1);
  157. //$filesarray = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, '\.php', null, 'fullname');
  158. foreach ($filesarray as $key => $file) {
  159. if (preg_match('/\/htdocs\/includes\//', $file['fullname'])) {
  160. continue;
  161. }
  162. if (preg_match('/\/htdocs\/custom\//', $file['fullname'])) {
  163. continue;
  164. }
  165. if (preg_match('/\/htdocs\/dolimed/', $file['fullname'])) {
  166. continue;
  167. }
  168. if (preg_match('/\/htdocs\/nltechno/', $file['fullname'])) {
  169. continue;
  170. }
  171. if (preg_match('/\/htdocs\/teclib/', $file['fullname'])) {
  172. continue;
  173. }
  174. print 'Check php file '.$file['fullname']."\n";
  175. $filecontent=file_get_contents($file['fullname']);
  176. if (preg_match('/\.class\.php/', $file['relativename'])
  177. || preg_match('/boxes\/box_/', $file['relativename'])
  178. || preg_match('/modules\/.*\/doc\/(doc|pdf)_/', $file['relativename'])
  179. || preg_match('/modules\/(import|mailings|printing)\//', $file['relativename'])
  180. || in_array($file['name'], array('modules_boxes.php', 'rapport.pdf.php', 'TraceableDB.php'))) {
  181. if (! in_array($file['name'], array(
  182. 'api.class.php',
  183. 'actioncomm.class.php',
  184. 'commonobject.class.php',
  185. 'conf.class.php',
  186. 'html.form.class.php',
  187. 'html.formmail.class.php',
  188. 'infobox.class.php',
  189. 'link.class.php',
  190. 'translate.class.php',
  191. 'utils.class.php',
  192. 'modules_product.class.php',
  193. 'modules_societe.class.php',
  194. 'TraceableDB.php',
  195. 'expeditionbatch.class.php',
  196. 'expensereport_ik.class.php',
  197. 'expensereport_rule.class.php',
  198. 'multicurrency.class.php',
  199. 'productbatch.class.php',
  200. 'reception.class.php',
  201. 'societe.class.php' ,
  202. 'account.class.php'
  203. ))) {
  204. // Must must not found $db->
  205. $ok=true;
  206. $matches=array();
  207. // Check string $db-> inside a class.php file (it should be $this->db-> insto such classes)
  208. preg_match_all('/'.preg_quote('$db->', '/').'/', $filecontent, $matches, PREG_SET_ORDER);
  209. foreach ($matches as $key => $val) {
  210. $ok=false;
  211. break;
  212. }
  213. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  214. $this->assertTrue($ok, 'Found string $db-> into a .class.php file in '.$file['relativename']);
  215. //exit;
  216. }
  217. } else {
  218. if (! in_array($file['name'], array(
  219. 'extrafieldsinexport.inc.php',
  220. 'DolQueryCollector.php'
  221. ))) {
  222. // Must must not found $this->db->
  223. $ok=true;
  224. $matches=array();
  225. // Check string $this->db-> into a non class.php file (it shoud be $db-> into such classes)
  226. preg_match_all('/'.preg_quote('$this->db->', '/').'/', $filecontent, $matches, PREG_SET_ORDER);
  227. foreach ($matches as $key => $val) {
  228. $ok=false;
  229. break;
  230. }
  231. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  232. $this->assertTrue($ok, 'Found string $this->db-> in '.$file['relativename']);
  233. //exit;
  234. }
  235. }
  236. $ok=true;
  237. $matches=array();
  238. // Check string get_class...
  239. preg_match_all('/'.preg_quote('get_class($this)."::".__METHOD__', '/').'/', $filecontent, $matches, PREG_SET_ORDER);
  240. foreach ($matches as $key => $val) {
  241. $ok=false;
  242. break;
  243. }
  244. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  245. $this->assertTrue($ok, 'Found string get_class($this)."::".__METHOD__ that must be replaced with __METHOD__ only in '.$file['relativename']);
  246. //exit;
  247. $ok=true;
  248. $matches=array();
  249. // Check string $this->db->idate without quotes
  250. preg_match_all('/(..)\s*\.\s*\$this->db->idate\(/', $filecontent, $matches, PREG_SET_ORDER);
  251. foreach ($matches as $key => $val) {
  252. if ($val[1] != '\'"' && $val[1] != '\'\'') {
  253. $ok=false;
  254. break;
  255. }
  256. //if ($reg[0] != 'db') $ok=false;
  257. }
  258. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  259. $this->assertTrue($ok, 'Found a $this->db->idate to forge a sql request without quotes around this date field '.$file['relativename']);
  260. //exit;
  261. $ok=true;
  262. $matches=array();
  263. // Check sql string AND ... yyy = ".$xxx
  264. // with xxx that is not 'thi' (for $this->db->sanitize) and 'db-' (for $db->sanitize). It means we forget a ' if string or an (int) if int when forging sql request.
  265. preg_match_all('/(DELETE|OR|AND)\s.*([^\s][^\s][^\s])\s*=\s*"\s*\.\s*\$(...)/', $filecontent, $matches, PREG_SET_ORDER);
  266. foreach ($matches as $key => $val) {
  267. if ($val[2] == 'ity' && $val[3] == 'con') {
  268. continue;
  269. }
  270. var_dump($matches);
  271. $ok=false;
  272. break;
  273. }
  274. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  275. $this->assertTrue($ok, 'Found non quoted or not casted var into sql request '.$file['relativename'].' - Bad.');
  276. //exit;
  277. // Check string ='".$this->xxx with xxx that is not 'escape'. It means we forget a db->escape when forging sql request.
  278. preg_match_all('/=\s*\'"\s*\.\s*\$this->(....)/', $filecontent, $matches, PREG_SET_ORDER);
  279. foreach ($matches as $key => $val) {
  280. if ($val[1] != 'db->' && $val[1] != 'esca') {
  281. $ok=false;
  282. break;
  283. }
  284. //if ($reg[0] != 'db') $ok=false;
  285. }
  286. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  287. $this->assertTrue($ok, 'Found non escaped string in building of a sql request '.$file['relativename'].' - Bad.');
  288. //exit;
  289. // Check string sql|set...'".$yyy->xxx with xxx that is not 'escape', 'idate', .... It means we forget a db->escape when forging sql request.
  290. preg_match_all('/(sql|SET).+\s*\'"\s*\.\s*\$(.........)/', $filecontent, $matches, PREG_SET_ORDER);
  291. foreach ($matches as $key => $val) {
  292. if (! in_array($val[2], array('this->db-', 'this->esc', 'db->escap', 'dbsession', 'db->idate', 'excludeGr', 'includeGr'))) {
  293. $ok=false;
  294. break;
  295. }
  296. //if ($reg[0] != 'db') $ok=false;
  297. }
  298. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  299. $this->assertTrue($ok, 'Found non escaped string in building of a sql request '.$file['relativename'].': '.$val[0].' - Bad.');
  300. //exit;
  301. // Check string 'IN (".xxx' or 'IN (\'.xxx' with xxx that is not '$this->db->sanitize' and not '$db->sanitize'. It means we forget a db->sanitize when forging sql request.
  302. preg_match_all('/ IN \([\'"]\s*\.\s*(.........)/i', $filecontent, $matches, PREG_SET_ORDER);
  303. foreach ($matches as $key => $val) {
  304. if (!in_array($val[1], array('$db->sani', '$this->db', 'getEntity', 'WON\',\'L', 'self::STA', 'Commande:', 'CommandeF', 'Entrepot:', 'Facture::', 'FactureFo', 'ExpenseRe', 'Societe::', 'Ticket::S'))) {
  305. $ok=false;
  306. break;
  307. }
  308. //if ($reg[0] != 'db') $ok=false;
  309. }
  310. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  311. $this->assertTrue($ok, 'Found non sanitized string in building of a IN or NOT IN sql request '.$file['relativename'].' - Bad.');
  312. //exit;
  313. // Check string 'IN (\'".xxx' with xxx that is not '$this->db->sanitize' and not '$db->sanitize'. It means we forget a db->sanitize when forging sql request.
  314. preg_match_all('/ IN \(\'"\s*\.\s*(.........)/i', $filecontent, $matches, PREG_SET_ORDER);
  315. foreach ($matches as $key => $val) {
  316. if (!in_array($val[1], array('$db->sani', '$this->db', 'getEntity', 'WON\',\'L', 'self::STA', 'Commande:', 'CommandeF', 'Entrepot:', 'Facture::', 'FactureFo', 'ExpenseRe', 'Societe::', 'Ticket::S'))) {
  317. $ok=false;
  318. break;
  319. }
  320. //if ($reg[0] != 'db') $ok=false;
  321. }
  322. //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n";
  323. $this->assertTrue($ok, 'Found non sanitized string in building of a IN or NOT IN sql request '.$file['relativename'].' - Bad.');
  324. //exit;
  325. // Test that output of $_SERVER\[\'QUERY_STRING\'\] is escaped.
  326. $ok=true;
  327. $matches=array();
  328. preg_match_all('/(..............)\$_SERVER\[\'QUERY_STRING\'\]/', $filecontent, $matches, PREG_SET_ORDER);
  329. foreach ($matches as $key => $val) {
  330. if ($val[1] != 'scape_htmltag(' && $val[1] != 'ing_nohtmltag(' && $val[1] != 'dol_escape_js(') {
  331. $ok=false;
  332. break;
  333. }
  334. }
  335. $this->assertTrue($ok, 'Found a $_SERVER[\'QUERY_STRING\'] without dol_escape_htmltag neither dol_string_nohtmltag around it, in file '.$file['relativename'].' ('.$val[1].'$_SERVER[\'QUERY_STRING\']). Bad.');
  336. // Test that first param of print_liste_field_titre is a translation key and not the translated value
  337. $ok=true;
  338. $matches=array();
  339. // Check string ='print_liste_field_titre\(\$langs'.
  340. preg_match_all('/print_liste_field_titre\(\$langs/', $filecontent, $matches, PREG_SET_ORDER);
  341. foreach ($matches as $key => $val) {
  342. $ok=false;
  343. break;
  344. }
  345. $this->assertTrue($ok, 'Found a use of print_liste_field_titre with first parameter that is a translated value instead of just the translation key in file '.$file['relativename'].'. Bad.');
  346. // Test we don't have <br />
  347. $ok=true;
  348. $matches=array();
  349. preg_match_all('/<br\s+\/>/', $filecontent, $matches, PREG_SET_ORDER);
  350. foreach ($matches as $key => $val) {
  351. if ($file['name'] != 'functions.lib.php') {
  352. $ok=false;
  353. break;
  354. }
  355. }
  356. $this->assertTrue($ok, 'Found a tag <br /> that is for xml in file '.$file['relativename'].'. You must use html syntax <br> instead.');
  357. // Test we don't have name="token" value="'.$_SESSION['newtoken'], we must use name="token" value="'.newToken() instead.
  358. $ok=true;
  359. $matches=array();
  360. preg_match_all('/name="token" value="\'\s*\.\s*\$_SESSION/', $filecontent, $matches, PREG_SET_ORDER);
  361. foreach ($matches as $key => $val) {
  362. if ($file['name'] != 'excludefile.php') {
  363. $ok=false;
  364. break;
  365. }
  366. }
  367. $this->assertTrue($ok, 'Found a forbidden string sequence into '.$file['relativename'].' : name="token" value="\'.$_SESSION[..., you must use a newToken() instead of $_SESSION[\'newtoken\'].');
  368. // Test we don't have @var array(
  369. $ok=true;
  370. $matches=array();
  371. preg_match_all('/@var\s+array\(/', $filecontent, $matches, PREG_SET_ORDER);
  372. foreach ($matches as $key => $val) {
  373. $ok=false;
  374. break;
  375. }
  376. $this->assertTrue($ok, 'Found a declaration @var array() instead of @var array in file '.$file['relativename'].'.');
  377. // Test we don't have CURDATE()
  378. $ok=true;
  379. $matches=array();
  380. preg_match_all('/CURDATE\(\)/', $filecontent, $matches, PREG_SET_ORDER);
  381. foreach ($matches as $key => $val) {
  382. $ok=false;
  383. break;
  384. }
  385. $this->assertTrue($ok, 'Found a CURDATE\(\) into code. Do not use this SQL method in file '.$file['relativename'].'. You must use the PHP function dol_now() instead.');
  386. }
  387. return;
  388. }
  389. }