Posted By

jatkins on 02/01/11


Tagged

mysql session image file search library cookie index upload user chart graph authentication account


Versions (?)

Library


 / Published in: PHP
 

Procedural.

  1. <?php
  2. /* Created December 22, 2010 by Josh Atkins
  3.  * Updated January 31, 2011 */
  4. ini_set('register_globals', 'off');
  5. global $db, $numeric_types, $session_identifier, $cookie_identifier, $default_db_name, $item_types;
  6. $numeric_types = array('integer', 'int', 'tinyint', 'smallint', 'mediumint', 'bigint', 'decimal', 'numeric', 'dec', 'fixed', 'float', 'real', 'double precision', 'double');
  7. $default_db_name = 'write';
  8. $item_types = array('document');
  9.  
  10. function relative_date($months_from_now) {
  11. $months_from_now = abs($months_from_now);
  12. $date = new DateTime();
  13. $date_interval = new DateInterval('P'.($months_from_now>=0?$months_from_now:substr($months_from_now, 1)).'M');
  14. if($months_from_now>=0) // positive
  15. $date->add($date_interval);
  16. else
  17. $date->sub($date_interval);
  18. return $date->getTimestamp();
  19. }
  20.  
  21. class session {
  22. function start() {
  23. }
  24.  
  25. function set($var_name, $var_value) {
  26. $var_value = db::sanitize_input($var_value);
  27. $_SESSION[$GLOBALS['session_identifier'].db::sanitize_input($var_name)] = $var_value;
  28. return $var_value;
  29. }
  30.  
  31. function get($var_name) {
  32. return stripslashes($_SESSION[$GLOBALS['session_identifier'].db::sanitize_input($var_name)]);
  33. }
  34.  
  35. function delete($var_name) {
  36. unset($_SESSION[$GLOBALS['session_identifier'].db::sanitize_input($var_name)]);
  37. }
  38.  
  39. function set_identifier($var) {
  40. $GLOBALS['session_identifier'] = db::sanitize_input($var) . '_';
  41. }
  42.  
  43. function end() {
  44. if(isset($_SESSION))
  45. }
  46.  
  47. function restart() {
  48. session::end();
  49. session::start();
  50. }
  51. function exists($var_name) {
  52. return isset($_SESSION[$GLOBALS['session_identifier'].$var_name]);
  53. }
  54. }
  55.  
  56. class cookie {
  57. function set_identifier($var) {
  58. $GLOBALS['cookie_identifier'] = db::sanitize_input($var) . '_';
  59. }
  60.  
  61. function set($name, $value, $months_to_expire_after = 12, $path = null, $domain = null, $secure = false, $http_only = true) {
  62. return setcookie($GLOBALS['cookie_identifier'].db::sanitize_input($name), db::sanitize_input($value), relative_date($months_to_expire_after), $path, $domain, $secure, $http_only);
  63. }
  64.  
  65. function get($name) {
  66. return stripslashes($_COOKIE[$GLOBALS['cookie_identifier'].db::sanitize_input($name)]);
  67. }
  68.  
  69. function delete($name) {
  70. return cookie::exists($name) ? cookie::set(db::sanitize_input($name), '', -1) : null;
  71. }
  72.  
  73. function exists($name) {
  74. return isset($_COOKIE[$GLOBALS['cookie_identifier'].db::sanitize_input($name)]);
  75. }
  76. }
  77.  
  78. function replace_placeholders($var, $placeholder_values) {
  79. $i = 0;
  80. $n = 0;
  81. while($i<strlen($var)) {
  82. if($var[$i]=='?') {
  83. $var = substr($var, 0, $i) . db::sanitize_input($placeholder_values[$n]) . substr($var, $i + 1);
  84. $n++;
  85. }
  86. $i++;
  87. }
  88. return $var;
  89. }
  90.  
  91. class db {
  92. function connect($db_name = null) {
  93. $GLOBALS['db'] = mysql_connect('localhost', 'root', 'password_goes_here');
  94. if(isset($db_name))
  95. mysql_select_db($db_name, $GLOBALS['db']);
  96. return $GLOBALS['db'];
  97. }
  98.  
  99. function sanitize_input($var, $strip_html = true) {
  100. if(!isset($GLOBALS['db']))
  101. db::connect();
  102. return mysql_real_escape_string($strip_html == true ? db::sanitize_text($var) : $var);
  103. }
  104.  
  105. function sanitize_style_attributes($tag_name, $tags) {
  106. for($i=0;$i<count($tags);$i++) {
  107. $tags[$i] = explode(';', $tags[$i]);
  108. $sanitized_style = array();
  109. foreach($tags[$i] as $attribute) {
  110. $attribute = explode(':', $attribute);
  111. $attribute_name = trim($attribute[0]);
  112. if($attribute_name=='text-decoration'||$attribute_name=='text-align'||$attribute_name=='font-style'||$attribute_name=='font-weight')
  113. $sanitized_style[] = implode(':', $attribute);
  114. }
  115. $tags[$i] = '<'.$tag_name.' style="' . trim(implode(';', $sanitized_style)) . '">';
  116. }
  117. return $tags;
  118. }
  119.  
  120. function str_replace_first($needle, $replacement, $haystack) {
  121. $needle_start = strpos($haystack, $needle);
  122. $needle_end = $needle_start + strlen($needle);
  123. if($needle_start!==false) { // !== is required b/c false == 0 which could equal $needle_start
  124. $to_replace = substr($haystack, 0, $needle_end);
  125. return str_replace($needle, $replacement, $to_replace) . substr($haystack, $needle_end);
  126. }
  127. else
  128. return $haystack;
  129. }
  130.  
  131. function sanitize_text($text) {
  132. //$text = str_replace(array('<span class="searchMatch">', '<!--m_a_t_c_h--></span>'), array('{[searchMatch]}', '[{/searchMatch]}'), $text);
  133. $text = strip_tags($text, '<img><a><br><p><s><b><i><u><span><div><table><tbody><tr><th><td><ul><ol><li>');
  134. $regexp = array('img' => '/<img[^>]*src=[\'\"]\/write\/download_image\.php\?filename=([^&]+)&[^n]*name=([^&]+)&[^r]*resized=([0-1])[^\'\"]*[\'\"] alt=[\'\"]([^\'\"]+)[\'\"][^>]*>/U', 'a' => '/<a[^>]*href=[\'\"](redirect_external\.php\?=|)([^\'\"]+)[\'\"][^>]*>/U', 'span' => '/<span[^>]*style=[\'\"]([^\'\"]+)[\'\"][^>]*>/U', 'b' => '/<b[^>]*style=[\'\"]([^\'\"]+)[\'\"][^>]*>/U', 'i' => '/<i[^>]*style=[\'\"]([^\'\"]+)[\'\"][^>]*>/U', 'u' => '/<u[^>]*style=[\'\"]([^\'\"]+)[\'\"][^>]*>/U', 's' => '/<s[^>]*style=[\'\"]([^\'\"]+)[\'\"][^>]*>/U', 'div' => '/<div[^>]*style=[\'\"]([^\'\"]+)[\'\"][^>]*>/U');
  135. preg_match_all($regexp['img'], $text, $images);
  136. preg_match_all($regexp['a'], $text, $links);
  137. preg_match_all($regexp['span'], $text, $spans);
  138. preg_match_all($regexp['b'], $text, $bs);
  139. preg_match_all($regexp['i'], $text, $is);
  140. preg_match_all($regexp['u'], $text, $us);
  141. preg_match_all($regexp['s'], $text, $ss);
  142. preg_match_all($regexp['div'], $text, $divs);
  143. $regexp_keys = array_keys($regexp);
  144. foreach($regexp_keys as $regexp_key) {
  145. $text = preg_replace($regexp[$regexp_key], '{[' . $regexp_key . ']}', $text);
  146. }
  147. $new_images = array();
  148. for($i=0;$i<count($images[1]);$i++) {
  149. $new_images[] = '<img src="/write/download_image.php?filename=' . $images[1][$i] . '&amp;name=' . $images[2][$i] . '&amp;resized=' . $images[3][$i] . '" alt="' . $images[4][$i] . '" title="' . $images[4][$i] . '" />';
  150. }
  151. $links = $links[2];
  152. for($i=0;$i<count($links);$i++) {
  153. $links[$i] = '<a href="redirect_external.php?url=' . urlencode($links[$i]) . '">';
  154. }
  155. $spans = db::sanitize_style_attributes('span', $spans[1]);
  156. $bs = db::sanitize_style_attributes('b', $bs[1]);
  157. $is = db::sanitize_style_attributes('i', $is[1]);
  158. $us = db::sanitize_style_attributes('u', $us[1]);
  159. $ss = db::sanitize_style_attributes('s', $ss[1]);
  160. $divs = db::sanitize_style_attributes('div', $divs[1]);
  161. $text = preg_replace('/<([^\s>]+)\s[^>]+>/U', '<$1>', $text); // strip all other attributes
  162. foreach($new_images as $image) {
  163. $text = db::str_replace_first('{[img]}', $image, $text);
  164. }
  165. foreach($links as $link) {
  166. $text = db::str_replace_first('{[a]}', $link, $text);
  167. }
  168. foreach($spans as $span) {
  169. $text = db::str_replace_first('{[span]}', $span, $text);
  170. }
  171. foreach($bs as $b) {
  172. $text = db::str_replace_first('{[b]}', $b, $text);
  173. }
  174. foreach($is as $i) {
  175. $text = db::str_replace_first('{[i]}', $i, $text);
  176. }
  177. foreach($us as $u) {
  178. $text = db::str_replace_first('{[u]}', $u, $text);
  179. }
  180. foreach($ss as $s) {
  181. $text = db::str_replace_first('{[s]}', $s, $text);
  182. }
  183. foreach($divs as $div) {
  184. $text = db::str_replace_first('{[div]}', $div, $text);
  185. }
  186. //$text = str_replace(array('{[searchMatch]}', '[{/searchMatch]}'), array('<span class="searchMatch">', '<!--m_a_t_c_h--></span>'), $text);
  187. return $text;
  188. }
  189.  
  190. function fast_is_array($array) { // from http://php.net/manual/en/function.is-array.php#98156, posted 5/28/2010
  191. return (array) $array === $array;
  192. }
  193.  
  194. function select($db_name, $table_name, $columns_to_select, $where_statement, $where_values, $limit = null, $offset = null, $order = null) {
  195. if(db::fast_is_array($columns_to_select)&&db::fast_is_array($where_values)) {
  196. $sql = 'SELECT ';
  197. if($columns_to_select&&$columns_to_select!='*'&&!(count($columns_to_select)==1&&$columns_to_select[0]=='*')) {
  198. foreach($columns_to_select as $column_to_select) {
  199. $sql .= '`' . db::sanitize_input($column_to_select) . '`, ';
  200. }
  201. }
  202. else
  203. $sql .= '* ';
  204. $sql = substr($sql, 0, -2) . ' FROM `' . db::sanitize_input($db_name) . '`.`' . db::sanitize_input($table_name) . '` WHERE ' . replace_placeholders($where_statement, $where_values) . (isset($order) ? ' ORDER BY ' . db::sanitize_input($order) : '') . (isset($limit) ? ' LIMIT ' . abs($limit) : '') . (isset($offset) ? ' OFFSET ' . abs($offset) : '');
  205. $sql = mysql_query($sql, $GLOBALS['db']);
  206. if($sql&&mysql_num_rows($sql)>0) {
  207. $results = array();
  208. while($row = mysql_fetch_object($sql)) {
  209. $results[] = $row;
  210. }
  211. return $results;
  212. }
  213. else
  214. return mysql_error($GLOBALS['db']);
  215. }
  216. else
  217. return false;
  218. }
  219.  
  220. function insert_row($db_name, $table_name, $row) {
  221. if(db::fast_is_array($row)) {
  222. $columns = array_keys($row);
  223. $column_types = db::get_column_types($db_name, $table_name);
  224. $sql = 'INSERT INTO `' . db::sanitize_input($db_name) . '`.`' . db::sanitize_input($table_name) . '` (';
  225. foreach($columns as $column) {
  226. $sql .= '`' . db::sanitize_input($column) . '`, ';
  227. }
  228. $sql = substr($sql, 0, -2) . ') VALUES(';
  229. $i = 0;
  230. foreach($row as $value) {
  231. $value = db::sanitize_input($value);
  232. if(isset($column_types[1][$columns[$i]])) {
  233. $sql .= ((!is_numeric($value) && $column_types[1][$columns[$i]]) ? 'NULL' : ($column_types[1][$columns[$i]] ? $value : '\'' . $value . '\'')) . ', ';
  234. }
  235. $i++;
  236. }
  237. $sql = substr($sql, 0, -2) . ')';
  238. return mysql_query($sql, $GLOBALS['db']) ? mysql_insert_id($GLOBALS['db']) : mysql_error($GLOBALS['db']);
  239. }
  240. else
  241. return false;
  242. }
  243.  
  244. function update_row($db_name, $table_name, $update_values, $where_statement, $where_values) {
  245. if(db::fast_is_array($update_values)&&db::fast_is_array($where_values)) {
  246. $column_types = db::get_column_types($db_name, $table_name);
  247. if($column_types) {
  248. $sql = 'UPDATE `' . db::sanitize_input($db_name) . '`.`' . db::sanitize_input($table_name) . '` SET ';
  249. $update_columns = array_keys($update_values);
  250. $i = 0;
  251. foreach($update_values as $update_value) {
  252. if(isset($column_types[1][$update_columns[$i]])) {
  253. $update_value = db::sanitize_input($update_value);
  254. $sql .= '`' . db::sanitize_input($update_columns[$i]) . '` = ' . (substr($update_value, 0, 1) == '!' ? $update_value : ((!is_numeric($update_value) && $column_types[1][$update_columns[$i]]) ? 'NULL' : ($column_types[1][$update_columns[$i]] ? $update_value : '\'' . $update_value . '\''))) . ', ';
  255. }
  256. $i++;
  257. }
  258. $sql = substr($sql, 0, -2) . ' WHERE ' . replace_placeholders($where_statement, $where_values);
  259. mysql_query($sql, $GLOBALS['db']);
  260. $sql = mysql_affected_rows($GLOBALS['db']);
  261. return $sql > 0;//mysql_query($sql, $GLOBALS['db']) or mysql_error($GLOBALS['db']);
  262. }
  263. else
  264. return false;
  265. }
  266. else
  267. return false;
  268. }
  269.  
  270. function delete_row($db_name, $table_name, $where_statement, $where_values) {
  271. if(db::fast_is_array($where_values))
  272. return $db_name && $table_name && $where_statement && $where_values ? mysql_query('DELETE FROM `' . db::sanitize_input($db_name) . '`.`' . db::sanitize_input($table_name) . '` WHERE ' . replace_placeholders($where_statement, $where_values), $GLOBALS['db']) or mysql_error($GLOBALS['db']) : false;
  273. else
  274. return false;
  275. }
  276.  
  277. function get_column_types($db_name, $table_name) {
  278. $columns = mysql_query('SELECT COLUMN_NAME, data_type FROM information_schema.COLUMNS WHERE table_schema = \'' . db::sanitize_input($db_name) . '\' AND table_name = \'' . db::sanitize_input($table_name) . '\'');
  279. if($columns&&mysql_num_rows($columns)>0) {
  280. $column_types = array();
  281. $is_numeric = array();
  282. while($column = mysql_fetch_row($columns)) {
  283. $column_types[$column[0]] = $column[1];
  284. $is_numeric[$column[0]] = array_search($column[1], $GLOBALS['numeric_types']) ? true : false;
  285. }
  286. return array($column_types, $is_numeric);
  287. }
  288. else
  289. return mysql_error($GLOBALS['db']);
  290. }
  291.  
  292. function paginate($url, $pages_either_side, $current_page, $total_pages) {
  293. $pagination = "<ul class=\"pagination\">";
  294. if($current_page>1) {
  295. $pagination .= "<li><a href=\"" . str_replace('[PAGE]', $current_page - 1, $url) . "\">&laquo; Previous</a></li>\n";
  296. $pagination_pages = array();
  297. $i = $current_page - 1;
  298. while($i>$current_page-$pages_either_side&&$i>0) {
  299. $pagination_pages[] = "<li><a href=\"" . str_replace('[PAGE]', $i, $url) . "\">" . $i . "</a></li>\n";
  300. $i--;
  301. }
  302. $pagination .= implode("\n", array_reverse($pagination_pages));
  303. }
  304. else
  305. $pagination .= "<li><span>&laquo; Previous</span></li>\n";
  306. $pagination .= "<li><span class=\"selected\">" . $current_page . "</span></li>\n";
  307. if($current_page<$total_pages) {
  308. $i = $current_page + 1;
  309. while($i<=$total_pages&&$i<$current_page+$pages_either_side) {
  310. $pagination .= "<li><a href=\"" . str_replace('[PAGE]', $i, $url) . "\">" . $i . "</a></li>\n";
  311. $i++;
  312. }
  313. $pagination .= "<li><a href=\"" . str_replace('[PAGE]', $current_page + 1, $url) . "\">Next &raquo;</a></li>\n";
  314. }
  315. else
  316. $pagination .= "<li><span>Next &raquo;</span></li>\n";
  317. $pagination .= "</ul>\n";
  318. return $pagination;
  319. }
  320. }
  321.  
  322. $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
  323.  
  324. class user {
  325. function random_string($length) {
  326. $string = '';
  327. for($i=0;$i<$length;$i++) {
  328. $char = $GLOBALS['chars'][rand(0, count($GLOBALS['chars'])-1)];
  329. $string .= rand(0, 10) > 5 ? strtoupper($char) : $char;
  330. }
  331. return $string;
  332. }
  333.  
  334. function create($username, $password = null, $security_question = null, $security_question_answer = null, $email) {
  335. $salt = user::random_string(10);
  336. if($password&&$security_question&&$security_question_answer) {
  337. $password = $salt . sha1($salt.$username.$password.$email);
  338. $salt = user::random_string(10);
  339. $sqa = $salt . sha1($salt.$username.$security_question.$security_question_answer);
  340. $user_id = db::insert_row($GLOBALS['default_db_name'], 'users', array('username' => $username, 'password' => $password, 'security_question' => $security_question, 'security_question_answer' => $sqa, 'email' => $email, 'creation_date' => time()));
  341. session::set('message', 'Your account was created successfully.');
  342. }
  343. else {
  344. $password = $salt . sha1($salt.sha1(user::random_string(100).time()));
  345. $user_id = db::insert_row($GLOBALS['default_db_name'], 'users', array('username' => $username, 'password' => $password, 'email' => $email, 'creation_date' => time()));
  346. }
  347. return $user_id;
  348. }
  349.  
  350. function authenticate($username, $password) {
  351. $user = db::select($GLOBALS['default_db_name'], 'users', array('id', 'username', 'password', 'email'), 'username = \'?\' AND password = CONCAT(SUBSTRING(password, 1, 10), SHA1(CONCAT(SUBSTRING(password, 1, 10), username, \'?\', email)))', array($username, $password), 1, 0);
  352. return $user ? $user[0] : false;
  353. }
  354.  
  355. function login($username, $password) {
  356. session::restart();
  357. $user = user::authenticate($username, $password);
  358. if($user) {
  359. session::set('user_logged_in', $user->id);
  360. session::set('user_name', $user->username);
  361. }
  362. else {
  363. session::set('message', 'Your username or password was incorrect. Please try again.');
  364. }
  365. return $user ? true : false;
  366. }
  367.  
  368. function check_auth_status() {
  369. session::start();
  370. if(!session::exists('user_logged_in')) {
  371. session::set('message', 'You are not currently logged in.');
  372. print_r($_SESSION);
  373. header('Location: index.php');
  374. exit();
  375. }
  376. }
  377.  
  378. function delete($username, $password = null) {
  379. if($username) {
  380. $where_statement = 'username = \'?\'';
  381. $where_values = array($username);
  382. return $password&&user::authenticate($username, $password)||!$password ? db::delete_row($GLOBALS['default_db_name'], 'users', $where_statement, $where_values, 1) : false;
  383. }
  384. else
  385. return false;
  386. }
  387.  
  388. function update($user_id, $updated_values) {
  389. if(isset($updated_values['username'])&&isset($updated_values['password'])) {
  390. $user = user::authenticate($updated_values['username'], $updated_values['password']);
  391. if($user) {
  392. $salt = user::random_string(10);
  393. $updated_values['password'] = $salt . sha1($salt . (isset($updated_values['username']) ? $updated_values['username'] : $user[0]->username), $updated_values['password'] . (isset($updated_values['email']) ? $updated_values['email'] : $user[0]->email));
  394. $salt = user::random_string(10);
  395. $updated_values['security_question_answer'] = $salt . sha1($salt . (isset($updated_values['username']) ? $updated_values['username'] : $user[0]->username) . (isset($updated_values['security_question']) ? $updated_values['security_question'] : $user[0]->security_question) . $updated_values['security_question_answer']);
  396. return db::update_row($GLOBALS['default_db_name'], 'users', $updated_values, 'id = \'?\' AND username = \'?\' AND password = \'?\'', array($user[0]->id, $user[0]->username, $user[0]->password));
  397. }
  398. }
  399. }
  400. }
  401.  
  402. class chart {
  403. function new_piechart($width, $height, $values, $labels, $title, $three_d = false) {
  404. $total_value = array_sum($values);
  405. $piechart = imagecreatetruecolor(strlen($title) * 12 > $width ? strlen($title) * 12 : $width, $height + count($labels) * 10 + 25);
  406. imagefilledrectangle($piechart, 0, 0, imagesx($piechart), imagesy($piechart), imagecolorallocate($piechart, 255, 255, 255));
  407. imagettftext($piechart, 18, 0, 0, 18, null, 'C:/Windows/Fonts/arialbd.ttf', $title);
  408. $current_angle = 0;
  409. $colors = array();
  410. $colors_three_d = array();
  411. foreach($values as $value) {
  412. $colors_rgb = array(rand(50, 255), rand(50, 255), rand(50, 255));
  413. $colors_three_d[] = imagecolorallocate($piechart, $colors_rgb[0], $colors_rgb[1], $colors_rgb[2]);
  414. $colors[] = imagecolorallocate($piechart, $colors_rgb[0] - 50, $colors_rgb[1] - 50, $colors_rgb[2] - 50);
  415. imagefilledarc($piechart, $width/2 + 30, $height/3.5 + 55, $width/2, $height/2, $current_angle, $current_angle + $value / $total_value * 360, $colors[count($colors)-1], IMG_ARC_PIE);
  416. $current_angle += $value / $total_value * 360;
  417. }
  418. if($three_d) {
  419. /* START: Draw 3-D effect */
  420. for($i=$height/3.5+20;$i>$height/3.5;$i--) {
  421. $current_angle = 0;
  422. $n = 0;
  423. foreach($values as $value) {
  424. imagefilledarc($piechart, $width/2 + 30, $i+25, $width/2, $height/2, $current_angle, $current_angle + $value / $total_value * 360, $colors_three_d[$n], IMG_ARC_PIE);
  425. $current_angle += $value / $total_value * 360;
  426. $n++;
  427. }
  428. }
  429. /* START: End 3-D effect */
  430. }
  431. /* START: Draw legend */
  432. $y1 = $height / 2 + 70;
  433. $y2 = $height / 2 + 85;
  434. $padding_left = 30;
  435. for($i=0;$i<count($values);$i++) {
  436. imagefilledrectangle($piechart, $padding_left, $y1, $padding_left + 10, $y2, $colors[$i]);
  437. imagettftext($piechart, 10, 0, $padding_left + 20, $y2 - 1, $colors[$i], 'C:/Windows/Fonts/arialbd.ttf', $labels[$i] . ' (' . $values[$i] . ' / ' . round($values[$i] / $total_value * 100) . '%)');
  438. $y1 += 30;
  439. $y2 = $y1 + 15;
  440. }
  441. /* END: Draw legend */
  442. header('Content-Type: image/png');
  443. imagepng($piechart);
  444. imagedestroy($piechart);
  445. }
  446.  
  447. function new_barchart($bar_width, $height, $values, $labels, $axes, $max_value) {
  448. $barsets = array();
  449. $highest_values = array();
  450. $colors = array();
  451. //$colors_three_d = array();
  452. $sum = 0;
  453. $barcount = 0;
  454. $barchart = imagecreatetruecolor(1, 1);
  455. foreach($values as $set) {
  456. $i = 0;
  457. if(!isset($barsets[$i]))
  458. $barsets[$i] = array();
  459. for($i=0;$i<count($set);$i++) {
  460. $barsets[$i][] = $set[$i];
  461. $sum += $set[$i];
  462. $barcount++;
  463. }
  464. $colors_rgb = array(rand(25, 255), rand(25, 255), rand(25, 255));
  465. $colors[] = imagecolorallocate($barchart, $colors_rgb[0], $colors_rgb[1], $colors_rgb[2]);
  466. //$colors_three_d[] = imagecolorallocate($barchart, $colors_rgb[0] + 25, $colors_rgb[1] + 25, $colors_rgb[2] + 25);
  467. }
  468. imagedestroy($barchart);
  469. $barchart = imagecreatetruecolor(($bar_width + 30) * $barcount, $max_value + 200);
  470. imagefilledrectangle($barchart, 0, 0, imagesx($barchart), imagesy($barchart), imagecolorallocate($barchart, 255, 255, 255));
  471. /* START: Draw axes */
  472. imagesetthickness($barchart, 10);
  473. imageline($barchart, 50, 10, 50, 500, null);
  474. imagettftext($barchart, 14, 90, 20, strlen($axes[0]) * 10, null, 'C:/Windows/Fonts/arialbd.ttf', $axes[0]);
  475. /* END: Draw axes */
  476. sort($highest_values);
  477. $padding_left = 100;
  478. $x1 = $padding_left;
  479. $x2 = $padding_left + $bar_width;
  480. $y1 = 0;
  481. $y2 = $max_value;
  482. foreach($barsets as $barset) {
  483. $n = 0;
  484. foreach($barset as $value) {
  485. imagefilledrectangle($barchart, $x1, $max_value - $value, $x2, $max_value, $colors[$n]);
  486. $x1 += $bar_width;
  487. $x2 += $bar_width;
  488. $n++;
  489. }
  490. $x1 += 60;
  491. $x2 += 60;
  492. }
  493. /* START: Draw legend */
  494. $y1 = $y2 + 40;
  495. $y2 = $y1 + 30;
  496. for($i=0;$i<count($values);$i++) {
  497. imagefilledrectangle($barchart, $padding_left, $y1, $padding_left + 30, $y2, $colors[$i]);
  498. imagettftext($barchart, 14, 0, $padding_left + 40, $y2 - 6, $colors[$i], 'C:/Windows/Fonts/arialbd.ttf', $labels[$i]);
  499. $y1 += 50;
  500. $y2 = $y1 + 30;
  501. }
  502. /* END: Draw legend */
  503. header('Content-Type: image/png');
  504. imagepng($barchart);
  505. imagedestroy($barchart);
  506. }
  507. }
  508.  
  509. class file {
  510. function sanitize_path($path) {
  511. return preg_replace(array('/([\.]{2,})/', '/([.])\//'), '.', strip_tags($path));
  512. }
  513.  
  514. function resize_image($new_width, $new_height, $filename, $new_filename) {
  515. $path = '../../resized/' . file::sanitize_path($new_filename);
  516. $original_img = '../../uploads/' . file::sanitize_path($filename);
  517. if(file_exists($original_img)) { // just in case
  518. $mime_type = getimagesize($original_img);
  519. $mime_type = $mime_type['mime'];
  520. if($mime_type=='image/jpeg'||$mime_type=='image/png'||$mime_type=='image/gif'&&!file_exists($path)) { // resized image does not exist, and it the image to resize is either a JPEG, PNG, or GIF image; create it
  521. list($img_width, $img_height) = getimagesize($original_img);
  522. if($img_width>$new_width||$img_height>$new_height) {
  523. $ratio = $img_width / $img_height;
  524. if($new_width/$new_height>$ratio)
  525. $new_width = $new_height * $ratio;
  526. else
  527. $new_height = $new_width / $ratio;
  528. $resized_img = imagecreatetruecolor($new_width, $new_height);
  529. $extensions = array('jpeg', 'png', 'gif');
  530. $ext = $extensions[str_replace('jpg', 'jpeg', substr($filename, strrpos($filename, '.')+1))];
  531. switch(abs($ext)) {
  532. case 0:
  533. echo 'jpeg';
  534. $img = imagecreatefromjpeg($original_img);
  535. imagecopyresampled($resized_img, $img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
  536. imagejpeg($resized_img, $path, 100);
  537. break;
  538. case 1:
  539. $img = imagecreatefrompng($original_img);
  540. imagecopyresampled($resized_img, $img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
  541. imagepng($resized_img, $path, 9);
  542. break;
  543. case 2:
  544. $img = imagecreatefromgif($original_img);
  545. imagecopyresampled($resized_img, $img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
  546. imagegif($resized_img, $path);
  547. break;
  548. }
  549. }
  550. else
  551. copy($original_img, $path);
  552. }
  553. //unlink($original_img);
  554. }
  555. }
  556.  
  557. function upload() {
  558. $filename = basename($_FILES['upload']['name']);
  559. $uploaded_time = time();
  560. $uploaded_filename = '../../uploads/'.session::get('user_logged_in').'_'.sha1($filename.'_'.$uploaded_time.'_'.rand().'_'.filesize($_FILES['upload']['tmp_name']));
  561. if($_FILES['upload']['size']<=10485760) { // less than or equal to 10 MB
  562. $md5_img = md5_file($_FILES['upload']['tmp_name']);
  563. $image = db::select($GLOBALS['default_db_name'], 'images', array('name', 'filename', 'md5_hash'), 'md5_hash = \'?\' AND uploaded_by = ?', array($md5_img, session::get('user_logged_in')));
  564. if(!$image) { // file not already uploaded by user
  565. $mime_type = getimagesize($_FILES['upload']['tmp_name']);
  566. $mime_type = $mime_type['mime'];
  567. if($mime_type=='image/jpeg'||$mime_type=='image/png'||$mime_type=='image/gif') { // acceptable mime type
  568. if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploaded_filename)) { // file uploaded successfully
  569. $image_id = db::insert_row($GLOBALS['default_db_name'], 'images', array('name' => $filename, 'filename' => basename($uploaded_filename), 'mime_type' => $mime_type, 'size' => $_FILES['upload']['size'], 'uploaded_date' => $uploaded_time, 'uploaded_by' => session::get('user_logged_in'), 'md5_hash' => $md5_img));
  570. if($image_id) {
  571. session::set('message', 'The file was successfully uploaded.');
  572. return array($image_id, $uploaded_filename, $filename, $mime_type['mime']);
  573. }
  574. }
  575. else
  576. return false; // the image was not uploaded successfully
  577. }
  578. else
  579. return false;
  580. }
  581. else // the image already exists, so it was not reuploaded
  582. return array($image[0]->name, substr($image[0]->filename, strpos($image[0]->filename, '_') + 1));
  583. }
  584. else
  585. return false;
  586. }
  587.  
  588. function download_image($filename, $name, $inline, $resized) {
  589. $filename = file::sanitize_path($filename);
  590. $path = '../../'.(isset($resized)&&$resized?'resized':'uploads').'/'.session::get('user_logged_in').'_'.$filename;
  591. if(file_exists($path)) {
  592. $mime_type = getimagesize($path);
  593. header('Content-Type: '.$mime_type['mime']);
  594. header('Content-Disposition: '.(isset($inline)&&$inline?'inline':'attachment').'; filename='.$name);
  595. header('Content-Length: '.filesize($path));
  596. readfile($path);
  597. }
  598. }
  599. }
  600.  
  601. class search {
  602. function edge_of_word($text, $position, $left = false) {
  603. $first_space = strpos($text, ' ');
  604. if(!$left&&$first_space!==false&&$position<$first_space)
  605. $position = $first_space;
  606. $last_space = strrpos($text, ' ');
  607. if($last_space!==false&&$position>$last_space)
  608. $position = $left ? $last_space : strlen($text);
  609. if(strpos($text, ' ', $position)!==false) {
  610. while($text[$position]!=' '&&((!$left&&$position<strlen($text))||($left&&$position>0))) {
  611. $position += $left ? -1 : 1;
  612. }
  613. }
  614. return $position;
  615. }
  616.  
  617. function find_adjacent_words($text, $position, $word_count, $left, $positions_only = false) {
  618. if($left===3) {
  619. $adjacent_words = array();
  620. $adjacent_words[] = search::find_adjacent_words($text, $position, $word_count, true, $positions_only);
  621. $adjacent_words[] = search::find_adjacent_words($text, $position, $word_count, false, $positions_only);
  622. return $adjacent_words;
  623. }
  624. else {
  625. $position = search::edge_of_word($text, $position, $left);
  626. $original_position = $position;
  627. $current_word_count = 0;
  628. while((($left&&$position>0)||(!$left&&$position<strlen($text)))&&$current_word_count<=$word_count) {
  629. if($text[$position]==' ')
  630. $current_word_count++;
  631. $position += $left ? -1 : 1;
  632. }
  633. $start_position = $left ? $position == 0 && $text[0] != ' ' ? $position : $position + 1 : $original_position;
  634. $length_of_words = $left ? $original_position - $position : $position - $original_position;
  635. return $positions_only ? array($start_position, $length_of_words) : trim(substr($text, $start_position, $length_of_words));
  636. }
  637. }
  638.  
  639. function index_search_terms($original_keywords, $new_keywords, $item_id, $item_type, $is_image = null) {
  640. if(search::item_type_valid($item_type)!==false) {
  641. $new_keywords = preg_replace('/<[^>]+?>/', ' ', $new_keywords);
  642. $new_keywords = preg_replace('/\s{2,}/', ' ', $new_keywords);
  643. $new_keywords_lowercase = strtolower($new_keywords);
  644. $all_words = preg_replace('/[^A-Za-z0-9]/', ' ', $new_keywords_lowercase);
  645. $all_words = str_replace('_', ' ', $all_words);
  646. $all_words = explode(' ', $all_words);
  647. $occurrences = array();
  648. foreach($all_words as $keyword) {
  649. if(isset($occurrences[$keyword]))
  650. $occurrences[$keyword]++;
  651. else
  652. $occurrences[$keyword] = 1;
  653. }
  654. $keywords = array_unique($all_words);
  655. foreach($keywords as $keyword) {
  656. if(trim($keyword)) {
  657. $kword_added = 0;
  658. $keyword_first_index = strpos($new_keywords_lowercase, $keyword);
  659. $extract = search::find_adjacent_words($new_keywords, $keyword_first_index, 10, 3, true);
  660. $values = array('occurrences' => $occurrences[$keyword], 'extract_start' => $extract[0][0], 'extract_end' => $extract[1][1]);
  661. if(!$is_image||($is_image&&$is_image==false))
  662. $values['extract'] = trim(substr($new_keywords, $extract[0][0], $extract[0][1]) . substr($new_keywords, $extract[0][0] + $extract[0][1], $extract[1][0] - ($extract[0][0] + $extract[0][1])) . substr($new_keywords, $extract[1][0], $extract[1][1]));
  663. if(db::select($GLOBALS['default_db_name'], 'search_results', array('id'), 'keyword = \'?\' AND created_by = ? AND item_id = ? AND item_type = \'?\'', array($keyword, session::get('user_logged_in'), $item_id, $item_type), 1))
  664. db::update_row($GLOBALS['default_db_name'], 'search_results', $values, 'keyword = \'?\' AND created_by = ? AND item_id = ? AND item_type = \'?\'', array($keyword, session::get('user_logged_in'), $item_id, $item_type));
  665. else {
  666. $values['keyword'] = trim($keyword);
  667. $values['created_by'] = session::get('user_logged_in');
  668. $values['item_id'] = $item_id;
  669. $values['item_type'] = $item_type;
  670. db::insert_row($GLOBALS['default_db_name'], 'search_results', $values);
  671. }
  672. }
  673. }
  674. if($original_keywords!=null) {
  675. $original_keywords = preg_replace('/<[^>]+?>/', ' ', strtolower($original_keywords));
  676. $original_keywords = preg_replace('/[^A-Za-z0-9]/', ' ', $original_keywords);
  677. $original_keywords = explode(' ', $original_keywords);
  678. $deleted_keywords = array_diff($original_keywords, $keywords);
  679. foreach($deleted_keywords as $deleted_keyword) {
  680. db::delete_row($GLOBALS['default_db_name'], 'search_results', 'keyword = \'?\' AND created_by = ? AND item_id = ? AND item_type = \'?\'', array($deleted_keyword, session::get('user_logged_in'), $item_id, $item_type));
  681. }
  682. }
  683. if(db::select($GLOBALS['default_db_name'], 'keyword_counts', array('id'), 'item_id = ? AND item_type = \'?\' AND created_by = ?', array($item_id, $item_type, session::get('user_logged_in'))))
  684. db::update_row($GLOBALS['default_db_name'], 'keyword_counts', array('keyword_count' => count($all_words)), 'item_id = ? AND item_type = \'?\' AND created_by = ?', array($item_id, $item_type, session::get('user_logged_in')));
  685. else
  686. db::insert_row($GLOBALS['default_db_name'], 'keyword_counts', array('keyword_count' => count($all_words), 'item_id' => $item_id, 'item_type' => $item_type, 'created_by' => session::get('user_logged_in')));
  687. }
  688. }
  689.  
  690. function item_type_valid($item_type) {
  691. return array_search($item_type, $GLOBALS['item_types']);
  692. }
  693.  
  694. function delete_search_terms($item_id, $item_type) {
  695. if(search::item_type_valid($item_type)!==false) {
  696. $search_results = db::select($GLOBALS['default_db_name'], 'search_results', array('id'), 'item_id = ? AND item_type = \'?\' AND created_by = ?', $item_id, $item_type, session::get('user_logged_in'));
  697. if($search_results) {
  698. foreach($search_results as $search_result) {
  699. db::delete_row($GLOBALS['default_db_name'], 'search_results', 'id = ? AND created_by = ?', array($search_result->id, session::get('user_logged_in')));
  700. }
  701. $keyword_count = db::select($GLOBALS['default_db_name'], 'search_results', array('item_id = ? AND item_type = \'?\' AND created_by = ?', $item_id, $item_type, session::get('user_logged_in')));
  702. db::delete_row($GLOBALS['default_db_name'], 'search_results', 'item_id = ? AND item_type = ? AND created_by = \'?\'', array($item_id, $item_type, session::get('user_logged_in')));
  703. }
  704. }
  705. }
  706.  
  707. function find() {
  708. $error_message = '';
  709. if(!isset($_GET['item_type'])||trim($_GET['item_type'])=='')
  710. $_GET['item_type'] = 'document';
  711. if(trim($_GET['keywords'])!=''&&(search::item_type_valid($_GET['item_type']||$_GET['item_type']=='all'))) {
  712. $keywords = preg_replace('/[^A-Za-z0-9]/', ' ', $_GET['keywords']);
  713. $keywords = explode(' ', $keywords);
  714. if($keywords&&count($keywords)>0) {
  715. /*$stop_words = array('the', 'of', 'from', 'to', 'and', 'an', 'a', 'in', 'its', 'is', 'it', 'at', 'this');
  716. foreach($stop_words as $stop_word) {
  717. $index = array_search($stop_word, $keywords);
  718. if($index!==false)
  719. unset($keywords[$index]);
  720. }*/
  721. $sql = 'SELECT id, keyword, item_id, item_type, created_by, extract, extract_start, extract_end, EXP(SUM(LN((SELECT keyword_count FROM keyword_counts WHERE item_id = t.item_id AND created_by = ? AND item_type = \'t.item_type\')/occurrences)))/100000 AS keyword_density_product FROM (SELECT * FROM search_results WHERE (';
  722. $count_sql = 'SELECT COUNT(1) AS result_count FROM (SELECT 1 FROM search_results WHERE (';
  723. $query = array();
  724. $count_query = array();
  725. foreach($keywords as $keyword) {
  726. $sql .= 'keyword = \'?\' OR ';
  727. $count_sql .= 'keyword = \'?\' OR ';
  728. }
  729. $sql = substr($sql, 0, count($sql)-5) . ') AND created_by = ? AND item_type = \'?\') t GROUP BY item_id ORDER BY keyword_density_product DESC LIMIT 5 OFFSET ?';
  730. $count_sql = substr($count_sql, 0, count($count_sql)-5) . ') AND created_by = ? AND item_type = \'?\' GROUP BY item_id) t';
  731. $query[] = session::get('user_logged_in');
  732. foreach($keywords as $keyword) {
  733. $keyword_lowercase = strtolower($keyword);
  734. $query[] = $keyword_lowercase;
  735. $count_query[] = $keyword_lowercase;
  736. }
  737. $query[] = session::get('user_logged_in');
  738. $query[] = $_GET['item_type'];
  739. $count_query[] = session::get('user_logged_in');
  740. $count_query[] = $_GET['item_type'];
  741. $pagination_page = isset($_GET['page']) ? $_GET['page'] : 1;
  742. $pagination_offset = ($pagination_page * 5) - 5;
  743. $query[] = $pagination_offset;
  744. $results = mysql_query(replace_placeholders($sql, $query));
  745. $total_result_count = mysql_query($count_sql, $count_query);
  746. $max_pages = ceil($total_result_count);
  747. }
  748. else
  749. $error_message = 'Your search query was invalid. Please try again.';
  750. }
  751. else {
  752. session::set('message', 'Error performing search');
  753. header('Location: http://localhost/write/document.php');
  754. }
  755. }
  756.  
  757. if(!(isset($bypass)&&($bypass=='signup'||$bypass=='index'||$bypass=='error'))) user::check_auth_status();
  758. ?>

Report this snippet  

You need to login to post a comment.