misc.inc

  1. 6.x includes/misc.inc
  2. 7.x includes/misc.inc
  3. 4.x includes/misc.inc
  4. 5.x includes/misc.inc

This file contains misc functions for FlightPath

File

includes/misc.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * This file contains misc functions for FlightPath
  5. */
  6. /**
  7. * Returns back the "friendly" timezone string if we have one.
  8. */
  9. function friendly_timezone($str) {
  10. $arr = array(
  11. 'America/Chicago' => 'Central Time - US & Canada',
  12. 'America/Los_Angeles' => 'Pacific Time - US & Canada',
  13. 'America/New_York' => 'Eastern Time - US & Canada',
  14. 'America/Denver' => 'Mountain Time - US & Canada',
  15. 'America/Phoenix' => 'Arizona Time',
  16. 'America/Anchorage' => 'Alaska Time',
  17. 'America/Adak' => 'Hawaii Time',
  18. 'Pacific/Honolulu' => 'Hawaii Time no DST',
  19. );
  20. if (isset($arr[$str])) return $arr[$str];
  21. return $str;
  22. }
  23. /**
  24. * Adding fp_trim function for backwards compatibility with FP 7
  25. */
  26. function fp_trim($str) {
  27. return trim($str);
  28. }
  29. // source: Laravel Framework
  30. // (helper functions if we are not running PHP 8.)
  31. // https://github.com/laravel/framework/blob/8.x/src/Illuminate/Support/Str.php
  32. if (!function_exists('str_starts_with')) {
  33. function str_starts_with($haystack, $needle) {
  34. return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
  35. }
  36. }
  37. if (!function_exists('str_ends_with')) {
  38. function str_ends_with($haystack, $needle) {
  39. return $needle !== '' && substr($haystack, -strlen($needle)) === (string)$needle;
  40. }
  41. }
  42. if (!function_exists('str_contains')) {
  43. function str_contains($haystack, $needle) {
  44. return $needle !== '' && mb_strpos($haystack, $needle) !== false;
  45. }
  46. }
  47. /**
  48. * Returns back a FAPI-compatible array of all term codes for the specified years, inclusive
  49. */
  50. function fp_get_terms_by_year_range($start_year, $end_year, $school_id = 0, $bool_include_term_id_in_description = TRUE) {
  51. // Let the user select a term for this school (starting at now - $min years, and going out to now + max years)
  52. $options = array();
  53. $temp = get_term_structures($school_id);
  54. for ($year = $start_year; $year <= $end_year; $year++) {
  55. foreach ($temp as $k => $details) {
  56. $term_id = $year . $k;
  57. // Adding year as the first element causes it to separate out the terms by year in the pulldown. Makes it cleaner.
  58. $options[$year][$term_id] = "[$term_id] &nbsp;" . get_term_description($term_id, FALSE, $school_id);
  59. if (!$bool_include_term_id_in_description) {
  60. $options[$year][$term_id] = get_term_description($term_id, FALSE, $school_id);
  61. }
  62. }
  63. } //for t
  64. ksort($options);
  65. return $options;
  66. }
  67. /**
  68. * Returns an array (suitable for form api) of departments on campus which
  69. * faculty/staff can be members of.
  70. */
  71. function fp_get_departments($school_id = 0, $bool_get_all_by_schools = FALSE) {
  72. $rtn = array();
  73. $cache_key = md5(serialize(func_get_args()));
  74. // Get from cache if already loaded once this page load
  75. if (isset($GLOBALS['fp_cache_departments'][$cache_key])) {
  76. return $GLOBALS['fp_cache_departments'][$cache_key];
  77. }
  78. if (!$bool_get_all_by_schools) {
  79. $val = variable_get_for_school('departments', '', $school_id);
  80. $lines = explode("\n", $val);
  81. foreach ($lines as $line) {
  82. $line = trim($line);
  83. if (!$line) continue;
  84. $temp = explode("~", $line);
  85. $rtn[trim($temp[0])] = trim($temp[1]);
  86. }
  87. }
  88. else if (module_enabled('schools') && $bool_get_all_by_schools == TRUE) {
  89. // We should return a multi-dimensional array where the school name is first, followed by dept_code.
  90. // Ex: $rtn['SCHOOL_ABC']['ENGL'] = "English";
  91. // We would need to go through all of our schools in a for loop first.
  92. $schools = schools_get_school_definitions();
  93. foreach ($schools as $school_id => $throw_away) {
  94. $school_code = schools_get_school_code_for_id($school_id);
  95. if ($school_id == 0) $school_code = "- Default -";
  96. $val = variable_get_for_school('departments', '', $school_id);
  97. $lines = explode("\n", $val);
  98. foreach ($lines as $line) {
  99. $line = trim($line);
  100. if (!$line) continue;
  101. $temp = explode("~", $line);
  102. $rtn[$school_code][trim($temp[0])] = trim($temp[1]);
  103. }
  104. }
  105. }
  106. $GLOBALS['fp_cache_departments'][$cache_key] = $rtn; // store in cache
  107. return $rtn;
  108. }
  109. /**
  110. * This function will use the "Numeric to Letter Grade" setting in the School settings to
  111. * translate the given grade (if it is numeric) to a letter grade. Otherwise, it will return
  112. * the grade as-is.
  113. */
  114. function fp_translate_numeric_grade($grade, $school_id = 0) {
  115. $only_grade = $grade;
  116. // We may have included MID at the end of our numeric grade, and if so, it's a midterm grade.
  117. $bool_midterm = FALSE;
  118. if (strstr($grade, "MID")) {
  119. $bool_midterm = TRUE;
  120. $only_grade = trim(str_replace("MID", "", $grade));
  121. }
  122. if (!is_numeric($only_grade)) return $grade; // already a letter, return the original grade.
  123. $translate = array();
  124. // Get our translation array from globals cache, if there.
  125. if (isset($GLOBALS['fp_translate_numeric_grade'][$school_id])) {
  126. $translate = $GLOBALS['fp_translate_numeric_grade'][$school_id];
  127. }
  128. else {
  129. $temp = trim(variable_get_for_school("numeric_to_letter_grades", "", $school_id));
  130. if ($temp === '') return $grade;
  131. $temp = explode("\n", $temp);
  132. foreach ($temp as $line) {
  133. $line = trim($line);
  134. if ($line == "") continue;
  135. $tokens = explode("~", $line);
  136. $low = floatval(trim($tokens[0]));
  137. $high = floatval(trim($tokens[1]));
  138. $letter = trim($tokens[2]);
  139. $translate[$low][$high] = $letter;
  140. } // foreach
  141. $GLOBALS['fp_translate_numeric_grade'][$school_id] = $translate;
  142. }
  143. // Okay, now that we have our "translate" array, we can do that with the grade.
  144. $grade = floatval($grade);
  145. foreach ($translate as $low => $details) {
  146. foreach ($translate[$low] as $high => $letter) {
  147. if ($grade >= $low && $grade <= $high) {
  148. if ($bool_midterm) $letter .= "MID";
  149. return $letter;
  150. }
  151. }
  152. }
  153. // Else, return back the original grade.
  154. return $grade;
  155. }
  156. /**
  157. * Re-order the _FILES array for multiple files, to make it easier to work with. From:
  158. * http://php.net/manual/en/features.file-upload.multiple.php
  159. *
  160. * To use:
  161. * $myfiles = fp_re_array_files($_FILES['fieldname'])
  162. *
  163. *
  164. */
  165. function fp_re_array_files($file_post) {
  166. $file_ary = array();
  167. $file_count = count($file_post['name']);
  168. $file_keys = array_keys($file_post);
  169. for ($i=0; $i<$file_count; $i++) {
  170. foreach ($file_keys as $key) {
  171. $file_ary[$i][$key] = $file_post[$key][$i];
  172. }
  173. }
  174. return $file_ary;
  175. }
  176. // From: https://www.php.net/manual/en/function.timezone-offset-get.php
  177. /** Returns the offset from the origin timezone to the remote timezone, in seconds.
  178. * @param $remote_tz;
  179. * @param $origin_tz; If null the servers current timezone is used as the origin.
  180. * @return int;
  181. */
  182. function get_timezone_offset($remote_tz, $origin_tz = null) {
  183. if($origin_tz === null) {
  184. if(!is_string($origin_tz = date_default_timezone_get())) {
  185. return false; // A UTC timestamp was returned -- bail out!
  186. }
  187. }
  188. $origin_dtz = new DateTimeZone($origin_tz);
  189. $remote_dtz = new DateTimeZone($remote_tz);
  190. $origin_dt = new DateTime("now", $origin_dtz);
  191. $remote_dt = new DateTime("now", $remote_dtz);
  192. $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
  193. return $offset;
  194. }
  195. /**
  196. *
  197. * From: https://stackoverflow.com/questions/1369936/check-to-see-if-a-string-is-serialized
  198. *
  199. *
  200. * Check if a string is serialized
  201. *
  202. * @param string $string
  203. *
  204. * @return bool
  205. */
  206. function is_serialized_string($string)
  207. {
  208. return ($string == 'b:0;' || @unserialize($string) !== false);
  209. }
  210. // From: https://gist.github.com/ryanboswell/cd02add580ddce012469
  211. /**
  212. * The point of this function is to convert between UTC (what we expect all times to start with.). If we're coming
  213. * from the the database or a time() function, it's UTC. The "end_timezone_string" should be the user's preferred timezone.
  214. *
  215. * if end_timezone_string == null, then we will use the user's selected timezone. If that isn't set, we use they system's.
  216. *
  217. * As a convenenience, if the data_format we will get back a formatted date. Otherwise we'll get back a timestamp.
  218. */
  219. function convert_time($time_to_convert = 0, $start_timezone_string = "UTC", $end_timezone_string = NULL, $date_format = null ) {
  220. // We require a start time
  221. if( empty( $time_to_convert ) ){
  222. return false;
  223. }
  224. if ($end_timezone_string == NULL) {
  225. $end_timezone_string = fp_get_user_timezone();
  226. }
  227. // If the two timezones are different, find the offset
  228. if( $start_timezone_string != $end_timezone_string ) {
  229. // Create two timezone objects, one for the start and one for
  230. // the end
  231. $dateTimeZoneStart = new DateTimeZone( $start_timezone_string );
  232. $dateTimeZoneEnd = new DateTimeZone( $end_timezone_string );
  233. // Create two DateTime objects that will contain the same Unix timestamp, but
  234. // have different timezones attached to them.
  235. $dateTimeStart = new DateTime("now", $dateTimeZoneStart );
  236. $dateTimeEnd = new DateTime("now", $dateTimeZoneEnd );
  237. // Calculate the UTC offset for the date/time contained in the $dateTimeStart
  238. // object, but using the timezone rules as defined for the end timezone ($dateTimeEnd)
  239. $timeOffset = $dateTimeZoneEnd->getOffset($dateTimeStart);
  240. // If we are converting FROM non-utc TO UTC, then this logic doesn't work!
  241. // We need to basically grab the reverse logic...
  242. if ($start_timezone_string != 'UTC' && $end_timezone_string == 'UTC') {
  243. $x = $dateTimeZoneStart->getOffset($dateTimeEnd);
  244. $timeOffset = -$x;
  245. }
  246. } else {
  247. // If the timezones are the same, there is no offset
  248. $timeOffset = 0;
  249. }
  250. // Convert the time by the offset
  251. $converted_time = $time_to_convert + $timeOffset;
  252. // If we have no given format, just return the time
  253. if( empty( $date_format ) ) {
  254. return $converted_time;
  255. }
  256. // Convert to the given date format
  257. return date( $date_format, $converted_time );
  258. }
  259. /**
  260. * Returns an array of all timezones PHP recognizes.
  261. * Inspired by code from: https://stackoverflow.com/questions/1727077/generating-a-drop-down-list-of-timezones-with-php
  262. *
  263. * This code will return the common US timezones first, followed by the rest of the timezones that PHP is aware of.
  264. *
  265. */
  266. function get_timezones($bool_include_offset = FALSE) {
  267. $timezones = array();
  268. // These are the common names for the US timezones.
  269. $us_desc_timezones = array(
  270. 'America/New_York' => 'Eastern',
  271. 'America/Chicago' => 'Central',
  272. 'America/Denver' => 'Mountain',
  273. 'America/Phoenix' => 'Mountain no DST',
  274. 'America/Los_Angeles' => 'Pacific',
  275. 'America/Anchorage' => 'Alaska',
  276. 'America/Adak' => 'Hawaii',
  277. 'Pacific/Honolulu' => 'Hawaii no DST',
  278. );
  279. $us_timezones = array_keys($us_desc_timezones);
  280. $timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
  281. // Place the US timezones at the top of the list.
  282. $timezones = array_merge($us_timezones, $timezones);
  283. $timezone_offsets = array();
  284. foreach( $timezones as $timezone )
  285. {
  286. $tz = new DateTimeZone($timezone);
  287. $timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
  288. }
  289. $timezone_list = array();
  290. foreach( $timezone_offsets as $timezone => $offset )
  291. {
  292. $offset_prefix = $offset < 0 ? '-' : '+';
  293. $offset_formatted = gmdate( 'H:i', abs($offset) );
  294. $pretty_offset = $extra = "";
  295. if ($bool_include_offset) $pretty_offset = "(UTC${offset_prefix}${offset_formatted}) ";
  296. if (isset($us_desc_timezones[$timezone])) {
  297. $extra = " - (" . $us_desc_timezones[$timezone] . ")";
  298. }
  299. $disp_timezone = str_replace("_", " ", $timezone);
  300. $timezone_list[$timezone] = "$pretty_offset$disp_timezone$extra";
  301. }
  302. return $timezone_list;
  303. }
  304. /**
  305. * This is our custom error handler, which will intercept PHP warnings, notices, etc, and let us
  306. * display them, log them, etc.
  307. *
  308. * See https://www.php.net/manual/en/function.set-error-handler.php
  309. */
  310. function _fp_error_handler($error_level, $message, $filename, $line, $context = array()) {
  311. global $user;
  312. // In case we have not loaded bootstrap.inc yet.
  313. @define ('WATCHDOG_NOTICE', 5);
  314. @define ('WATCHDOG_ALERT', 1);
  315. @define ('WATCHDOG_ERROR', 3);
  316. @define ('WATCHDOG_DEBUG', 7);
  317. $PHP_8_0_SUPPRESSED_ERROR = E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE;
  318. $er = error_reporting();
  319. if ($er === 0 || $er === $PHP_8_0_SUPPRESSED_ERROR) { return false;} // suppressed with @-operator (0 for pre-php8, the variable for 8.0)
  320. $err_name = _fp_map_php_error_code($error_level);
  321. if (is_string($err_name) && stristr($err_name, 'notice')) return FALSE; // don't care about Notices.
  322. $watchdog_type = "php_error";
  323. $watchdog_severity = WATCHDOG_ERROR;
  324. if (is_string($err_name) && stristr($err_name, 'warning')) {
  325. $watchdog_type = "php_warning";
  326. $watchdog_severity = WATCHDOG_ALERT;
  327. }
  328. if (is_string($err_name) && stristr($err_name, 'recoverable error')) {
  329. $watchdog_type = "php_warning";
  330. $watchdog_severity = WATCHDOG_ALERT;
  331. }
  332. $arr = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 10); // limit of 10 levels deep so as not to eat up all the memory.
  333. // fpm() only displays for privileged users
  334. // We don't want to bother repeating the same message more than once for errors. The following code
  335. // will prevent that.
  336. // TODO: Make this a setting?
  337. $errmsg = $err_name . ": $message<br>... ($line) $filename";
  338. $errmsg_hash = hash('sha256', $errmsg);
  339. if (!isset($GLOBALS['fp_error_handler__already_shown_error'][$errmsg_hash])) {
  340. fpm($errmsg);
  341. fpm($arr);
  342. $GLOBALS['fp_error_handler__already_shown_error'][$errmsg_hash] = TRUE;
  343. }
  344. else {
  345. return; // we've already displayed this error message; we can harmlessly return.
  346. }
  347. // Before we watchdog or mail this backtrace, make sure no field called "password" is in plain text.
  348. foreach ($arr as $c => $trace) {
  349. if (is_array($trace) && isset($trace['args'])) {
  350. foreach ($trace['args'] as $k => $details) {
  351. if (is_array($details)) {
  352. foreach ($details as $j => $val) {
  353. if (stristr($j, 'password')) {
  354. $arr[$c]['args'][$k][$j] = "--PASSWORD HIDDEN IN LOG--";
  355. }
  356. }
  357. }
  358. }
  359. }
  360. }
  361. $hostname = php_uname('n') . ' - ' . $GLOBALS['fp_system_settings']['base_url'];
  362. $msg = "";
  363. $msg .= "USER: $user->name ($user->id) \n";
  364. $msg .= "SERVER: $hostname \n";
  365. $msg .= "DATE: " . format_date(convert_time(time())) . "\n";
  366. $msg .= "SEVERITY: $err_name \n";
  367. $msg .= "--------------------------\n\n";
  368. $msg .= "$err_name: $message \n\n";
  369. $msg .= "... ($line) $filename\n\n";
  370. $msg .= "Backtrace: <pre>\n";
  371. $msg .= print_r($arr, TRUE);
  372. $msg .= "\n\n</pre>";
  373. // Because we can have EXTREMELY long $msg due to the backtrace, limit it to a reasonable number.
  374. if (strlen($msg) > 10000) {
  375. $msg = substr($msg, 0, 10000) . "\n\n\n... truncated to 10,000 characters to save space. Full length was: " . strlen($msg);
  376. }
  377. watchdog($watchdog_type, $msg, array(), $watchdog_severity);
  378. if (@intval($user->id) !== 0) {
  379. // We are NOT the admin user. (No need to email, since it would appear on screen with the fpm() calls earlier.
  380. // Should we email someone, as with mysql errors?
  381. $tomail = trim(variable_get("notify_php_error_email_address", ""));
  382. if ($tomail != "") {
  383. fp_mail($tomail, "PHP Error in FlightPath", $msg);
  384. }
  385. }
  386. } // _fp_error_handler
  387. /**
  388. * Map an error code into an Error word
  389. *
  390. * @param int $code Error code to map
  391. * @return array Array of error word, and log location.
  392. */
  393. function _fp_map_php_error_code($code) {
  394. $error = '';
  395. switch ($code) {
  396. case E_PARSE:
  397. case E_ERROR:
  398. case E_CORE_ERROR:
  399. case E_COMPILE_ERROR:
  400. case E_USER_ERROR:
  401. $error = 'Fatal Error';
  402. break;
  403. case E_WARNING:
  404. case E_USER_WARNING:
  405. case E_COMPILE_WARNING:
  406. case E_RECOVERABLE_ERROR:
  407. $error = 'Warning';
  408. break;
  409. case E_NOTICE:
  410. case E_USER_NOTICE:
  411. $error = 'Notice';
  412. break;
  413. case E_STRICT:
  414. $error = 'Strict';
  415. break;
  416. case E_DEPRECATED:
  417. case E_USER_DEPRECATED:
  418. $error = 'Deprecated';
  419. break;
  420. default :
  421. break;
  422. }
  423. return $error;
  424. }
  425. /**
  426. * Send an email. Drop-in replacement for PHP's mail() command,
  427. * but can use SMTP protocol if enabled.
  428. *
  429. * For attachments (only for use in SMTP), the array can be one of two methods:
  430. *
  431. * (1)
  432. * $arr["full_filename"] => "filename"
  433. * or
  434. * (2)
  435. * $arr['filename'] = "string that makes up attachment"
  436. *
  437. * For method #2, $bool_string_attachment must be set to TRUE.
  438. *
  439. */
  440. function fp_mail($to, $subject, $msg, $bool_html = FALSE, $attachments = array(), $bool_string_attachment = FALSE) {
  441. // TODO: In the future, check to see if there are any other modules which invoke a hook to intercept mail.
  442. // The reason we do this md5 check is so that we don't try to send identical emails over and over. This can happen if we are trying
  443. // to email regarding the mysql server being down, and when we try to do a "watchdog", which has to use the mysql server,
  444. // we try to send ANOTHER error, then we are right back here and try to send ANOTHER email, etc, etc.
  445. $md5_check = md5($to . $subject . $msg . time());
  446. if (isset($_SESSION['fp_mail_last_sent_md5'])) {
  447. if ($_SESSION['fp_mail_last_sent_md5'] == $md5_check) {
  448. return;
  449. }
  450. }
  451. $_SESSION['fp_mail_last_sent_md5'] = $md5_check;
  452. watchdog('fp_mail', t("Sending mail to @to, subject: @subject. Last sent md5: @md5", array("@to" => $to, "@subject" => $subject, "@md5" => $md5_check)), array(), WATCHDOG_DEBUG);
  453. if (module_enabled('smtp')) {
  454. smtp_mail($to, $subject, $msg, $bool_html, $attachments, $bool_string_attachment);
  455. return;
  456. }
  457. else {
  458. $headers = array();
  459. if ($bool_html) {
  460. // To send HTML mail, the Content-type header must be set
  461. $headers[] = 'MIME-Version: 1.0';
  462. $headers[] = 'Content-type: text/html; charset=iso-8859-1';
  463. }
  464. mail($to, $subject, $msg, implode("\r\n", $headers));
  465. }
  466. } // fp_mail
  467. /**
  468. * Returns the component of the page's path.
  469. *
  470. * When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".
  471. *
  472. */
  473. function arg($index) {
  474. $q = $_REQUEST["q"];
  475. $temp = explode("/", $q);
  476. $rtn = @trim($temp[$index]);
  477. return $rtn;
  478. }
  479. /**
  480. * This function uses CURL to get the simple contents of a URL, whether http or https.
  481. */
  482. function fp_url_get_contents($url) {
  483. /*
  484. $ch = curl_init();
  485. curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
  486. curl_setopt( $ch, CURLOPT_HEADER, 0 );
  487. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  488. curl_setopt( $ch, CURLOPT_URL, $url );
  489. curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
  490. $data = curl_exec( $ch );
  491. curl_close( $ch );
  492. return $data;
  493. */
  494. // Make use of the superior fp_http_request instead.
  495. $res = fp_http_request($url);
  496. if (is_object($res) && isset($res->data)) {
  497. return $res->data;
  498. }
  499. return FALSE;
  500. }
  501. /**
  502. * Send a request through the Internet and return the result as an object.
  503. *
  504. * This is a modified copy of the Drupal 6 function drupal_http_request(),
  505. * taken from here: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request/6
  506. */
  507. function fp_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3, $timeout = 30.0) {
  508. global $db_prefix;
  509. $result = new stdClass();
  510. // Parse the URL and make sure we can handle the schema.
  511. $uri = parse_url($url);
  512. if ($uri == FALSE) {
  513. $result->error = 'unable to parse URL';
  514. $result->code = -1001;
  515. return $result;
  516. }
  517. if (!isset($uri['scheme'])) {
  518. $result->error = 'missing schema';
  519. $result->code = -1002;
  520. return $result;
  521. }
  522. timer_start(__FUNCTION__);
  523. switch ($uri['scheme']) {
  524. case 'http':
  525. case 'feed':
  526. $port = isset($uri['port']) ? $uri['port'] : 80;
  527. $host = $uri['host'] . ($port != 80 ? ':' . $port : '');
  528. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, $timeout);
  529. break;
  530. case 'https':
  531. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  532. $port = isset($uri['port']) ? $uri['port'] : 443;
  533. $host = $uri['host'] . ($port != 443 ? ':' . $port : '');
  534. $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, $timeout);
  535. break;
  536. default:
  537. $result->error = 'invalid schema ' . $uri['scheme'];
  538. $result->code = -1003;
  539. return $result;
  540. }
  541. // Make sure the socket opened properly.
  542. if (!$fp) {
  543. // When a network error occurs, we use a negative number so it does not
  544. // clash with the HTTP status codes.
  545. $result->code = -$errno;
  546. $result->error = trim($errstr);
  547. // Log that this failed.
  548. watchdog("http_request", "fp_http_request failed! Perhaps the server cannot make requests?", array(), WATCHDOG_ERROR);
  549. return $result;
  550. }
  551. // Construct the path to act on.
  552. $path = isset($uri['path']) ? $uri['path'] : '/';
  553. if (isset($uri['query'])) {
  554. $path .= '?' . $uri['query'];
  555. }
  556. // Create HTTP request.
  557. $defaults = array(
  558. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  559. // We don't add the port to prevent from breaking rewrite rules checking the
  560. // host that do not take into account the port number.
  561. 'Host' => "Host: $host",
  562. 'User-Agent' => 'User-Agent: FlightPath (+https://getflightpath.com/)',
  563. );
  564. // Only add Content-Length if we actually have any content or if it is a POST
  565. // or PUT request. Some non-standard servers get confused by Content-Length in
  566. // at least HEAD/GET requests, and Squid always requires Content-Length in
  567. // POST/PUT requests.
  568. $content_length = strlen($data);
  569. if ($content_length > 0 || $method == 'POST' || $method == 'PUT' || $method == 'DELETE') {
  570. $defaults['Content-Length'] = 'Content-Length: ' . $content_length;
  571. }
  572. // If the server url has a user then attempt to use basic authentication
  573. if (isset($uri['user'])) {
  574. $defaults['Authorization'] = 'Authorization: Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
  575. }
  576. foreach ($headers as $header => $value) {
  577. $defaults[$header] = $header . ': ' . $value;
  578. }
  579. $request = $method . ' ' . $path . " HTTP/1.0\r\n";
  580. $request .= implode("\r\n", $defaults);
  581. $request .= "\r\n\r\n";
  582. $request .= $data;
  583. $result->request = $request;
  584. // Calculate how much time is left of the original timeout value.
  585. $time_left = $timeout - timer_read(__FUNCTION__) / 1000;
  586. if ($time_left > 0) {
  587. stream_set_timeout($fp, floor($time_left), floor(1000000 * fmod($time_left, 1)));
  588. fwrite($fp, $request);
  589. }
  590. // Fetch response.
  591. $response = '';
  592. while (!feof($fp)) {
  593. // Calculate how much time is left of the original timeout value.
  594. $time_left = $timeout - timer_read(__FUNCTION__) / 1000;
  595. if ($time_left <= 0) {
  596. $result->code = HTTP_REQUEST_TIMEOUT;
  597. $result->error = 'request timed out';
  598. return $result;
  599. }
  600. stream_set_timeout($fp, floor($time_left), floor(1000000 * fmod($time_left, 1)));
  601. $chunk = fread($fp, 1024);
  602. $response .= $chunk;
  603. }
  604. fclose($fp);
  605. // Parse response headers from the response body.
  606. // Be tolerant of malformed HTTP responses that separate header and body with
  607. // \n\n or \r\r instead of \r\n\r\n. See http://drupal.org/node/183435
  608. list($split, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
  609. $split = preg_split("/\r\n|\n|\r/", $split);
  610. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  611. $result->protocol = $protocol;
  612. $result->status_message = $status_message;
  613. $result->headers = array();
  614. // Parse headers.
  615. while ($line = trim(array_shift($split))) {
  616. list($header, $value) = explode(':', $line, 2);
  617. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  618. // RFC 2109: the Set-Cookie response header comprises the token Set-
  619. // Cookie:, followed by a comma-separated list of one or more cookies.
  620. $result->headers[$header] .= ',' . trim($value);
  621. }
  622. else {
  623. $result->headers[$header] = trim($value);
  624. }
  625. }
  626. $responses = array(
  627. 100 => 'Continue',
  628. 101 => 'Switching Protocols',
  629. 200 => 'OK',
  630. 201 => 'Created',
  631. 202 => 'Accepted',
  632. 203 => 'Non-Authoritative Information',
  633. 204 => 'No Content',
  634. 205 => 'Reset Content',
  635. 206 => 'Partial Content',
  636. 300 => 'Multiple Choices',
  637. 301 => 'Moved Permanently',
  638. 302 => 'Found',
  639. 303 => 'See Other',
  640. 304 => 'Not Modified',
  641. 305 => 'Use Proxy',
  642. 307 => 'Temporary Redirect',
  643. 400 => 'Bad Request',
  644. 401 => 'Unauthorized',
  645. 402 => 'Payment Required',
  646. 403 => 'Forbidden',
  647. 404 => 'Not Found',
  648. 405 => 'Method Not Allowed',
  649. 406 => 'Not Acceptable',
  650. 407 => 'Proxy Authentication Required',
  651. 408 => 'Request Time-out',
  652. 409 => 'Conflict',
  653. 410 => 'Gone',
  654. 411 => 'Length Required',
  655. 412 => 'Precondition Failed',
  656. 413 => 'Request Entity Too Large',
  657. 414 => 'Request-URI Too Large',
  658. 415 => 'Unsupported Media Type',
  659. 416 => 'Requested range not satisfiable',
  660. 417 => 'Expectation Failed',
  661. 500 => 'Internal Server Error',
  662. 501 => 'Not Implemented',
  663. 502 => 'Bad Gateway',
  664. 503 => 'Service Unavailable',
  665. 504 => 'Gateway Time-out',
  666. 505 => 'HTTP Version not supported',
  667. );
  668. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  669. // base code in their class.
  670. if (!isset($responses[$code])) {
  671. $code = floor($code / 100) * 100;
  672. }
  673. switch ($code) {
  674. case 200: // OK
  675. case 304: // Not modified
  676. break;
  677. case 301: // Moved permanently
  678. case 302: // Moved temporarily
  679. case 307: // Moved temporarily
  680. $location = $result->headers['Location'];
  681. $timeout -= timer_read(__FUNCTION__) / 1000;
  682. if ($timeout <= 0) {
  683. $result->code = HTTP_REQUEST_TIMEOUT;
  684. $result->error = 'request timed out';
  685. }
  686. elseif ($retry) {
  687. $result = fp_http_request($result->headers['Location'], $headers, $method, $data, --$retry, $timeout);
  688. $result->redirect_code = $result->code;
  689. }
  690. $result->redirect_url = $location;
  691. break;
  692. default:
  693. $result->error = $status_message;
  694. }
  695. $result->code = $code;
  696. return $result;
  697. }
  698. /**
  699. * Begin a microtime timer for later use.
  700. */
  701. function timer_start($name) {
  702. global $timers;
  703. list($usec, $sec) = explode(' ', microtime());
  704. $timers[$name]['start'] = (float) $usec + (float) $sec;
  705. $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
  706. }
  707. /**
  708. * Works with the timer_start() function to return how long
  709. * it has been since the start.
  710. */
  711. function timer_read($name) {
  712. global $timers;
  713. if (isset($timers[$name]['start'])) {
  714. list($usec, $sec) = explode(' ', microtime());
  715. $stop = (float) $usec + (float) $sec;
  716. $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
  717. if (isset($timers[$name]['time'])) {
  718. $diff += $timers[$name]['time'];
  719. }
  720. return $diff;
  721. }
  722. }
  723. /**
  724. * Returns a random string of length len.
  725. */
  726. function fp_get_random_string($len = 7, $alpha = TRUE, $numeric = TRUE, $symbols = FALSE) {
  727. $base = "";
  728. if ($alpha) {
  729. $base .= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  730. }
  731. if ($numeric) {
  732. $base .= "12345678901234567890";
  733. }
  734. if ($symbols) {
  735. $base .= "!@#$%^&*()_+!@#$%^&*()-=";
  736. }
  737. $str = "";
  738. for ($t = 0; $t < $len; $t++) {
  739. $base = str_shuffle($base);
  740. $str .= $base[0];
  741. }
  742. return $str;
  743. }
  744. /**
  745. * Call all modules which implement hook_clear_cache
  746. */
  747. function fp_clear_cache() {
  748. // Find modules which implement hook_clear_cache
  749. $modules = modules_implement_hook("clear_cache");
  750. foreach ($modules as $module) {
  751. call_user_func($module . '_clear_cache');
  752. }
  753. }
  754. /**
  755. Remove any possiblilty of a malicious attacker trying to inject
  756. nonsense.
  757. From: https://paragonie.com/blog/2015/06/preventing-xss-vulnerabilities-in-php-everything-you-need-know
  758. */
  759. function fp_no_html_xss($string) {
  760. return htmlentities($string, ENT_QUOTES, 'UTF-8');
  761. //return htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); // ENT_HTML5 requires PGP 5.4+
  762. }
  763. /**
  764. * Filter string with possible HTML, allowing only certain tags, and removing dangerous attributes.
  765. *
  766. * $type can be:
  767. * - "plain" - No HTML tags are allowed.
  768. * - "basic" - Only certain tags allowed, no attributes. Safest. New lines = <br>
  769. * - "full" - All HTML is allowed through.
  770. *
  771. */
  772. function filter_markup($str, $type = "basic") {
  773. if (!$str) return $str;
  774. // Use the DOM functions to repair any mismatched HTML.
  775. $doc = new DOMDocument();
  776. @$doc->loadHTML(mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8')); // ensure we are in UTF8
  777. $str = $doc->saveHTML($doc->documentElement); // Apparently this helps solve a glitch in Linux that isn't in Windows
  778. if ($type == 'plain') {
  779. $str = strip_tags($str);
  780. }
  781. if ($type == "basic") {
  782. // To reduce extra newlines, remove any newline which is at the END of an existing <br> tag.
  783. $str = str_ireplace("<br>\n", "<br>", $str);
  784. $str = str_ireplace("<br />\n", "<br>", $str);
  785. $allowed_tags = array('a', 'em', 'strong', 'cite',
  786. 'blockquote', 'code', 'ul', 'ol', 'li',
  787. 'dl', 'dt', 'dd', 'span', 'div',
  788. 'b', 'i', 'u', 'br', 'p', 'table', 'tr',
  789. 'td', 'th', 'tbody', );
  790. $str = filter_xss($str, $allowed_tags);
  791. $str = trim($str);
  792. }
  793. return $str;
  794. }
  795. /**
  796. * This function is taken almost directly from Drupal 7's core code. It is used to help us filter out
  797. * dangerous HTML which the user might type.
  798. * From the D7 documentation:
  799. *
  800. * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
  801. * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses. For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
  802. * This code does four things:
  803. * Removes characters and constructs that can trick browsers.
  804. * Makes sure all HTML entities are well-formed.
  805. * Makes sure all HTML tags and attributes are well-formed.
  806. * Makes sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:).
  807. *
  808. */
  809. function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'span', 'div')) {
  810. // Only operate on valid UTF-8 strings. This is necessary to prevent cross
  811. // site scripting issues on Internet Explorer 6.
  812. if (!fp_validate_utf8($string)) {
  813. return '';
  814. }
  815. // Store the text format.
  816. filter_xss_split($allowed_tags, TRUE);
  817. // Remove NULL characters (ignored by some browsers).
  818. $string = str_replace(chr(0), '', $string);
  819. // Remove Netscape 4 JS entities.
  820. $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
  821. // Defuse all HTML entities.
  822. $string = str_replace('&', '&amp;', $string);
  823. // Change back only well-formed entities in our whitelist:
  824. // Decimal numeric entities.
  825. $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
  826. // Hexadecimal numeric entities.
  827. $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
  828. // Named entities.
  829. $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
  830. return preg_replace_callback('%
  831. (
  832. <(?=[^a-zA-Z!/]) # a lone <
  833. | # or
  834. <!--.*?--> # a comment
  835. | # or
  836. <[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
  837. | # or
  838. > # just a >
  839. )%x', 'filter_xss_split', $string);
  840. }
  841. /**
  842. * Like the filter_xss function, this is taken from D7's
  843. * _filter_xss_split function
  844. */
  845. function filter_xss_split($m, $store = FALSE) {
  846. static $allowed_html;
  847. if ($store) {
  848. $allowed_html = array_flip($m);
  849. return;
  850. }
  851. $string = $m[1];
  852. if (substr($string, 0, 1) != '<') {
  853. // We matched a lone ">" character.
  854. return '&gt;';
  855. }
  856. elseif (strlen($string) == 1) {
  857. // We matched a lone "<" character.
  858. return '&lt;';
  859. }
  860. if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
  861. // Seriously malformed.
  862. return '';
  863. }
  864. $slash = trim($matches[1]);
  865. $elem = &$matches[2];
  866. $attrlist = &$matches[3];
  867. $comment = &$matches[4];
  868. if ($comment) {
  869. $elem = '!--';
  870. }
  871. if (!isset($allowed_html[strtolower($elem)])) {
  872. // Disallowed HTML element.
  873. return '';
  874. }
  875. if ($comment) {
  876. return $comment;
  877. }
  878. if ($slash != '') {
  879. return "</$elem>";
  880. }
  881. // Is there a closing XHTML slash at the end of the attributes?
  882. $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
  883. $xhtml_slash = $count ? ' /' : '';
  884. // Clean up attributes.
  885. $attr2 = implode(' ', filter_xss_attributes($attrlist));
  886. $attr2 = preg_replace('/[<>]/', '', $attr2);
  887. $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
  888. return "<$elem$attr2$xhtml_slash>";
  889. }
  890. function filter_xss_attributes($attr) {
  891. $attrarr = array();
  892. $mode = 0;
  893. $attrname = '';
  894. $skip = FALSE;
  895. while (strlen($attr) != 0) {
  896. // Was the last operation successful?
  897. $working = 0;
  898. switch ($mode) {
  899. case 0:
  900. // Attribute name, href for instance.
  901. if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
  902. $attrname = strtolower($match[1]);
  903. $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
  904. $working = $mode = 1;
  905. $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
  906. }
  907. break;
  908. case 1:
  909. // Equals sign or valueless ("selected").
  910. if (preg_match('/^\s*=\s*/', $attr)) {
  911. $working = 1;
  912. $mode = 2;
  913. $attr = preg_replace('/^\s*=\s*/', '', $attr);
  914. break;
  915. }
  916. if (preg_match('/^\s+/', $attr)) {
  917. $working = 1;
  918. $mode = 0;
  919. if (!$skip) {
  920. $attrarr[] = $attrname;
  921. }
  922. $attr = preg_replace('/^\s+/', '', $attr);
  923. }
  924. break;
  925. case 2:
  926. // Attribute value, a URL after href= for instance.
  927. if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
  928. $thisval = filter_xss_bad_protocol($match[1]);
  929. if (!$skip) {
  930. $attrarr[] = "$attrname=\"$thisval\"";
  931. }
  932. $working = 1;
  933. $mode = 0;
  934. $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
  935. break;
  936. }
  937. if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
  938. $thisval = filter_xss_bad_protocol($match[1]);
  939. if (!$skip) {
  940. $attrarr[] = "$attrname='$thisval'";
  941. }
  942. $working = 1;
  943. $mode = 0;
  944. $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
  945. break;
  946. }
  947. if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
  948. $thisval = filter_xss_bad_protocol($match[1]);
  949. if (!$skip) {
  950. $attrarr[] = "$attrname=\"$thisval\"";
  951. }
  952. $working = 1;
  953. $mode = 0;
  954. $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
  955. }
  956. break;
  957. }
  958. if ($working == 0) {
  959. // Not well formed; remove and try again.
  960. $attr = preg_replace('/
  961. ^
  962. (
  963. "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
  964. | # or
  965. \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
  966. | # or
  967. \S # - a non-whitespace character
  968. )* # any number of the above three
  969. \s* # any number of whitespaces
  970. /x', '', $attr);
  971. $mode = 0;
  972. }
  973. }
  974. // The attribute list ends with a valueless attribute like "selected".
  975. if ($mode == 1 && !$skip) {
  976. $attrarr[] = $attrname;
  977. }
  978. return $attrarr;
  979. }
  980. function filter_xss_bad_protocol($string) {
  981. // Get the plain text representation of the attribute value (i.e. its meaning).
  982. $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
  983. return htmlspecialchars(fp_strip_dangerous_protocols($string), ENT_QUOTES, 'UTF-8');
  984. }
  985. function fp_strip_dangerous_protocols($uri) {
  986. static $allowed_protocols;
  987. if (!isset($allowed_protocols)) {
  988. $allowed_protocols = array_flip(array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal'));
  989. }
  990. // Iteratively remove any invalid protocol found.
  991. do {
  992. $before = $uri;
  993. $colonpos = strpos($uri, ':');
  994. if ($colonpos > 0) {
  995. // We found a colon, possibly a protocol. Verify.
  996. $protocol = substr($uri, 0, $colonpos);
  997. // If a colon is preceded by a slash, question mark or hash, it cannot
  998. // possibly be part of the URL scheme. This must be a relative URL, which
  999. // inherits the (safe) protocol of the base document.
  1000. if (preg_match('![/?#]!', $protocol)) {
  1001. break;
  1002. }
  1003. // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
  1004. // (URI Comparison) scheme comparison must be case-insensitive.
  1005. if (!isset($allowed_protocols[strtolower($protocol)])) {
  1006. $uri = substr($uri, $colonpos + 1);
  1007. }
  1008. }
  1009. } while ($before != $uri);
  1010. return $uri;
  1011. }
  1012. function fp_validate_utf8($text) {
  1013. if (strlen($text) == 0) {
  1014. return TRUE;
  1015. }
  1016. // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
  1017. // containing invalid UTF-8 byte sequences. It does not reject character
  1018. // codes above U+10FFFF (represented by 4 or more octets), though.
  1019. return (preg_match('/^./us', $text) == 1);
  1020. }
  1021. /**
  1022. * Simple function to convert a string into a machine-readable string.
  1023. *
  1024. * Useful for making possibly unsafe text work as an array index, a CSS class, etc. Replaces
  1025. * "bad" characters, or characters which might not be allowed for variables, for example,
  1026. * into underscores (_).
  1027. *
  1028. * @param string $str
  1029. * @return string
  1030. */
  1031. function fp_get_machine_readable($str) {
  1032. return preg_replace('@[^a-zA-Z0-9_]+@','_',$str);
  1033. }
  1034. /////////////////////////////////////////////////////////////////////
  1035. /**
  1036. * Return back an assoc array of our set degree classifications, separated by "level"
  1037. */
  1038. function fp_get_degree_classifications() {
  1039. $rtn = array();
  1040. // Level 1
  1041. $temp = explode("\n", variable_get("degree_classifications_level_1", "MAJOR ~ Major"));
  1042. foreach ($temp as $line) {
  1043. $temp2 = explode("~", $line);
  1044. $machine_name = trim($temp2[0]);
  1045. $title = trim($temp2[1]);
  1046. if ($machine_name != "") {
  1047. $rtn["levels"][1][$machine_name] = $title;
  1048. $rtn["machine_names"][$machine_name] = $title;
  1049. $rtn["machine_name_to_level_num"][$machine_name] = 1;
  1050. }
  1051. }
  1052. // Level 2
  1053. $temp = explode("\n", variable_get("degree_classifications_level_2", "MINOR ~ Minor"));
  1054. foreach ($temp as $line) {
  1055. $temp2 = explode("~", $line);
  1056. $machine_name = trim($temp2[0]);
  1057. $title = trim($temp2[1]);
  1058. if ($machine_name != "") {
  1059. $rtn["levels"][2][$machine_name] = $title;
  1060. $rtn["machine_names"][$machine_name] = $title;
  1061. $rtn["machine_name_to_level_num"][$machine_name] = 2;
  1062. }
  1063. }
  1064. // Level 3
  1065. $temp = explode("\n", variable_get("degree_classifications_level_3", "CONC ~ Concentration"));
  1066. foreach ($temp as $line) {
  1067. $temp2 = explode("~", $line);
  1068. $machine_name = trim($temp2[0]);
  1069. $title = trim($temp2[1]);
  1070. if ($machine_name != "") {
  1071. $rtn["levels"][3][$machine_name] = $title;
  1072. $rtn["machine_names"][$machine_name] = $title;
  1073. $rtn["machine_name_to_level_num"][$machine_name] = 3;
  1074. }
  1075. }
  1076. return $rtn;
  1077. }
  1078. /**
  1079. * Returns back an assoc array for the supplied code. Looks like:
  1080. * $arr["level_num"] = number
  1081. * $arr["title"] = the title
  1082. *
  1083. *
  1084. */
  1085. function fp_get_degree_classification_details($degree_class = "MAJOR", $bool_return_class_code_as_title_if_not_found = TRUE) {
  1086. $rtn = array();
  1087. if ($bool_return_class_code_as_title_if_not_found) {
  1088. // Use the degree_class as title for default, if we can't find it otherwise.
  1089. $rtn["level_num"] = 0;
  1090. $rtn["title"] = $degree_class;
  1091. $rtn["degree_class"] = $degree_class;
  1092. }
  1093. $degree_classifications = fp_get_degree_classifications();
  1094. foreach ($degree_classifications["levels"] as $num => $details) {
  1095. if (isset($details[$degree_class])) {
  1096. $rtn["level_num"] = $num;
  1097. $rtn["title"] = $details[$degree_class];
  1098. $rtn["degree_class"] = $degree_class;
  1099. break;
  1100. }
  1101. }
  1102. return $rtn;
  1103. }
  1104. /**
  1105. * Return an array version of the term_id_structure field from the admin settings
  1106. *
  1107. */
  1108. function get_term_structures($school_id = 0) {
  1109. $rtn = array();
  1110. $temp = variable_get_for_school("term_id_structure", "", $school_id);
  1111. $structures = explode("\n", $temp);
  1112. foreach ($structures as $structure) {
  1113. $tokens = explode(",", $structure);
  1114. $term_def = trim($tokens[0]);
  1115. // Get rid of the replacement pattern.
  1116. // Looks like: [Y4]40. We want the 40.
  1117. // Simply explode on "]"
  1118. $temp = explode("]", $term_def);
  1119. $term_suffix = trim($temp[1]);
  1120. $rtn[$term_suffix] = array(
  1121. "term_suffix" => $term_suffix,
  1122. "term_def" => $term_def,
  1123. "short" => trim(@$tokens[1]),
  1124. "full" => trim(@$tokens[2]),
  1125. "abbr" => trim(@$tokens[3]),
  1126. "disp_adjust" => trim(@$tokens[4]),
  1127. );
  1128. }
  1129. return $rtn;
  1130. }
  1131. /**
  1132. * Returns back an array of all the available requirement types (by code) that
  1133. * have been defined.
  1134. *
  1135. */
  1136. function fp_get_requirement_types($school_id) {
  1137. $rtn = array();
  1138. if (isset($GLOBALS['fp_temp_cache']['fp_get_requirement_types'][$school_id])) {
  1139. return $GLOBALS['fp_temp_cache']['fp_get_requirement_types'][$school_id];
  1140. }
  1141. $temp = explode("\n", variable_get_for_school("requirement_types", "g ~ General Requirements\nc ~ Core Requirements\ne ~ Electives\nm ~ Major Requirements\ns ~ Supporting Requirements\nx ~ Additional Requirements", $school_id));
  1142. foreach ($temp as $line) {
  1143. $line = trim($line);
  1144. if ($line == "") continue;
  1145. $temp = explode("~", $line);
  1146. $code = trim(strtolower($temp[0]));
  1147. $desc = trim($temp[1]);
  1148. $rtn[$code] = $desc;
  1149. }
  1150. // Make sure that code 'x' is set.
  1151. if (!isset($rtn["x"])) {
  1152. $rtn["x"] = t("Additional Requirements");
  1153. }
  1154. // Make sure code 'e' for Electives is set.
  1155. if (!isset($rtn["e"])) {
  1156. $rtn["e"] = t("Electives");
  1157. }
  1158. // Make sure code 'm' is set, for Major Requirements, our default type.
  1159. if (!isset($rtn["m"])) {
  1160. $rtn["m"] = t("Major Requirements");
  1161. }
  1162. $GLOBALS['fp_temp_cache']['fp_get_requirement_types'][$school_id] = $rtn;
  1163. return $rtn;
  1164. }
  1165. /**
  1166. * This function provides a pass-thru to $d = new DegreePlan(args).
  1167. * However, it allows for quick caching look-up, so it should be used when possible instead of $x = new DegreePlan.
  1168. */
  1169. function fp_load_degree($degree_id = "", DatabaseHandler $db = NULL, $bool_load_minimal = false, $array_significant_courses = false, $bool_use_draft = false) {
  1170. // Create a "cache key" based on the arguments, so we can look this degree up faster later.
  1171. $cache_key = md5(serialize(func_get_args()));
  1172. //fpm("degree_id: $degree_id . cache key:" . $cache_key . "+++++++++++++");
  1173. if (isset($GLOBALS['fp_temp_cache']['fp_load_degree'][$cache_key])) {
  1174. $degree = $GLOBALS['fp_temp_cache']['fp_load_degree'][$cache_key];
  1175. //fpm(" ... returning cache");
  1176. return $degree;
  1177. }
  1178. $degree = new DegreePlan($degree_id, $db, $bool_load_minimal, $array_significant_courses, $bool_use_draft);
  1179. // Save to our cache
  1180. $GLOBALS['fp_temp_cache']['fp_load_degree'][$cache_key] = $degree;
  1181. return $degree;
  1182. }
  1183. /**
  1184. * If this function is called, it will override any other page tabs
  1185. * which might be getting constructed. This lets the programmer,
  1186. * at run-time, completely control what tabs are at the top of the page.
  1187. */
  1188. function fp_set_page_tabs($tab_array) {
  1189. $GLOBALS["fp_set_page_tabs"] = $tab_array;
  1190. }
  1191. /**
  1192. * Allows the programmer to define subtabs at the top of the page.
  1193. *
  1194. * @param unknown_type $tab_array
  1195. */
  1196. function fp_set_page_sub_tabs($tab_array) {
  1197. $GLOBALS["fp_set_page_sub_tabs"] = $tab_array;
  1198. }
  1199. /**
  1200. * Set our breadcrumbs array.
  1201. *
  1202. * We expect the array to look like this:
  1203. * [0]['text'] = "Alerts";
  1204. * [0]['path'] = "my/alerts";
  1205. * [0]['query'] (optional)
  1206. * [0]['attributes'] (optional. Used exactly as in the l() function. @see l() )
  1207. *
  1208. * [1] .... etc.
  1209. * @see fp_render_breadcrumbs();
  1210. *
  1211. *
  1212. * Here is a practical example of how to call this function:
  1213. *
  1214. * $crumbs = array();
  1215. * $crumbs[] = array(
  1216. * 'text' => 'Alerts',
  1217. * 'path' => 'alerts',
  1218. * );
  1219. *
  1220. * fp_set_breadcrumbs($crumbs);
  1221. *
  1222. */
  1223. function fp_set_breadcrumbs($arr = array()) {
  1224. $GLOBALS['fp_breadcrumbs'] = $arr;
  1225. }
  1226. /**
  1227. * Allows the programmer to set the title of the page, overwriting any default title.
  1228. *
  1229. * @param unknown_type $title
  1230. */
  1231. function fp_set_title($title) {
  1232. $GLOBALS["fp_set_title"] = $title;
  1233. if ($title == "") {
  1234. fp_show_title(FALSE); // No title to show!
  1235. }
  1236. else {
  1237. fp_show_title(TRUE); // If we are calling this function, we clearly want to display the title.
  1238. }
  1239. }
  1240. /**
  1241. * Add a CSS class to the body tag of the page. Useful for themeing later on.
  1242. *
  1243. * @param String $class
  1244. */
  1245. function fp_add_body_class($class) {
  1246. // Let's sanitize the "class" to make sure it doesn't contain any trouble characters.
  1247. $class = str_replace("'", '', $class);
  1248. $class = str_replace('"', '', $class);
  1249. $class = str_replace('(', '', $class);
  1250. $class = str_replace(')', '', $class);
  1251. $class = str_replace(';', '', $class);
  1252. $class = str_replace('.', '', $class);
  1253. $class = str_replace('<', '', $class);
  1254. $class = str_replace('>', '', $class);
  1255. $class = str_replace('/', '', $class);
  1256. $class = str_replace('\\', '', $class);
  1257. $class = str_replace('#', '', $class);
  1258. $class = str_replace('&', '', $class);
  1259. @$GLOBALS["fp_add_body_classes"] .= " " . $class;
  1260. }
  1261. /**
  1262. * Returns back the site's "token", which is a simply md5 of some randomness.
  1263. * It is used primarily with forms, to ensure against cross-site forgeries.
  1264. * The site's token gets saved to the variables table, for later use. The idea
  1265. * is that every installation of FlightPath has a semi-unique token.
  1266. */
  1267. function fp_token() {
  1268. $site_token = variable_get("site_token", "");
  1269. if ($site_token == "") {
  1270. $site_token = md5("" . time() . rand(1,9999));
  1271. variable_set("site_token", $site_token);
  1272. }
  1273. return $site_token;
  1274. }
  1275. /**
  1276. * This function will provide the session_id as a string, as well as a secret token we can
  1277. * use to make sure the session_id is authentic and came from us and not a hacker.
  1278. */
  1279. function fp_get_session_str() {
  1280. $session_id = session_id(); // Get the PHP session_id
  1281. $ip = @$_SERVER["REMOTE_ADDR"];
  1282. if ($ip == "") $ip = "000";
  1283. // NOTE: We cannot use fp_token() here, since the get function (below) is called before the various bootstrap files are loaded.
  1284. // Create a string where we can confirm the ip and server name the session came from.
  1285. // TODO: Might be able to add more entropy later on, as long as it does not involve the database, since bootstrap isn't loaded yet when validating.
  1286. $str = $session_id . "~_" . md5($session_id . $ip . php_uname('n'));
  1287. return $str;
  1288. }
  1289. /**
  1290. * This will validate the session str (@see fp_get_session_str()) and return back either FALSE
  1291. * or the session_id.
  1292. */
  1293. function fp_get_session_id_from_str($str) {
  1294. // We expect $str to look like this:
  1295. // session_id~_md5(session_id . ip . php_uname('n'))
  1296. $temp = explode("~_", $str);
  1297. $session_id = trim($temp[0]);
  1298. $hash = trim($temp[1]);
  1299. $ip = @$_SERVER["REMOTE_ADDR"];
  1300. if ($ip == "") $ip = "000";
  1301. $test_hash = md5($session_id . $ip . php_uname('n'));
  1302. if ($test_hash === $hash) {
  1303. // Success!
  1304. return $session_id;
  1305. }
  1306. return FALSE;
  1307. }
  1308. /**
  1309. * Simple function that adds spaces after commas in CSV strings. Makes them easier to read.
  1310. */
  1311. function fp_space_csv($str) {
  1312. $str = str_replace(",", ", ", $str);
  1313. // Get rid of double spaces we might have introduced.
  1314. $str = str_replace(", ", ", ", $str);
  1315. $str = str_replace(", ", ", ", $str);
  1316. $str = str_replace(", ", ", ", $str);
  1317. $str = trim($str);
  1318. return $str;
  1319. }
  1320. /**
  1321. * Simple function to split a basic CSV string, trim all elements, then return
  1322. * the resulting array.
  1323. */
  1324. function csv_to_array($csv_string) {
  1325. $temp = explode(",", $csv_string);
  1326. $temp = array_map("trim", $temp);
  1327. return $temp;
  1328. }
  1329. /**
  1330. * Splits a basic csv but returns an array suitable for the form_api, retuns assoc array.
  1331. */
  1332. function csv_to_form_api_array($csv_string, $delimeter = ",", $bool_make_keys_machine_readable = TRUE) {
  1333. $rtn = array();
  1334. $temp = explode($delimeter, $csv_string);
  1335. foreach ($temp as $line) {
  1336. $line = trim($line);
  1337. if (!$line) continue;
  1338. $key = strtolower(fp_get_machine_readable($line));
  1339. $rtn[$key] = $line;
  1340. }
  1341. return $rtn;
  1342. }
  1343. /**
  1344. * From https://www.php.net/manual/en/function.str-getcsv.php#117692
  1345. */
  1346. function csv_multiline_to_array($csv_str, $bool_first_row_is_headers = TRUE) {
  1347. $csv = array_map('str_getcsv', explode("\n", trim($csv_str)));
  1348. array_walk($csv, function(&$a) use ($csv) {
  1349. if (count($a) == count($csv[0])) {
  1350. $a = array_combine($csv[0], $a);
  1351. }
  1352. else {
  1353. fpm("Warning: issue converting multiline CSV to an array within FlightPath. Not the same number of elements.");
  1354. }
  1355. });
  1356. if (!$bool_first_row_is_headers) {
  1357. array_shift($csv); # remove column header
  1358. }
  1359. return $csv;
  1360. }
  1361. /**
  1362. * Add a "message" to the top of the screen. Useful for short messages like "You have been logged out"
  1363. * or "Form submitted successfully."
  1364. *
  1365. * @param String $msg
  1366. * This is the string message itself.
  1367. * @param String $type
  1368. * The "type" of message. This string is added as a CSS class to the message, for theming later.
  1369. * @param boolean $bool_no_repeat
  1370. * Boolean. Should the message show more than once per page view? Set to TRUE if it should NOT.
  1371. */
  1372. function fp_add_message($msg, $type = "status", $bool_no_repeat = FALSE) {
  1373. $md5 = md5($type . $msg);
  1374. if ($bool_no_repeat && isset($_SESSION["fp_messages"]) && is_array($_SESSION["fp_messages"])) {
  1375. // Make sure this message isn't already in the session.
  1376. foreach($_SESSION["fp_messages"] as $s) {
  1377. if ($s["md5"] == $md5) return;
  1378. }
  1379. }
  1380. $_SESSION["fp_messages"][] = array("type" => $type, "msg" => $msg, "md5" => $md5);
  1381. }
  1382. /*
  1383. Does the string end with the provided needed?
  1384. */
  1385. function fp_str_ends_with ($haystack, $needle) {
  1386. return substr_compare($haystack, $needle, -strlen($needle)) === 0;
  1387. }
  1388. /**
  1389. * Add an extra CSS file to the page with this function.
  1390. * Ex: fp_add_css(fp_get_module_path("admin") . '/css/admin.css');
  1391. *
  1392. * @param String $path_to_css
  1393. */
  1394. function fp_add_css($path_to_css) {
  1395. // Init if needed
  1396. if (!isset($GLOBALS['fp_extra_css'])) $GLOBALS['fp_extra_css'] = array();
  1397. if (!in_array($path_to_css, $GLOBALS['fp_extra_css'])) {
  1398. $GLOBALS["fp_extra_css"][] = $path_to_css;
  1399. }
  1400. }
  1401. /**
  1402. * Add extra javascript to the page.
  1403. *
  1404. * - type = file... $js is expected to be the path to a javascript file.
  1405. * - type = setting... $js is expected to be an associative array of settings.
  1406. * For example: array("my_path" => "blah", "my_color" => "red").
  1407. * They will be available in javascript in the object FlightPath like so:
  1408. * FlightPath.settings.my_color;
  1409. *
  1410. * Ex: fp_add_js(fp_get_module_path("admin") . '/js/admin.js');
  1411. *
  1412. * @see fp_add_css()
  1413. *
  1414. */
  1415. function fp_add_js($js, $type = "file") {
  1416. // Init if needed
  1417. if (!isset($GLOBALS['fp_extra_js'])) $GLOBALS['fp_extra_js'] = array();
  1418. if ($type == "file") {
  1419. if (!in_array($js, $GLOBALS['fp_extra_js'])) {
  1420. $GLOBALS["fp_extra_js"][] = $js;
  1421. }
  1422. }
  1423. if ($type == "setting") {
  1424. if (!isset($GLOBALS["fp_extra_js_settings"])) $GLOBALS["fp_extra_js_settings"] = array();
  1425. // Instead of using array_merge_recursive, this guarantees that keys are not re-used.
  1426. foreach ($js as $key => $val) {
  1427. $GLOBALS["fp_extra_js_settings"][$key] = $val;
  1428. }
  1429. }
  1430. }
  1431. /**
  1432. * This function will create a string from a 1 dimensional assoc array.
  1433. * Ex: arr = array("pet" => "dog", "name" => "Rex")
  1434. * will return: pet_S-dog,name_S-Rex under the default settings.
  1435. *
  1436. * The separator is meant to be a string extremely unlikely to be used in the key or values.
  1437. *
  1438. * Use the fp_explode_assoc function to piece it back together.
  1439. * @see fp_explode_assoc
  1440. */
  1441. function fp_join_assoc($arr, $glue = ",", $assign_sep = "_S-") {
  1442. $rtn = "";
  1443. foreach ($arr as $key => $val) {
  1444. $rtn .= $key . $assign_sep . $val . $glue;
  1445. }
  1446. // Should be an extra glue character at the end we need to trim off.
  1447. $rtn = rtrim($rtn, $glue);
  1448. return $rtn;
  1449. }
  1450. /**
  1451. * Takes a string (created by fp_join_assoc()) and re-creates the 1 dimensional assoc array.
  1452. *
  1453. * The separator is meant to be a string extremely unlikely to be used in the key or values.
  1454. *
  1455. * @see fp_join_assoc()
  1456. */
  1457. function fp_explode_assoc($string, $delim = ",", $assign_sep = "_S-") {
  1458. $rtn = array();
  1459. $temp = explode($delim, $string);
  1460. foreach($temp as $line) {
  1461. $line = trim($line);
  1462. if ($line == "") continue;
  1463. $temp2 = explode($assign_sep, $line);
  1464. if (is_numeric($temp2[1])) {
  1465. $temp2[1] = $temp2[1] * 1; // if its numeric anyway, make it have a numeric type.
  1466. }
  1467. $rtn[$temp2[0]] = $temp2[1];
  1468. }
  1469. return $rtn;
  1470. }
  1471. /**
  1472. * Return the filepath to the module
  1473. *
  1474. * @param unknown_type $module
  1475. * @param unknown_type $bool_include_file_system_path
  1476. * @param unknown_type $bool_include_base_path
  1477. * @return unknown
  1478. */
  1479. function fp_get_module_path($module, $bool_include_file_system_path = FALSE, $bool_include_base_path = TRUE) {
  1480. $p = menu_get_module_path($module, $bool_include_file_system_path);
  1481. if ($bool_include_file_system_path == FALSE && $bool_include_base_path == TRUE) {
  1482. $p = base_path() . "/" . $p;
  1483. }
  1484. return $p;
  1485. }
  1486. /**
  1487. * Convenience function to return the /files system path. Does NOT end with a trailing slash.
  1488. *
  1489. */
  1490. function fp_get_files_path() {
  1491. return $GLOBALS["fp_system_settings"]["file_system_path"] . "/custom/files";
  1492. }
  1493. /**
  1494. * Simply returns TRUE or FALSE if the user is a student. (has the is_student == 1
  1495. *
  1496. * If account is null, the global user will be used.
  1497. */
  1498. function fp_user_is_student($account = null) {
  1499. global $user;
  1500. if ($account == NULL) {
  1501. $account = $user;
  1502. }
  1503. return (bool)$account->is_student;
  1504. }
  1505. /**
  1506. * Simply returns the module's row from the modules table, if it exists.
  1507. *
  1508. * @param unknown_type $module
  1509. */
  1510. function fp_get_module_details($module) {
  1511. // Special case if we are looking up flightpath itself
  1512. if ($module == "flightpath") {
  1513. $rtn = array(
  1514. "info" => array("name" => t("FlightPath (Core)")),
  1515. "version" => FLIGHTPATH_VERSION,
  1516. );
  1517. return $rtn;
  1518. }
  1519. $res = db_query("SELECT * FROM modules WHERE name = '?' ", $module);
  1520. $cur = db_fetch_array($res);
  1521. if ($test = unserialize($cur["info"])) {
  1522. $cur["info"] = $test;
  1523. }
  1524. return $cur;
  1525. }
  1526. /**
  1527. * This function will facilitate translations by using hook_translate()
  1528. *
  1529. * Allows variable replacements. Use like this:
  1530. * t("@name's blob", array("@name" => "Richard"));
  1531. * or simply
  1532. * t("My blob"); if you don't need replacements.
  1533. *
  1534. * Not implimented yet.
  1535. */
  1536. function t($str, $vars = array()) {
  1537. // Note: at the moment, this isn't being used, but should one day be set.
  1538. @$langcode = isset($langcode) ? $langcode : $GLOBALS["fp_system_settings"]["language"];
  1539. // First, change $str if any other modules implement hook_translate().
  1540. invoke_hook("translate", array(&$str, $langcode, $vars)); // str is passed by ref, so no return needed.
  1541. if (is_array($vars) && count($vars) > 0) {
  1542. foreach ($vars as $var => $val) {
  1543. // If var begins with %, it means we want to italicize the val.
  1544. if (strstr($var, "%")) {
  1545. $val = "<em>$val</em>";
  1546. }
  1547. $str = str_replace($var, $val, $str);
  1548. }
  1549. }
  1550. return $str;
  1551. }
  1552. /**
  1553. * Provides translation functionality when database is not available.
  1554. *
  1555. * TODO: Not implemented yet
  1556. */
  1557. function st($str, $vars = array()) {
  1558. // Not implemented yet. For now, just replicate t().
  1559. if (is_array($vars) && count($vars) > 0) {
  1560. foreach ($vars as $var => $val) {
  1561. // If var begins with %, it means we want to italicize the val.
  1562. if (strstr($var, "%")) {
  1563. $val = "<em>$val</em>";
  1564. }
  1565. $str = str_replace($var, $val, $str);
  1566. }
  1567. }
  1568. return $str;
  1569. }
  1570. /**
  1571. * Shortcut for getting the base_url variable from the global system settings.
  1572. */
  1573. function base_url() {
  1574. $p = $GLOBALS["fp_system_settings"]["base_url"];
  1575. return $p;
  1576. }
  1577. /**
  1578. * Shortcut for getting the base_path variable from the global system settings.
  1579. */
  1580. function base_path() {
  1581. $p = $GLOBALS["fp_system_settings"]["base_path"];
  1582. // the base_path setting isn't set, so just use '.', meaning, start
  1583. // at the currect directory by default.
  1584. if ($p == "") {
  1585. $p = ".";
  1586. }
  1587. // if our base_path is simply "/" (meaning, we are hosted on a bare domain), then we should
  1588. // actually return nothing, so as not to cause errors with other systems.
  1589. if ($p == "/") {
  1590. $p = "";
  1591. }
  1592. return $p;
  1593. }
  1594. /**
  1595. * Convert a term ID into a description. Ex: 20095 = Spring of 2009.
  1596. */
  1597. function get_term_description($term_id, $bool_abbreviate = FALSE, $school_id = 0) {
  1598. // Describe the term in plain english, for displays.
  1599. // Ex: "Fall of 2002."
  1600. $rtn = "";
  1601. // If already in our GLOBALS cache, then just return that.
  1602. if (isset($GLOBALS['fp_cache_get_term_description'][$term_id][intval($bool_abbreviate)][$school_id])) {
  1603. return $GLOBALS['fp_cache_get_term_description'][$term_id][intval($bool_abbreviate)][$school_id];
  1604. }
  1605. // See if any modules would like to act on the term_id before we proceed.
  1606. invoke_hook("alter_term_id_prior_to_description", array(&$term_id, &$bool_abbreviate, $school_id));
  1607. if (strstr($term_id, "1111"))
  1608. {
  1609. return "(data unavailable at this time)";
  1610. }
  1611. $year4 = intval(trim(substr($term_id, 0, 4)));
  1612. $year2 = intval(trim(substr($term_id, 2, 2)));
  1613. $ss = trim(substr($term_id, 4, strlen($term_id) - 4));
  1614. $year4p1 = $year4 + 1;
  1615. $year4m1 = $year4 - 1;
  1616. // left-pad these with 0's if needed.
  1617. $year2p1 = @fp_number_pad($year2 + 1, 2);
  1618. $year2m1 = @fp_number_pad($year2 - 1, 2);
  1619. // Let's look at the term_idStructure setting and attempt to match
  1620. // what we have been supplied.
  1621. // We expect this structure to look something like:
  1622. // [Y4]60, Spring, Spring of [Y4], Spr '[Y2]
  1623. // [Y4]40, Fall, Fall of [Y4-1], Fall '[Y2-1]
  1624. $temp = @variable_get_for_school("term_id_structure", '', $school_id);
  1625. $structures = explode("\n", $temp);
  1626. foreach ($structures as $structure) {
  1627. // Perform the necessary replacement patterns on the structure.
  1628. $structure = str_replace("[Y4]", $year4, $structure);
  1629. $structure = str_replace("[Y2]", $year2, $structure);
  1630. $structure = str_replace("[Y4-1]", $year4m1, $structure);
  1631. $structure = str_replace("[Y2-1]", $year2m1, $structure);
  1632. $structure = str_replace("[Y4+1]", $year4p1, $structure);
  1633. $structure = str_replace("[Y2+1]", $year2p1, $structure);
  1634. // Now, break up the structure to make it easier to work with.
  1635. $tokens = explode(",", $structure);
  1636. $term_def = @trim($tokens[0]);
  1637. $full_description = @trim($tokens[2]);
  1638. $abbr_description = @trim($tokens[3]);
  1639. // Does our term_id match the termDef?
  1640. if ($term_def == $term_id) {
  1641. if ($bool_abbreviate) {
  1642. return $abbr_description;
  1643. }
  1644. else {
  1645. return $full_description;
  1646. }
  1647. }
  1648. }
  1649. // No descr could be found, so just display the term_id itself.
  1650. if (trim($rtn) == "") {
  1651. $rtn = $term_id;
  1652. }
  1653. // Save to our GLOBALS cache
  1654. $GLOBALS['fp_cache_get_term_description'][$term_id][intval($bool_abbreviate)][$school_id] = $rtn;
  1655. return $rtn;
  1656. }
  1657. /**
  1658. * Redirect the user's browser to the specified internal path + query.
  1659. *
  1660. * We will automatically add the current_student_id variable, if it is not present
  1661. * in the query.
  1662. *
  1663. * Example uses:
  1664. * - fp_goto("admin");
  1665. * - fp_goto("test/1234");
  1666. * - fp_goto("test/123", "selection=yes&fruit=apple");
  1667. */
  1668. function fp_goto($path, $query = "") {
  1669. global $current_student_id;
  1670. // Were we sent an array instead of separate values? That's OK if so, let's separate them back out.
  1671. if (is_array($path)) {
  1672. $query = @$path[1];
  1673. $path = @$path[0];
  1674. }
  1675. if ($current_student_id != "" && !strstr($query, "current_student_id=")) {
  1676. // If the query doesn't contain the current_student_id, then add it in.
  1677. $query .= "&current_student_id=$current_student_id";
  1678. }
  1679. // Close the seesion before we try to redirect.
  1680. session_write_close();
  1681. if ($path == "<front>") {
  1682. $path = variable_get("front_page", "main");
  1683. }
  1684. $location = fp_url($path, $query);
  1685. if (str_starts_with($path, "http://") || str_starts_with($path, "https://")) {
  1686. // We are going to an external address.
  1687. if (str_starts_with($query, "&")) {
  1688. // Need to add ? to the query.
  1689. $query = "?fprnd=" . mt_rand(9,999999) . $query;
  1690. }
  1691. $location = $path . $query;
  1692. }
  1693. header('Location: ' . $location);
  1694. exit();
  1695. }
  1696. /**
  1697. * This works like Drupal's l() function for creating links.
  1698. * Ex: l("Click here for course search!", "tools/course-search", "abc=xyz&hello=goodbye", array("class" => "my-class"));
  1699. * Do not include preceeding or trailing slashes.
  1700. */
  1701. function l($text, $path, $query = "", $attributes = array()) {
  1702. $rtn = "";
  1703. if ($path == "<front>") {
  1704. $path = variable_get("front_page", "main");
  1705. }
  1706. // Does the path contain possible replacement patterns? (look for %)
  1707. if (strpos($path, "%") !== 0) {
  1708. $path = menu_convert_replacement_pattern($path);
  1709. }
  1710. // Does the query contain possible replacement patterns? (look for %)
  1711. if (strpos($query, "%") !== 0) {
  1712. $query = menu_convert_replacement_pattern($query);
  1713. }
  1714. $rtn .= '<a href="' . fp_url($path, $query) . '" ';
  1715. foreach ($attributes as $key => $value) {
  1716. $rtn .= $key . '="' . $value . '" ';
  1717. }
  1718. $rtn .= ">$text</a>";
  1719. return $rtn;
  1720. }
  1721. /**
  1722. * This function will take a path, ex: "admin/config/module"
  1723. * and a query, ex: "nid=5&whatever=yes"
  1724. * And join them together, respecting whether or not clean URL's are enabled.
  1725. */
  1726. function fp_url($path, $query = "", $include_base_path = TRUE) {
  1727. if ($path == "<front>") {
  1728. $path = variable_get("default_home_path", "main");
  1729. }
  1730. // If clean URLs are enabled, we should begin with a ?, if not, use an &
  1731. $rtn = "";
  1732. if ($include_base_path) {
  1733. $rtn .= base_path() . "/";
  1734. }
  1735. // Make sure that $rtn isn't now "//". This can happen if our
  1736. // site is hosted on a bare domain. Ex: http://fp.example.com
  1737. // And we have set the base_path to simply "/"
  1738. if ($rtn == "//") $rtn = "/";
  1739. $bool_clean_urls = variable_get("clean_urls", FALSE);
  1740. if (!$bool_clean_urls) {
  1741. // Clean URLs are NOT enabled! Let's make sure the URL contains "index.php?q="
  1742. $rtn .= "index.php?q=";
  1743. }
  1744. $rtn .= $path;
  1745. if ($query != "") {
  1746. // Is there a ? already in the $rtn? If not, add a ?. If so, use a &.
  1747. if (!strstr($rtn, "?")) {
  1748. $rtn .= "?";
  1749. }
  1750. else {
  1751. $rtn .= "&";
  1752. }
  1753. $rtn .= $query;
  1754. }
  1755. return $rtn;
  1756. }
  1757. /**
  1758. * This function will attempt to determine automatically
  1759. * if we are on a mobile device, and should therefor use the mobile
  1760. * theme and layout settings.
  1761. *
  1762. */
  1763. function fp_screen_is_mobile(){
  1764. depricated_message("calling fp_screen_is_mobile is no longer used in FP6");
  1765. if (isset($GLOBALS["fp_page_is_mobile"])) {
  1766. return $GLOBALS["fp_page_is_mobile"];
  1767. }
  1768. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  1769. $look_for = array(
  1770. "ipod",
  1771. "iphone",
  1772. "android",
  1773. "opera mini",
  1774. "blackberry",
  1775. "(pre\/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)",
  1776. "(iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile)",
  1777. "(smartphone|iemobile)",
  1778. );
  1779. $is_mobile = FALSE;
  1780. foreach ($look_for as $test_agent) {
  1781. if (preg_match('/' . $test_agent . '/i',$user_agent)) {
  1782. $is_mobile = TRUE;
  1783. break;
  1784. }
  1785. }
  1786. $GLOBALS["fp_page_is_mobile"] = $is_mobile;
  1787. return $is_mobile;
  1788. } // ends function mobile_device_detect
  1789. /**
  1790. * Simple function that returns TRUE if the module is enabled, FALSE otherwise.
  1791. *
  1792. * We also will use our existing GLOBALS cache.
  1793. */
  1794. function module_enabled($module_name) {
  1795. return (isset($GLOBALS["fp_system_settings"]["modules"][$module_name]));
  1796. }
  1797. /**
  1798. * Return an array of enabled modules which implement the provided hook.
  1799. * Do not include the preceeding "_" on the hook name!
  1800. */
  1801. function modules_implement_hook($hook = "example_hook_here") {
  1802. // Going to use a global array to keep track of what hooks exist.
  1803. if (!isset($GLOBALS['hook_cache'])) $GLOBALS['hook_cache'] = array();
  1804. // Have we already cached this list previously?
  1805. if (isset($GLOBALS['hook_cache'][$hook])) return $GLOBALS['hook_cache'][$hook];
  1806. // We have not already cached this, so let's look for it fresh...
  1807. $rtn = array();
  1808. // If we are in the install script, the GLOBALS array won't be set up, since there is no
  1809. // settings file yet. If that's the case, create a blank array so we don't have an issue.
  1810. if (!isset($GLOBALS['fp_system_settings'])) $GLOBALS['fp_system_settings'] = array();
  1811. if (!isset($GLOBALS['fp_system_settings']['modules'])) $GLOBALS['fp_system_settings']['modules'] = array();
  1812. foreach ($GLOBALS["fp_system_settings"]["modules"] as $module => $value) {
  1813. if (isset($value["enabled"]) && $value["enabled"] != "1") {
  1814. // Module is not enabled. Skip it.
  1815. continue;
  1816. }
  1817. if (function_exists($module . '_' . $hook)) {
  1818. $rtn[] = $module;
  1819. }
  1820. }
  1821. $GLOBALS['hook_cache'][$hook] = $rtn;
  1822. return $rtn;
  1823. }
  1824. /**
  1825. * Invokes a hook to get numbers on the total, read, and unread values from our modules, to find out
  1826. * if we need to place a badge on the bell icon at the top of the screen.
  1827. */
  1828. function fp_recalculate_alert_count_by_type($account = NULL) {
  1829. global $user;
  1830. if ($account === NULL) $account = $user;
  1831. if ($account->id == 0) return FALSE;
  1832. $res = invoke_hook("get_alert_count_by_type", array($account));
  1833. $_SESSION['fp_alert_count_by_type'] = $res;
  1834. $_SESSION['fp_alert_count_by_type_last_check'] = time();
  1835. }
  1836. /**
  1837. * Returns back the total, read, and unread numbers previously calculated to see if we need to place
  1838. * a badge next to the bell icon at the top of the screen. If unset, we will call the recalculate function.
  1839. */
  1840. function fp_get_alert_count_by_type($account = NULL) {
  1841. global $user;
  1842. if ($account === NULL) $account = $user;
  1843. if ($account->id == 0) return FALSE;
  1844. if (!isset($_SESSION['fp_alert_count_by_type_last_check'])) {
  1845. $_SESSION['fp_alert_count_by_type_last_check'] = 0;
  1846. }
  1847. // Should we recalculate again?
  1848. $test = time() - intval(variable_get('recalculate_alert_badge_seconds', 30));
  1849. if ($_SESSION['fp_alert_count_by_type_last_check'] < $test) {
  1850. unset($_SESSION['fp_alert_count_by_type']); // this will force us to recalculate.
  1851. }
  1852. if (!isset($_SESSION['fp_alert_count_by_type'])) {
  1853. fp_recalculate_alert_count_by_type($account);
  1854. }
  1855. return $_SESSION['fp_alert_count_by_type'];
  1856. }
  1857. /**
  1858. * Invoke all module hooks for the supplied hook.
  1859. */
  1860. function invoke_hook($hook = "example_hook_here", $params = array()) {
  1861. $rtn = array();
  1862. $modules = modules_implement_hook($hook);
  1863. foreach($modules as $module) {
  1864. $rtn[$module] = call_user_func_array($module . "_" . $hook, $params);
  1865. }
  1866. return $rtn;
  1867. }
  1868. /**
  1869. * Uses fp_add_message, but in this case, it also adds in the filename and line number
  1870. * which the message came from!
  1871. *
  1872. * Most useful for developers, tracking down issues. It's also only visible to administrators
  1873. * with the "view_fpm_debug" permission. So if you need to display a message only to admins,
  1874. * you can use fpm() as a shortcut.
  1875. *
  1876. * Note: If you attempt to fpm() an array
  1877. * or object with too many levels of nesting, it may run out of memory and your script will die.
  1878. */
  1879. function fpm($var, $max_levels = 20) {
  1880. if (!user_has_permission("view_fpm_debug")) {
  1881. return;
  1882. }
  1883. // Complex variable? Change it to print_r.
  1884. $str = $var;
  1885. if (is_array($str) || is_object($str)) {
  1886. $str = "<div class='fp-html-print-r-wrapper'>" . fp_html_print_r($str, "", 0, $max_levels) . "</div>";
  1887. }
  1888. $arr = debug_backtrace();
  1889. //pretty_print($arr);
  1890. $t = 0;
  1891. if (@$arr[1]['function'] == 'fpmct') {
  1892. $t = 1;
  1893. }
  1894. $file = $arr[$t]["file"];
  1895. if (strlen($file) > 70) {
  1896. $file = "..." . substr($file, strlen($file) - 70);
  1897. }
  1898. $str .= "<div class='fp-message-backtrace'>line {$arr[$t]["line"]}: $file</div>";
  1899. fp_add_message("&bull; " . $str);
  1900. }
  1901. /**
  1902. * Displays a depricated message on screen. Useful for tracking down
  1903. * when depricated functions are being used.
  1904. */
  1905. function depricated_message($str = "A depricated function has been called.") {
  1906. fpm($str);
  1907. fpm(debug_backtrace());
  1908. }
  1909. /**
  1910. * Convenience function, will use fp_debug_ct() to display
  1911. * a message, and the number of miliseconds since its last call.
  1912. */
  1913. function fpmct($val, $var = "") {
  1914. fpm(fp_debug_ct($val, $var));
  1915. }
  1916. /**
  1917. * Similar to print_r, this will return an HTML-friendly
  1918. * click-to-open system similar in design to Krumo.
  1919. */
  1920. function fp_html_print_r($var, $name = "", $cnt = 0, $max_levels = 20) {
  1921. $rtn = "";
  1922. if ($cnt > $max_levels) {
  1923. // Max levels deep. Deeper, and PHP might run
  1924. // out of memory or complain.
  1925. $rtn .= "<div class='fp-html-print-r-too-deep'>
  1926. " . t("Depth too great. To view deeper,
  1927. rephrase your fpm() call, starting at this depth.") . "
  1928. </div>";
  1929. return $rtn;
  1930. }
  1931. $type = gettype($var);
  1932. $rnd = md5(mt_rand(0, 999999) . microtime() . $type . $name);
  1933. if ($type == "boolean") {
  1934. $var = ($var == TRUE) ? "TRUE" : "FALSE";
  1935. }
  1936. $count = "";
  1937. if ($type == "string") {
  1938. $count = " - " . strlen($var) . " " . t("chars");
  1939. }
  1940. if ($type == "array" || $type == "object") {
  1941. if ($type == "array") {
  1942. $count = " - " . count($var) . " " . t("elements");
  1943. }
  1944. if ($type == "object") {
  1945. $count = " - " . get_class($var);
  1946. }
  1947. $rtn .= "<div class='fp-html-print-r-multi-row'>
  1948. <div class='fp-html-print-r-selector'
  1949. onClick='\$(\"#fp-html-print-r-var-value-$rnd\").toggle(\"medium\");'
  1950. >
  1951. <span class='fp-html-print-r-var-name'>$name</span>
  1952. <span class='fp-html-print-r-var-type'>($type$count)</span>
  1953. </div>
  1954. <div class='fp-html-print-r-var-value' id='fp-html-print-r-var-value-$rnd' style='display: none;'>";
  1955. foreach ($var as $key => $value) {
  1956. $rtn .= fp_html_print_r($value, $key, ($cnt + 1), $max_levels);
  1957. }
  1958. $rtn .= "</div>
  1959. </div>";
  1960. }
  1961. else if ($type == "string" && strlen($var) > 50) {
  1962. // If the variable is fairly long, we want to also make it a hide-to-show type field.
  1963. $rtn .= "<div class='fp-html-print-r-multi-row'>
  1964. <div
  1965. onClick='\$(\"#fp-html-print-r-var-value-$rnd\").toggle(\"medium\");'
  1966. >
  1967. <span class='fp-html-print-r-var-name'>$name</span>
  1968. <span class='fp-html-print-r-var-type'>($type$count)</span>
  1969. <span class='fp-html-print-r-var-value-abbr'>" . htmlentities(substr($var, 0, 50)) . "...</span>
  1970. </div>
  1971. <div class='fp-html-print-r-var-value' id='fp-html-print-r-var-value-$rnd' style='display: none;'>
  1972. ";
  1973. $rtn .= htmlentities($var);
  1974. $rtn .= "</div></div>";
  1975. }
  1976. else {
  1977. $html_val = $var;
  1978. if ($type != "resource") {
  1979. $html_val = htmlentities("" . $var);
  1980. }
  1981. $rtn .= "<div class='fp-html-print-r-single-row'>
  1982. <span class='fp-html-print-r-var-name'>$name</span>
  1983. <span class='fp-html-print-r-var-type'>($type$count)</span>
  1984. <span class='fp-html-print-r-var-value'>$html_val</span>
  1985. </div>";
  1986. }
  1987. return $rtn;
  1988. }
  1989. /**
  1990. * This is used usually when being viewed by a mobile device.
  1991. * It will shorten a catalog year range of 2008-2009 to just
  1992. * "08-09" or "2008-09" or even "09-2009".
  1993. *
  1994. *
  1995. * @param string $cat_range - Ex: 2006-2007
  1996. */
  1997. function get_shorter_catalog_year_range($cat_range, $abbr_first = true, $abbr_second = true) {
  1998. $temp = explode("-", $cat_range);
  1999. $first = $temp[0];
  2000. $second = $temp[1];
  2001. if ($abbr_first) {
  2002. $first = substr($first, 2, 2);
  2003. }
  2004. if ($abbr_second) {
  2005. $second = substr($second, 2, 2);
  2006. }
  2007. return "$first-$second";
  2008. }
  2009. /**
  2010. * This will find and include the module in question, calling
  2011. * it's hook_init() function if it has one.
  2012. *
  2013. * Will return TRUE or FALSE for success or failure to include
  2014. * the module.
  2015. *
  2016. * If the use_module_path is set to some value, we will not attempt to use
  2017. * the setting for this module's path. Useful if we do not have the module in our
  2018. * modules table yet.
  2019. *
  2020. * Example use: include_module("course_search");
  2021. *
  2022. * @param string $module
  2023. */
  2024. function include_module($module, $bool_call_init = TRUE, $use_module_path = "") {
  2025. $system_path = trim($GLOBALS["fp_system_settings"]["file_system_path"]);
  2026. $module_path = "";
  2027. if (isset($GLOBALS["fp_system_settings"]["modules"][$module])) {
  2028. $module_path = $GLOBALS["fp_system_settings"]["modules"][$module]["path"];
  2029. }
  2030. if ($use_module_path != "") {
  2031. $module_path = $use_module_path;
  2032. }
  2033. if ($module_path != "") {
  2034. $path = $module_path . "/$module.module";
  2035. if (file_exists($system_path . "/" . $path)) {
  2036. require_once($system_path . "/" . $path);
  2037. }
  2038. else {
  2039. print "<br><b>Could not find module '$module' at '$system_path/$path'</b><br>";
  2040. }
  2041. // Now that we have included it, call the module's hook_init() method.
  2042. if ($bool_call_init) {
  2043. if (function_exists($module . "_init")) {
  2044. call_user_func($module . "_init");
  2045. }
  2046. }
  2047. return TRUE;
  2048. }
  2049. return FALSE;
  2050. }
  2051. /**
  2052. * Find and include the module's .install file, if it exists.
  2053. * Returns TRUE or FALSE if it was able to find & include the file.
  2054. */
  2055. function include_module_install($module, $path) {
  2056. $system_path = trim($GLOBALS["fp_system_settings"]["file_system_path"]);
  2057. $install_path = $path . "/$module.install";
  2058. if (file_exists($system_path . "/" . $install_path)) {
  2059. require_once($system_path . "/" . $install_path);
  2060. return TRUE;
  2061. }
  2062. return FALSE;
  2063. }
  2064. /**
  2065. * Creates a javascript "confirm" link, so when clicked it asks the user a question, then proceeds
  2066. * if they select OK. The main reason I want to do this is so I can pass the $question through
  2067. * my t() function. (do it when you call this function)
  2068. */
  2069. function fp_get_js_confirm_link($question, $action_if_yes, $link_text, $extra_class = "", $link_title = "") {
  2070. $rtn = "";
  2071. $question = fp_reduce_whitespace($question);
  2072. //$question = htmlentities($question, ENT_QUOTES);
  2073. //$question = str_replace("\n", "\\n", $question);
  2074. $question = str_replace("\\n", "<br>", $question);
  2075. $question = str_replace("\n", "<br>", $question);
  2076. $question_64 = base64_encode($question); // convert to base_64 so we can have HTML
  2077. $link_title = htmlentities($link_title, ENT_QUOTES);
  2078. //$rtn .= "<a href='javascript: if(fp_confirm(\"$question\")) { $action_if_yes; }' class='$extra_class' title='$link_title'>$link_text</a>";
  2079. // Using new fp_confirm code
  2080. $action_if_yes_64 = base64_encode($action_if_yes);
  2081. $rtn .= "<a href='javascript: fp_confirm(\"$question_64\",\"base64\",\"$action_if_yes_64\");' class='$extra_class' title='$link_title'>$link_text</a>";
  2082. return $rtn;
  2083. }
  2084. /**
  2085. * Creates a javascript "prompt" link, which will ask the user a question.
  2086. *
  2087. * Similar to the fp_get_js_confirm_link function, but this is a prompt box
  2088. * which lets the user type in a response.
  2089. *
  2090. *
  2091. * @see fp_get_js_confirm_link
  2092. */
  2093. function fp_get_js_prompt_link($question, $default, $action_if_yes, $link_text, $extra_class = "") {
  2094. $rtn = "";
  2095. $question = fp_reduce_whitespace($question);
  2096. $question = htmlentities($question, ENT_QUOTES);
  2097. $question = str_replace("\n", "\\n", $question);
  2098. $rtn .= "<a href='javascript: var response = prompt(\"$question\", \"$default\");
  2099. if (response != null)
  2100. {
  2101. $action_if_yes ;
  2102. }
  2103. ' class='$extra_class'>$link_text</a>";
  2104. return $rtn;
  2105. }
  2106. /**
  2107. * Creates a javascript "alert" link, which tells the user some message with javascript alert().
  2108. *
  2109. * Similar to the fp_get_js_confirm_link function, but this is a simple alert message,
  2110. * with no user input.
  2111. *
  2112. *
  2113. * @see fp_get_js_confirm_link
  2114. */
  2115. function fp_get_js_alert_link($message, $link_text = "", $extra_css_class = "") {
  2116. $rtn = "";
  2117. if ($link_text == "") {
  2118. $link_text = "[?]";
  2119. }
  2120. $message = str_replace("\n", " ", $message);
  2121. $message = fp_reduce_whitespace($message);
  2122. //$message = htmlentities($message, ENT_QUOTES);
  2123. //$message = str_replace("&quot;", "\&quot;", $message);
  2124. //$message = str_replace("[NL]", "<br>", $message);
  2125. //$rtn .= "<a href='javascript: alert(\"" . $message . "\");' class='fp-alert-link $extra_css_class'>$link_text</a>";
  2126. $rtn .= "<a href='javascript: fp_alert(\"" . base64_encode($message) . "\",\"base64\");' class='fp-alert-link $extra_css_class'>$link_text</a>";
  2127. return $rtn;
  2128. }
  2129. /**
  2130. * Simple helper function to reduce whitespace (like double-spaces)
  2131. *
  2132. * @param string $str
  2133. */
  2134. function fp_reduce_whitespace($str) {
  2135. // Cheap hack to get rid of whitespace
  2136. for ($t = 0; $t < 5; $t++) {
  2137. $str = str_replace(" ", " ", $str);
  2138. $str = str_replace("\n ", "\n", $str);
  2139. }
  2140. return $str;
  2141. }
  2142. /**
  2143. * Does the user have the specified role?
  2144. */
  2145. function user_has_role($role, $account = NULL) {
  2146. global $user;
  2147. if ($account == NULL) $account = $user;
  2148. // Admin always = TRUE
  2149. if ($account->id == 1) return TRUE;
  2150. // Check for other users...
  2151. if (in_array($role, $account->roles)) return TRUE;
  2152. return FALSE;
  2153. }
  2154. /**
  2155. * Returns TRUE or FALSE if the logged in user has access based on the
  2156. * permission supplied.
  2157. *
  2158. * @param String $permission
  2159. */
  2160. function user_has_permission($permission = "", $account = NULL) {
  2161. global $user;
  2162. if ($account == NULL) $account = $user;
  2163. //fpm("checking permission $permission");
  2164. // If the user is admin (id == 1) then they always have access.
  2165. if ($account->id == 1) return TRUE;
  2166. if (!isset($account->permissions) || !is_array($account->permissions)) return FALSE; // not set up yet; anonymous user most likely.
  2167. // Otherwise, simply check their permissions array.
  2168. if (in_array($permission, $account->permissions)) {
  2169. return TRUE;
  2170. }
  2171. return FALSE;
  2172. }
  2173. /**
  2174. * This function will read through all the modules' permissions and
  2175. * return back an array. Specifically, it retrieves arrays from each
  2176. * modules' hook_perm() function.
  2177. *
  2178. */
  2179. function get_modules_permissions() {
  2180. $rtn = array();
  2181. foreach ($GLOBALS["fp_system_settings"]["modules"] as $module => $value) {
  2182. if (isset($value["disabled"]) && $value["disabled"] == "yes") {
  2183. // Module is not enabled. Skip it.
  2184. continue;
  2185. }
  2186. if (function_exists($module . "_perm")) {
  2187. $rtn[$module][] = call_user_func($module . "_perm");
  2188. }
  2189. }
  2190. return $rtn;
  2191. }
  2192. /**
  2193. * Similar to get_modules_permissions, this will scan through all installed
  2194. * modules' hook_menu() functions, and assemble an array which is sorted
  2195. * by "location" and then by "weight".
  2196. *
  2197. */
  2198. function get_modules_menus() {
  2199. $menus = array();
  2200. foreach ($GLOBALS["fp_system_settings"]["modules"] as $module => $value) {
  2201. if (isset($value["disabled"]) && $value["disabled"] == "yes") {
  2202. // Module is not enabled. Skip it.
  2203. continue;
  2204. }
  2205. if (function_exists($module . "_menu")) {
  2206. $menus[] = call_user_func($module . "_menu");
  2207. }
  2208. }
  2209. // Let's re-order based on weight...
  2210. // Convert to a single dimensional array for easier sorting.
  2211. $temp = array();
  2212. foreach ($menus as $c => $value) {
  2213. foreach ($menus[$c] as $d => $menu_data) {
  2214. $w = $menu_data["weight"];
  2215. if ($w == "") $w = "0";
  2216. // We need to front-pad $w with zeros, so it is the same length
  2217. // for every entry. Otherwise it will not sort correctly.
  2218. $w = fp_number_pad($w, 10);
  2219. $temp[] = "$w~~$c~~$d";
  2220. }
  2221. }
  2222. //var_dump($temp);
  2223. // Now, sort $temp...
  2224. sort($temp);
  2225. //var_dump($temp);
  2226. // Now, go back through $temp and get our new array...
  2227. $new_array = array();
  2228. foreach ($temp as $t) {
  2229. $vals = explode("~~", $t);
  2230. $c = $vals[1];
  2231. $d = $vals[2];
  2232. // Place them into subarrays indexed by location
  2233. $new_array[$menus[$c][$d]["location"]][] = $menus[$c][$d];
  2234. }
  2235. return $new_array;
  2236. }
  2237. /**
  2238. * Simple function to left padd numbers with 0's.
  2239. * 1 becomes 001
  2240. * 20 becomes 020
  2241. * and so on.
  2242. *
  2243. * @param int $number
  2244. * @param int $n
  2245. * @return String
  2246. */
  2247. function fp_number_pad($number, $len) {
  2248. return str_pad((int) $number, $len, "0", STR_PAD_LEFT);
  2249. }
  2250. /**
  2251. * This simple function will take a number and truncate the number of decimals
  2252. * to the requested places. This can be used in place of number_format(), which *rounds*
  2253. * numbers.
  2254. *
  2255. * For example, number_format(1.99999, 2) gives you 2.00.
  2256. * But THIS function gives:
  2257. * fp_truncate_decimals(1.999999, 2) = 1.99
  2258. *
  2259. *
  2260. * @param unknown_type $places
  2261. */
  2262. function fp_truncate_decimals($num, $places = 2) {
  2263. // does $num contain a .? If not, add it on.
  2264. if (!strstr("" . $num, ".")) {
  2265. $num .= ".0";
  2266. }
  2267. // Break it by .
  2268. $temp = explode (".", "" . $num);
  2269. // Get just the decimals and trim 'em
  2270. $decimals = trim(substr($temp[1], 0, $places));
  2271. if (strlen($decimals) < $places) {
  2272. // Padd with zeros on the right!
  2273. $decimals = str_pad($decimals, $places, "0", STR_PAD_RIGHT);
  2274. }
  2275. $new_num = $temp[0] . "." . $decimals;
  2276. return $new_num;
  2277. }
  2278. /**
  2279. * Adapted from https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_query_string_encode/6.x
  2280. */
  2281. function fp_query_string_encode($query, $exclude = array(), $parent = '') {
  2282. $params = array();
  2283. foreach ($query as $key => $value) {
  2284. $key = rawurlencode($key);
  2285. if ($parent) {
  2286. $key = $parent . '[' . $key . ']';
  2287. }
  2288. if (in_array($key, $exclude)) {
  2289. continue;
  2290. }
  2291. if (is_array($value)) {
  2292. $params[] = fp_query_string_encode($value, $exclude, $key);
  2293. }
  2294. else {
  2295. $params[] = $key . '=' . rawurlencode($value);
  2296. }
  2297. }
  2298. return implode('&', $params);
  2299. }
  2300. /**
  2301. * Shortcut to fp_debug_current_time_millis()
  2302. *
  2303. * @see fp_debug_current_time_millis()
  2304. *
  2305. * @param unknown_type $debug_val
  2306. * @param unknown_type $var
  2307. * @return unknown
  2308. */
  2309. function fp_debug_ct($debug_val = "", $var = "")
  2310. { // Shortcut to the other function.
  2311. return fp_debug_current_time_millis($debug_val, false, $var);
  2312. }
  2313. /**
  2314. * When called repeatedly, this function will display a message along with a milisecond count
  2315. * out to the side. Very useful for developers to time function calls or queries, to see how long they
  2316. * are taking.
  2317. *
  2318. * For example:
  2319. * fp_debug_ct("starting query");
  2320. * db_query(".........") // whatever
  2321. * fp_debug_ct("finished query");
  2322. *
  2323. * On screen, that would display our messages, with time values, so we can see how many milliseconds
  2324. * it took to execute between calls of fp_debug_ct().
  2325. *
  2326. * @param String $debug_val
  2327. * The message to display on screen.
  2328. * @param boolean $show_current_time
  2329. * Should we display the current time as well?
  2330. * @param String $var
  2331. * Optional. Include a variable name so you can have more than one timer running
  2332. * at the same time.
  2333. * @return unknown
  2334. */
  2335. function fp_debug_current_time_millis($debug_val = "", $show_current_time = true, $var = "")
  2336. {
  2337. // Display the current time in milliseconds, and, if available,
  2338. // show how many milliseconds its been since the last time
  2339. // this function was called. This helps programmers tell how
  2340. // long a particular function takes to run. Just place a call
  2341. // to this function before and after the function call.
  2342. $rtn = "";
  2343. $debug_string = $debug_val;
  2344. if (is_array($debug_val) || is_object($debug_val)) {
  2345. $debug_string = "<pre>" . print_r($debug_val, true) . "</pre>";
  2346. }
  2347. $last_time = @($GLOBALS["current_time_millis" . $var]) * 1; //*1 forces numeric
  2348. $cur_time = microtime(true) * 1000;
  2349. $debug_string = "<span style='color:red;'>DEBUG:</span>
  2350. <span style='color:green;'>$debug_string</span>";
  2351. $rtn .= "<div style='background-color: white;'>$debug_string";
  2352. if ($last_time > 1)
  2353. {
  2354. $diff = round($cur_time - $last_time,2);
  2355. $rtn .= "<span style='color: blue;'> ($diff" . t("ms since last call") . "</span>";
  2356. } else {
  2357. // Start of clock...
  2358. $rtn .= "<span style='color: blue;'> --- </span>";
  2359. }
  2360. $rtn .= "</div>";
  2361. $GLOBALS["current_time_millis" . $var] = $cur_time;
  2362. $GLOBALS["current_time_millis"] = $cur_time;
  2363. return $rtn;
  2364. }

Functions

Namesort ascending Description
_fp_map_php_error_code Map an error code into an Error word *
_fp_error_handler This is our custom error handler, which will intercept PHP warnings, notices, etc, and let us display them, log them, etc.
user_has_role Does the user have the specified role?
user_has_permission Returns TRUE or FALSE if the logged in user has access based on the permission supplied.
timer_start Begin a microtime timer for later use.
timer_read Works with the timer_start() function to return how long it has been since the start.
t This function will facilitate translations by using hook_translate()
st Provides translation functionality when database is not available.
module_enabled Simple function that returns TRUE if the module is enabled, FALSE otherwise.
modules_implement_hook Return an array of enabled modules which implement the provided hook. Do not include the preceeding "_" on the hook name!
l This works like Drupal's l() function for creating links. Ex: l("Click here for course search!", "tools/course-search", "abc=xyz&hello=goodbye", array("class" => "my-class")); Do not…
is_serialized_string From: https://stackoverflow.com/questions/1369936/check-to-see-if-a-string-is-...
invoke_hook Invoke all module hooks for the supplied hook.
include_module_install Find and include the module's .install file, if it exists. Returns TRUE or FALSE if it was able to find & include the file.
include_module This will find and include the module in question, calling it's hook_init() function if it has one.
get_timezone_offset Returns the offset from the origin timezone to the remote timezone, in seconds.
get_timezones Returns an array of all timezones PHP recognizes. Inspired by code from: https://stackoverflow.com/questions/1727077/generating-a-drop-down-list-...
get_term_structures Return an array version of the term_id_structure field from the admin settings
get_term_description Convert a term ID into a description. Ex: 20095 = Spring of 2009.
get_shorter_catalog_year_range This is used usually when being viewed by a mobile device. It will shorten a catalog year range of 2008-2009 to just "08-09" or "2008-09" or even "09-2009".
get_modules_permissions This function will read through all the modules' permissions and return back an array. Specifically, it retrieves arrays from each modules' hook_perm() function.
get_modules_menus Similar to get_modules_permissions, this will scan through all installed modules' hook_menu() functions, and assemble an array which is sorted by "location" and then by "weight".
friendly_timezone Returns back the "friendly" timezone string if we have one.
fp_validate_utf8
fp_user_is_student Simply returns TRUE or FALSE if the user is a student. (has the is_student == 1
fp_url_get_contents This function uses CURL to get the simple contents of a URL, whether http or https.
fp_url This function will take a path, ex: "admin/config/module" and a query, ex: "nid=5&whatever=yes" And join them together, respecting whether or not clean URL's are enabled.
fp_truncate_decimals This simple function will take a number and truncate the number of decimals to the requested places. This can be used in place of number_format(), which *rounds* numbers.
fp_trim Adding fp_trim function for backwards compatibility with FP 7
fp_translate_numeric_grade This function will use the "Numeric to Letter Grade" setting in the School settings to translate the given grade (if it is numeric) to a letter grade. Otherwise, it will return the grade as-is.
fp_token Returns back the site's "token", which is a simply md5 of some randomness. It is used primarily with forms, to ensure against cross-site forgeries. The site's token gets saved to the variables table, for later use. The idea is…
fp_str_ends_with
fp_strip_dangerous_protocols
fp_space_csv Simple function that adds spaces after commas in CSV strings. Makes them easier to read.
fp_set_title Allows the programmer to set the title of the page, overwriting any default title.
fp_set_page_tabs If this function is called, it will override any other page tabs which might be getting constructed. This lets the programmer, at run-time, completely control what tabs are at the top of the page.
fp_set_page_sub_tabs Allows the programmer to define subtabs at the top of the page.
fp_set_breadcrumbs Set our breadcrumbs array.
fp_screen_is_mobile This function will attempt to determine automatically if we are on a mobile device, and should therefor use the mobile theme and layout settings.
fp_re_array_files Re-order the _FILES array for multiple files, to make it easier to work with. From: http://php.net/manual/en/features.file-upload.multiple.php
fp_reduce_whitespace Simple helper function to reduce whitespace (like double-spaces)
fp_recalculate_alert_count_by_type Invokes a hook to get numbers on the total, read, and unread values from our modules, to find out if we need to place a badge on the bell icon at the top of the screen.
fp_query_string_encode Adapted from https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_...
fp_number_pad Simple function to left padd numbers with 0's. 1 becomes 001 20 becomes 020 and so on.
fp_no_html_xss Remove any possiblilty of a malicious attacker trying to inject nonsense. From: https://paragonie.com/blog/2015/06/preventing-xss-vulnerabilities-in-php...
fp_mail Send an email. Drop-in replacement for PHP's mail() command, but can use SMTP protocol if enabled.
fp_load_degree This function provides a pass-thru to $d = new DegreePlan(args). However, it allows for quick caching look-up, so it should be used when possible instead of $x = new DegreePlan.
fp_join_assoc This function will create a string from a 1 dimensional assoc array. Ex: arr = array("pet" => "dog", "name" => "Rex") will return: pet_S-dog,name_S-Rex under the default settings.
fp_http_request Send a request through the Internet and return the result as an object.
fp_html_print_r Similar to print_r, this will return an HTML-friendly click-to-open system similar in design to Krumo.
fp_goto Redirect the user's browser to the specified internal path + query.
fp_get_terms_by_year_range Returns back a FAPI-compatible array of all term codes for the specified years, inclusive
fp_get_session_str This function will provide the session_id as a string, as well as a secret token we can use to make sure the session_id is authentic and came from us and not a hacker.
fp_get_session_id_from_str This will validate the session str (or the session_id.
fp_get_requirement_types Returns back an array of all the available requirement types (by code) that have been defined.
fp_get_random_string Returns a random string of length len.
fp_get_module_path Return the filepath to the module
fp_get_module_details Simply returns the module's row from the modules table, if it exists.
fp_get_machine_readable Simple function to convert a string into a machine-readable string.
fp_get_js_prompt_link Creates a javascript "prompt" link, which will ask the user a question.
fp_get_js_confirm_link Creates a javascript "confirm" link, so when clicked it asks the user a question, then proceeds if they select OK. The main reason I want to do this is so I can pass the $question through my t() function. (do it when you call this function)
fp_get_js_alert_link Creates a javascript "alert" link, which tells the user some message with javascript alert().
fp_get_files_path Convenience function to return the /files system path. Does NOT end with a trailing slash.
fp_get_departments Returns an array (suitable for form api) of departments on campus which faculty/staff can be members of.
fp_get_degree_classification_details Returns back an assoc array for the supplied code. Looks like: $arr["level_num"] = number $arr["title"] = the title
fp_get_degree_classifications Return back an assoc array of our set degree classifications, separated by "level"
fp_get_alert_count_by_type Returns back the total, read, and unread numbers previously calculated to see if we need to place a badge next to the bell icon at the top of the screen. If unset, we will call the recalculate function.
fp_explode_assoc Takes a string (created by fp_join_assoc()) and re-creates the 1 dimensional assoc array.
fp_debug_current_time_millis When called repeatedly, this function will display a message along with a milisecond count out to the side. Very useful for developers to time function calls or queries, to see how long they are taking.
fp_debug_ct Shortcut to fp_debug_current_time_millis()
fp_clear_cache Call all modules which implement hook_clear_cache
fp_add_message Add a "message" to the top of the screen. Useful for short messages like "You have been logged out" or "Form submitted successfully."
fp_add_js Add extra javascript to the page.
fp_add_css Add an extra CSS file to the page with this function. Ex: fp_add_css(fp_get_module_path("admin") . '/css/admin.css');
fp_add_body_class Add a CSS class to the body tag of the page. Useful for themeing later on.
fpmct Convenience function, will use fp_debug_ct() to display a message, and the number of miliseconds since its last call.
fpm Uses fp_add_message, but in this case, it also adds in the filename and line number which the message came from!
filter_xss_split Like the filter_xss function, this is taken from D7's _filter_xss_split function
filter_xss_bad_protocol
filter_xss_attributes
filter_xss This function is taken almost directly from Drupal 7's core code. It is used to help us filter out dangerous HTML which the user might type. From the D7 documentation:
filter_markup Filter string with possible HTML, allowing only certain tags, and removing dangerous attributes.
depricated_message Displays a depricated message on screen. Useful for tracking down when depricated functions are being used.
csv_to_form_api_array Splits a basic csv but returns an array suitable for the form_api, retuns assoc array.
csv_to_array Simple function to split a basic CSV string, trim all elements, then return the resulting array.
csv_multiline_to_array From https://www.php.net/manual/en/function.str-getcsv.php#117692
convert_time The point of this function is to convert between UTC (what we expect all times to start with.). If we're coming from the the database or a time() function, it's UTC. The "end_timezone_string" should be the user's preferred…
base_url Shortcut for getting the base_url variable from the global system settings.
base_path Shortcut for getting the base_path variable from the global system settings.
arg Returns the component of the page's path.