PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/supporting_functions.php

https://github.com/benblank/ureddit
PHP | 914 lines | 800 code | 79 blank | 35 comment | 99 complexity | 360b3834bbb686a615736dee0d34bf8f MD5 | raw file
  1. <?php
  2. define('COOKIE_SESSID','ureddit_sessid');
  3. define('PREFIX','');
  4. define('USE_MARKDOWN','true');
  5. define('SRVDOMAIN','http' . (isset($_SERVER['HTTPS']) && strlen($_SERVER['HTTPS']) > 0 ? "s" : "") . '://uofreddit.com');
  6. function render($__template, $__context=null)
  7. {
  8. if (is_array($__context))
  9. {
  10. foreach ($__context as $__key => $__value)
  11. {
  12. $$__key = $__value;
  13. }
  14. }
  15. include($__template);
  16. }
  17. function first_letter_subdir($str)
  18. {
  19. return $str[0] . '/' . $str;
  20. }
  21. function latest_blog_post($dbpdo)
  22. {
  23. if(config::wordpress)
  24. {
  25. $res = $dbpdo->query("SELECT `post_title`, `post_name`, `post_date` FROM `wp_posts` WHERE `post_status`='publish' AND `post_type`='post' ORDER BY `ID` DESC LIMIT 1", array());
  26. $year = date("Y", strtotime($res[0]['post_date']));
  27. $month = date("m", strtotime($res[0]['post_date']));
  28. $day = date("d", strtotime($res[0]['post_date']));
  29. return array('title' => $res[0]['post_title'], 'url' => '/blog/' . $year . '/' . $month . '/' . $day . '/' . $res[0]['post_name']);
  30. }
  31. else
  32. return array('title' => "Install WordPress or remove this box.", 'url' => "http://wordpress.com");
  33. }
  34. function latest_commit($dbpdo)
  35. {
  36. if(config::use_memcache)
  37. {
  38. if(!($val = $dbpdo->memcache->get('latest_commit')))
  39. {
  40. $fdata = new SimpleXMLElement(stripslashes(file_get_contents("https://github.com/ureddit/ureddit/commits/master.atom")), true);
  41. //$fdata = new SimpleXMLElement(file_get_contents("github.txt"), true);
  42. $val = array('title' => '' . $fdata->entry[0]->title, 'url' => '' . $fdata->entry[0]->link[0]['href']);
  43. $dbpdo->memcache_set('latest_commit',$val);
  44. }
  45. }
  46. else
  47. {
  48. $fdata = new SimpleXMLElement(stripslashes(file_get_contents("https://github.com/ureddit/ureddit/commits/master.atom")), true);
  49. //$fdata = new SimpleXMLElement(file_get_contents("github.txt"), true);
  50. $val = array('title' => $fdata->entry[0]->title, 'url' => $fdata->entry[0]->link[0]['href']);
  51. }
  52. return $val;
  53. }
  54. function translate_class_id($dbpdo,$old_id)
  55. {
  56. $translation = $dbpdo->query("SELECT new_id FROM class_id_translation WHERE old_id = ?", array($old_id));
  57. if(count($translation) > 0)
  58. return $translation[0]['new_id'];
  59. return false;
  60. }
  61. function votebox($class, $user = false)
  62. {
  63. $score = $class->calculate_score();
  64. if($user !== false)
  65. {
  66. if(isset($user->votes['downvoted']) && in_array($class->id, $user->votes['downvoted']))
  67. {
  68. echo '<img src="' . SRVDOMAIN . PREFIX . '/img/down-filled.png" alt="-1\'d" class="downvoted" onclick="$.post(\'' . PREFIX . '/vote.php\', {action: \'remove\', id: \'' . $class->id . '\'}, function(response) {$(\'#class' . $class->id . ' > .content > .voting\').html(response);})">';
  69. }
  70. else
  71. {
  72. echo '<img src="' . SRVDOMAIN . PREFIX . '/img/down.png" alt="-1" class="downvote" onclick="$.post(\'' . PREFIX . '/vote.php\', {action: \'downvote\', id: \'' . $class->id . '\'}, function(response) {$(\'#class' . $class->id . ' > .content > .voting\').html(response);})">';
  73. }
  74. if(isset($user->votes['upvoted']) && in_array($class->id, $user->votes['upvoted']))
  75. {
  76. echo '<img src="' . SRVDOMAIN . PREFIX . '/img/up-filled.png" alt="+1\'d" class="upvoted" onclick="$.post(\'' . PREFIX . '/vote.php\', {action: \'remove\', id: \'' . $class->id . '\'}, function(response) {$(\'#class' . $class->id . ' > .content > .voting\').html(response);})">';
  77. }
  78. else
  79. {
  80. echo '<img src="' . SRVDOMAIN . PREFIX . '/img/up.png" alt="+1" class="upvote" onclick="$.post(\'' . PREFIX . '/vote.php\', {action: \'upvote\', id: \'' . $class->id . '\'}, function(response) {$(\'#class' . $class->id . ' > .content > .voting\').html(response);})">';
  81. }
  82. }
  83. else
  84. {
  85. echo '<a href="' . PREFIX . '/login"><img src="' . SRVDOMAIN . PREFIX . '/img/down.png" alt="-1" class="downvote"></a>';
  86. echo '<a href="' . PREFIX . '/login"><img src="' . SRVDOMAIN . PREFIX . '/img/up.png" alt="+1" class="upvote"></a>';
  87. }
  88. echo $score . '&nbsp;';
  89. }
  90. function signup_button($user, $class_id)
  91. {
  92. /*
  93. class statuses:
  94. 0 cancelled
  95. 1 has not begun, open for signups
  96. 2 has not begun, closed to signups
  97. 3 running, open for signups
  98. 4 running, closed to signups
  99. 5 finished
  100. */
  101. if($user === false)
  102. $class = new course($user, $class_id);
  103. else
  104. $class = new course($user->dbpdo, $class_id);
  105. $status = $class->get_attribute_value('status');
  106. echo "<div id=\"button" . $class->id . "\">\n";
  107. if(!logged_in())
  108. {
  109. $text = array("0" => "canceled", "1" => "+add", "2" => "closed", "3" => "+add", "4" => "closed", "5" => "finished");
  110. ?>
  111. <div class="signup-button">
  112. <a href="<?=PREFIX ?>/login"><button class="button-add"><?=$text[$status] ?></button></a>
  113. </div></div>
  114. <?php
  115. return;
  116. }
  117. if(!$user->is_taking_class($class->id)) // if student is not in class
  118. {
  119. if(!$user->is_teaching_class($class->id))
  120. {
  121. if($status == "1" || $status == "3")
  122. {
  123. ?>
  124. <div class="signup-button">
  125. <a onclick="$.get('<?=PREFIX ?>/enroll.php',{id: '<?=$class->id ?>'}, function(data) { $('#button<?=$class->id ?>').html(data) });">
  126. <button class="button-add">
  127. +add
  128. </button>
  129. </a>
  130. </div>
  131. <?php
  132. } elseif($status == "5") {
  133. ?>
  134. <div class="signup-button">
  135. <a class="link-signup-button">
  136. <button class="button-add">
  137. finished
  138. </button>
  139. </a>
  140. </div>
  141. <?php
  142. } elseif($status == "2" || $status == "4") {
  143. ?>
  144. <div class="signup-button">
  145. <a class="link-signup-button">
  146. <button class="button-add">
  147. closed
  148. </button>
  149. </a>
  150. </div>
  151. <?php
  152. } elseif($status == "0") {
  153. ?>
  154. <div class="signup-button">
  155. <button class="button-add">
  156. canceled
  157. </button>
  158. </div>
  159. <?php
  160. }
  161. }
  162. else
  163. {
  164. ?>
  165. <div class="teacher-button">
  166. <a href="<?=PREFIX ?>/teachers/" class="link-signup-button">
  167. teacher
  168. </a>
  169. </div>
  170. <?php
  171. }
  172. }
  173. else
  174. {
  175. ?>
  176. <div class="signup-button">
  177. <a onclick="$.get('<?=PREFIX ?>/drop_class.php',{id: '<?=$class->id ?>'}, function(data) { $('#button<?=$class->id ?>').html(data) });" class="link-signup-button">
  178. <button class="button-added">
  179. enrolled
  180. </button>
  181. </a>
  182. </div>
  183. <?
  184. }
  185. echo "</div>\n";
  186. }
  187. function get_feed($user)
  188. {
  189. $items = array();
  190. $actions = $user->dbpdo->query("SELECT * FROM `activity` WHERE `parent_id` = ? ORDER BY `datetime` DESC LIMIT 25", array($user->id));
  191. foreach($actions as $action)
  192. {
  193. if(is_null($action['child_id']))
  194. $items[] = '<li><strong>' . $user->value . '</strong> ' . $action['action'] . '<br><small><em>' . $action['datetime'] . '</em></small></li>';
  195. else
  196. {
  197. $object = new object($user->dbpdo, $action['child_id']);
  198. $items[] = '<li><strong>' . $user->value . '</strong> ' . $action['action'] . ' <strong>' . $object->value . '</strong><br><small><em>' . $action['datetime'] . '</em></small></li>';
  199. }
  200. }
  201. if(empty($items))
  202. $items[] = "<em>no user activity found</em>";
  203. return $items;
  204. }
  205. function display_schedule($user)
  206. {
  207. $user->get_schedule();
  208. $categories = array();
  209. $sorted_categories = array();
  210. foreach($user->schedule as $class_id)
  211. {
  212. $class = new course($user->dbpdo, $class_id);
  213. if($class->get_attribute_value('status') == '0')
  214. continue;
  215. $class->get_categories();
  216. foreach($class->categories as $category_id)
  217. $categories[$category_id][] = $class;
  218. }
  219. foreach($categories as $category_id => &$classes)
  220. {
  221. $category = new category($user->dbpdo, $category_id);
  222. $category_objects[$category_id] = $category;
  223. $sorted_categories[$category_id] = $category->value;
  224. }
  225. asort($sorted_categories);
  226. foreach($sorted_categories as $category_id => $category_value)
  227. {
  228. ?>
  229. <div class="category">
  230. <div class="content">
  231. <?php
  232. echo $category_value;
  233. foreach($categories[$category_id] as $class)
  234. $class->display_with_container();
  235. ?>
  236. </div>
  237. </div>
  238. <?php
  239. }
  240. }
  241. function list_teacher_classes($user)
  242. {
  243. $user->get_taught_classes();
  244. $categories = array();
  245. foreach($user->teaching as $class_id)
  246. {
  247. $class = new course($user->dbpdo, $class_id);
  248. $class->get_categories();
  249. foreach($class->categories as $category_id)
  250. $categories[$category_id][] = $class;
  251. }
  252. foreach($categories as $category_id => $classes)
  253. {
  254. $category = new category($user->dbpdo, $category_id);
  255. ?>
  256. <div id="category<?=$category->id ?>" class="category">
  257. <div class="content">
  258. <?=$category->value ?>
  259. <?php
  260. foreach($classes as $class)
  261. $class->display_with_container(true);
  262. ?>
  263. </div>
  264. </div>
  265. <?php
  266. }
  267. }
  268. function object_type_value_to_id($dbpdo, $type, $value)
  269. {
  270. return $dbpdo->query("SELECT `id` FROM `objects` WHERE `type` = ? AND `value` = ?",
  271. array(
  272. $type,
  273. $value
  274. ));
  275. }
  276. function latest_reddit_post($dbpdo)
  277. {
  278. if(config::use_memcache)
  279. {
  280. if(!($val = $dbpdo->memcache_get('latest_reddit_post')))
  281. {
  282. $json = json_decode(file_get_contents('/srv/http/ureddit.com/public_html/reddit.json'), true);
  283. $val = array('url' => 'http://reddit.com' . $json['data']['children'][0]['data']['permalink'], 'title' => $json['data']['children'][0]['data']['title']);
  284. $dbpdo->memcache_set('latest_reddit_post', $val);
  285. }
  286. }
  287. else
  288. {
  289. $json = json_decode(file_get_contents('/srv/http/ureddit.com/public_html/reddit.json'), true);
  290. $val = array('url' => 'http://reddit.com' . $json['data']['children'][0]['data']['permalink'], 'title' => $json['data']['children'][0]['data']['title']);
  291. }
  292. return $val;
  293. }
  294. function latest_tweet($dbpdo)
  295. {
  296. $config = $dbpdo->config;
  297. if(config::use_memcache)
  298. {
  299. if(!($val = $dbpdo->memcache_get('latest_tweet')))
  300. {
  301. try
  302. {
  303. $t = new Twitter($config::twitterConsumerKey, $config::twitterConsumerSecret, $config::twitterAccessToken, $config::twitterAccessTokenSecret);
  304. $latest = $t->load(Twitter::ME,1);
  305. $val = array('text' => Twitter::clickable($latest->status->text), 'url' => 'http://twitter.com/uofreddit/status/' . $latest->status->id);
  306. $dbpdo->memcache_set('latest_tweet',$val,60);
  307. }
  308. catch (TwitterException $e)
  309. {
  310. return array('text' => 'Error fetching tweets. Click to go to the @uofreddit Twitter feed.', 'url' => 'http://twitter.com/uofreddit');
  311. }
  312. }
  313. }
  314. else
  315. {
  316. try
  317. {
  318. $t = new Twitter($config::twitterConsumerKey, $config::twitterConsumerSecret, $config::twitterAccessToken, $config::twitterAccessTokenSecret);
  319. $latest = $t->load(Twitter::ME,1);
  320. $val = array('text' => Twitter::clickable($latest->status->text), 'url' => 'http://twitter.com/uofreddit/status/' . $latest->status->id);
  321. memcache_set('latest_tweet',$val,300);
  322. }
  323. catch (TwitterException $e)
  324. {
  325. return array('text' => 'Error fetching tweets. Click to go to the @uofreddit Twitter feed.', 'url' => 'http://twitter.com/uofreddit');
  326. }
  327. }
  328. return $val;
  329. }
  330. function tweet($config,$status)
  331. {
  332. $t = new Twitter($config::twitterConsumerKey, $config::twitterConsumerSecret, $config::twitterAccessToken, $config::twitterAccessTokenSecret);
  333. $t->send($status);
  334. }
  335. function category_dropdown($dbpdo, $name, $selected_val = "")
  336. {
  337. $categories = $dbpdo->query("SELECT * FROM `objects` WHERE `type` = ? ORDER BY `value` ASC", array('category'));
  338. ?><select name="<?=$name ?>" class="teach"><?php
  339. foreach($categories as $cat)
  340. {
  341. ?><option <?=($cat['id'] == $selected_val ? "SELECTED" : "") ?> value="<?=$cat['id'] ?>"><?=$cat['value'] ?></option><?php
  342. }
  343. ?></select><?
  344. }
  345. function num_sent_messages($user)
  346. {
  347. $sent = $user->dbpdo->query("SELECT COUNT(*) FROM associations WHERE type = ? AND parent_id = ?", array('message','$user->id'));
  348. return $sent[0]['COUNT(*)'];
  349. }
  350. function num_messages($user)
  351. {
  352. $num = $user->dbpdo->query("SELECT COUNT(*) FROM associations WHERE type = ? AND child_id = ?", array('message','$user->id'));
  353. return $num[0]['COUNT(*)'];
  354. }
  355. // this function is not original, it was found online
  356. // I have lost my record of who the author was; if found,
  357. // I will give credit
  358. function encrypt($toEncrypt,$privatekey)
  359. {
  360. $priv = openssl_pkey_get_private ($privatekey);
  361. $toEncrypt = unpack('H*', $toEncrypt);
  362. $toEncrypt = $toEncrypt[1];
  363. $result = "";
  364. while(strlen($toEncrypt)%16 != 0){
  365. $toEncrypt .= "00";
  366. }
  367. $iv = "1234567812345678";
  368. for($i = 0; $i < strlen($toEncrypt); $i+=16){
  369. $p = substr($toEncrypt, $i, 16);
  370. $x = $p ^ $iv;
  371. if(!openssl_private_encrypt($x, $e, $priv, OPENSSL_NO_PADDING)){
  372. throw new Exception(openssl_error_string());
  373. }
  374. $iv = $e ^ $p;
  375. $result .= $e;
  376. }
  377. $result = unpack('H*', $result);
  378. return $result[1];
  379. }
  380. function post($name, $default = "")
  381. {
  382. if(!empty($_POST) && isset($_POST[$name]))
  383. return htmlspecialchars(stripslashes($_POST[$name]));
  384. return htmlspecialchars(stripslashes($default));
  385. }
  386. function display_messages($user, $offset = 0, $limit=15)
  387. {
  388. $found = 0;
  389. $unread = array();
  390. $user->get_inbox($offset, $limit*2);
  391. for($i = 0; $i < count($user->inbox)/2; $i++)
  392. {
  393. if($user->get_object_type($user->inbox[2*$i]['parent_id']) == 'class')
  394. {
  395. $sender = new user($user->dbpdo, $user->inbox[2*$i]['parent_id']);
  396. if($sender->type == 'class')
  397. {
  398. $author = $sender->dbpdo->query("SELECT value FROM association_attributes WHERE association_id = ? AND type = ?",
  399. array(
  400. $user->inbox[2*$i]['association_id'],
  401. 'author'
  402. ));
  403. $author = new user($sender->dbpdo, $author[0]['value']);
  404. }
  405. $found = 1;
  406. }
  407. else
  408. {
  409. $sender = new user($user->dbpdo, $user->inbox[2*$i]['parent_id']);
  410. $found = 1;
  411. }
  412. ?>
  413. <div class="message">
  414. <div class="content">
  415. <div class="subject"><?=$user->inbox[2*$i]['value'] ?></div>
  416. <div class="body"><?=$user->process_text($user->inbox[2*$i+1]['value']) ?></div>
  417. <div class="signature">from <strong><?=($sender->type == 'class' ? $author->value . '</strong> (regarding class <strong><a href="' . PREFIX . "/class/" . $sender->id . '">' . $sender->value . '</a></strong>)' : $sender->value) . '</strong>'?> at <?=$user->inbox[2*$i]['creation'] ?> [<a href="<?=PREFIX ?>/user/<?=($sender->type == 'class' ? $author->value : $sender->value) ?>" class="link-class-desc">reply</a>]</div>
  418. </div>
  419. </div>
  420. <?php
  421. }
  422. if($found == 0)
  423. {
  424. ?>
  425. <div class="message">
  426. <p><em>you have no new messages</em></p>
  427. </div>
  428. <?php
  429. }
  430. $user->dbpdo->query("UPDATE `associations` SET `type` = ? WHERE type = ? AND child_id = ?",
  431. array(
  432. 'read_mass_message',
  433. 'unread_mass_message',
  434. $user->id
  435. ));
  436. $user->dbpdo->query("UPDATE `associations` SET `type` = ? WHERE type = ? AND child_id = ?",
  437. array(
  438. 'read_message',
  439. 'unread_message',
  440. $user->id
  441. ));
  442. }
  443. function display_sent_messages($user, $offset = 0, $limit=15)
  444. {
  445. $found = 0;
  446. $unread = array();
  447. $user->get_outbox($offset, $limit*2);
  448. for($i = 0; $i < count($user->outbox)/2; $i++)
  449. {
  450. $receipient = new user($user->dbpdo, $user->outbox[2*$i]['child_id']);
  451. $found = 1;
  452. ?>
  453. <div class="message">
  454. <div class="content">
  455. <div class="subject"><?=$user->outbox[2*$i]['value'] ?></div>
  456. <div class="body"><?=$user->process_text($user->outbox[2*$i+1]['value']) ?></div>
  457. <div class="signature">to <strong><?=$receipient->value ?></strong> at <?=$user->outbox[$i]['creation'] ?> [<a href="<?=PREFIX ?>/user/<?=$recepient->value ?>" class="link-class-desc">reply</a>]</div>
  458. </div>
  459. </div>
  460. <?php
  461. }
  462. if($found == 0)
  463. {
  464. ?>
  465. <div class="message">
  466. <p><em>you have no new messages</em></p>
  467. </div>
  468. <?php
  469. }
  470. }
  471. function generate_random_password()
  472. {
  473. $pass = "";
  474. for($i = 0; $i < 16; $i++)
  475. $pass .= chr((rand(0,5) < 5 ? (int) rand(65,90) : (int)rand(97,122)));
  476. return $pass;
  477. }
  478. function send_user_to($place,$domain="ureddit.com",$http_code = NULL)
  479. {
  480. $s = isset($_SERVER['HTTPS']) && strlen($_SERVER['HTTPS']) > 0 ? "s" : "";
  481. if($http_code !== NULL)
  482. header("HTTP/1.1 $http_code");
  483. header("Location: http$s://" . str_replace('universityofreddit','ureddit',$_SERVER['SERVER_NAME']) . PREFIX . $place);
  484. die();
  485. }
  486. function process($text)
  487. {
  488. if(USE_MARKDOWN == "true")
  489. return Markdown(htmlspecialchars(stripslashes($text)));
  490. return nl2br(htmlspecialchars(stripslashes($text)));
  491. }
  492. function logged_in()
  493. {
  494. if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] != "true")
  495. return false;
  496. return true;
  497. }
  498. function logout($dbpdo)
  499. {
  500. $dbpdo->query("DELETE FROM `sessions` WHERE `object_id` = ?", array($dbpdo->session('user_id')));
  501. setcookie(COOKIE_SESSID,"",time()-60*60*24);
  502. $_SESSION = array();
  503. session_destroy();
  504. send_user_to("/");
  505. }
  506. function cookie_exists()
  507. {
  508. if(isset($_COOKIE[COOKIE_SESSID]))
  509. return true;
  510. return false;
  511. }
  512. function login($user)
  513. {
  514. $_SESSION['logged_in'] = "true";
  515. $_SESSION['user_id'] = $user->id;
  516. $_SESSION['username'] = $user->value;
  517. setcookie(COOKIE_SESSID,session_id(),time()-60*60*24);
  518. }
  519. function send_email($from, $to, $subject, $message, $internalid = false)
  520. {
  521. $fHeaders = "To: " . $to . "\n";
  522. $fHeaders .= "From: " . $from . "\n";
  523. $fHeaders .= "Subject: " . encode_header ($subject) . "\n";
  524. $fHeaders .= "MIME-Version: 1.0\n";
  525. if($internalid !== false)
  526. $fHeaders .= "Association: $internalid\r\n";
  527. //$fHeaders .= "Content-Type: text/plain; charset=utf-8\n";
  528. //$fHeaders .= "Content-Transfer-Encoding: 8bit\n";
  529. $fHeaders .= "Content-Type: text/html; charset=utf-8\r\n";
  530. $fHeaders .= "<html><body>\n";
  531. $fHeaders .= $message;
  532. $fHeaders .= "</body></html>\n";
  533. $errno = "0";
  534. $errstr = "0";
  535. $fh = @fsockopen ('localhost', '25', $errno, $errstr, '30');
  536. if ($fh)
  537. {
  538. $res = smtp_get_response($fh);
  539. fputs ($fh, "EHLO localhost\r\n");
  540. $res = smtp_get_response($fh);
  541. fputs ($fh, "MAIL FROM:<$from>\r\n");
  542. $res = smtp_get_response($fh);
  543. fputs ($fh, "RCPT TO:<$to>\r\n");
  544. $res = smtp_get_response($fh);
  545. fputs ($fh, "DATA\r\n");
  546. $res = smtp_get_response($fh);
  547. fputs ($fh, "$fHeaders\r\n.\r\n");
  548. $res = smtp_get_response($fh);
  549. fputs ($fh, "QUIT\r\n");
  550. $res = smtp_get_response($fh);
  551. fclose ($fh);
  552. return true;
  553. }
  554. else
  555. return false;
  556. }
  557. function encode_header($string, $default_charset = "utf-8")
  558. {
  559. if (strtolower ($default_charset) == 'iso-8859-1')
  560. {
  561. $string = str_replace ("\240",' ',$string);
  562. }
  563. $j = strlen ($string);
  564. $max_l = 75 - strlen ($default_charset) - 7;
  565. $aRet = array ();
  566. $ret = '';
  567. $iEncStart = $enc_init = false;
  568. $cur_l = $iOffset = 0;
  569. for ($i = 0; $i < $j; ++$i)
  570. {
  571. switch ($string{$i})
  572. {
  573. case '=':
  574. case '<':
  575. case '>':
  576. case ',':
  577. case '?':
  578. case '_':
  579. if ($iEncStart === false)
  580. {
  581. $iEncStart = $i;
  582. }
  583. $cur_l+=3;
  584. if ($cur_l > ($max_l-2))
  585. {
  586. $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
  587. $aRet[] = "=?$default_charset?Q?$ret?=";
  588. $iOffset = $i;
  589. $cur_l = 0;
  590. $ret = '';
  591. $iEncStart = false;
  592. }
  593. else
  594. {
  595. $ret .= sprintf ("=%02X",ord($string{$i}));
  596. }
  597. break;
  598. case '(':
  599. case ')':
  600. if ($iEncStart !== false)
  601. {
  602. $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
  603. $aRet[] = "=?$default_charset?Q?$ret?=";
  604. $iOffset = $i;
  605. $cur_l = 0;
  606. $ret = '';
  607. $iEncStart = false;
  608. }
  609. break;
  610. case ' ':
  611. if ($iEncStart !== false)
  612. {
  613. $cur_l++;
  614. if ($cur_l > $max_l)
  615. {
  616. $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
  617. $aRet[] = "=?$default_charset?Q?$ret?=";
  618. $iOffset = $i;
  619. $cur_l = 0;
  620. $ret = '';
  621. $iEncStart = false;
  622. }
  623. else
  624. {
  625. $ret .= '_';
  626. }
  627. }
  628. break;
  629. default:
  630. $k = ord ($string{$i});
  631. if ($k > 126)
  632. {
  633. if ($iEncStart === false)
  634. {
  635. // do not start encoding in the middle of a string, also take the rest of the word.
  636. $sLeadString = substr ($string,0,$i);
  637. $aLeadString = explode (' ',$sLeadString);
  638. $sToBeEncoded = array_pop ($aLeadString);
  639. $iEncStart = $i - strlen ($sToBeEncoded);
  640. $ret .= $sToBeEncoded;
  641. $cur_l += strlen ($sToBeEncoded);
  642. }
  643. $cur_l += 3;
  644. // first we add the encoded string that reached it's max size
  645. if ($cur_l > ($max_l-2))
  646. {
  647. $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
  648. $aRet[] = "=?$default_charset?Q?$ret?= ";
  649. $cur_l = 3;
  650. $ret = '';
  651. $iOffset = $i;
  652. $iEncStart = $i;
  653. }
  654. $enc_init = true;
  655. $ret .= sprintf ("=%02X", $k);
  656. }
  657. else
  658. {
  659. if ($iEncStart !== false)
  660. {
  661. $cur_l++;
  662. if ($cur_l > $max_l)
  663. {
  664. $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
  665. $aRet[] = "=?$default_charset?Q?$ret?=";
  666. $iEncStart = false;
  667. $iOffset = $i;
  668. $cur_l = 0;
  669. $ret = '';
  670. }
  671. else
  672. {
  673. $ret .= $string{$i};
  674. }
  675. }
  676. }
  677. break;
  678. }
  679. }
  680. if ($enc_init)
  681. {
  682. if ($iEncStart !== false)
  683. {
  684. $aRet[] = substr ($string,$iOffset,$iEncStart-$iOffset);
  685. $aRet[] = "=?$default_charset?Q?$ret?=";
  686. }
  687. else
  688. {
  689. $aRet[] = substr ($string,$iOffset);
  690. }
  691. $string = implode ('',$aRet);
  692. }
  693. return $string;
  694. }
  695. function pacrypt ($pw, $salt,$pw_db="")
  696. {
  697. $pw = stripslashes($pw);
  698. $password = "";
  699. //$salt = "uofr!336";
  700. $split_salt = preg_split ('/\$/', $pw_db);
  701. if (isset ($split_salt[2])) {
  702. $salt = $split_salt[2];
  703. }
  704. $password = md5crypt ($pw, $salt);
  705. $password = escape_string ($password);
  706. return $password;
  707. }
  708. function escape_string ($string)
  709. {
  710. // if the string is actually an array, do a recursive cleaning.
  711. // Note, the array keys are not cleaned.
  712. if(is_array($string)) {
  713. $clean = array();
  714. foreach(array_keys($string) as $row) {
  715. $clean[$row] = escape_string($string[$row]);
  716. }
  717. return $clean;
  718. }
  719. if (get_magic_quotes_gpc ())
  720. {
  721. $string = stripslashes($string);
  722. }
  723. if (!is_numeric($string))
  724. {
  725. $escaped_string = ($string);
  726. }
  727. else
  728. {
  729. $escaped_string = $string;
  730. }
  731. return $escaped_string;
  732. }
  733. function md5crypt ($pw, $salt="", $magic="")
  734. {
  735. $MAGIC = "$1$";
  736. if ($magic == "") $magic = $MAGIC;
  737. $slist = explode ("$", $salt);
  738. if ($slist[0] == "1") $salt = $slist[1];
  739. $salt = substr ($salt, 0, 8);
  740. $ctx = $pw . $magic . $salt;
  741. $final = hex2bin (md5 ($pw . $salt . $pw));
  742. for ($i=strlen ($pw); $i>0; $i-=16)
  743. {
  744. if ($i > 16)
  745. {
  746. $ctx .= substr ($final,0,16);
  747. }
  748. else
  749. {
  750. $ctx .= substr ($final,0,$i);
  751. }
  752. }
  753. $i = strlen ($pw);
  754. while ($i > 0)
  755. {
  756. if ($i & 1) $ctx .= chr (0);
  757. else $ctx .= $pw[0];
  758. $i = $i >> 1;
  759. }
  760. $final = hex2bin (md5 ($ctx));
  761. for ($i=0;$i<1000;$i++)
  762. {
  763. $ctx1 = "";
  764. if ($i & 1)
  765. {
  766. $ctx1 .= $pw;
  767. }
  768. else
  769. {
  770. $ctx1 .= substr ($final,0,16);
  771. }
  772. if ($i % 3) $ctx1 .= $salt;
  773. if ($i % 7) $ctx1 .= $pw;
  774. if ($i & 1)
  775. {
  776. $ctx1 .= substr ($final,0,16);
  777. }
  778. else
  779. {
  780. $ctx1 .= $pw;
  781. }
  782. $final = hex2bin (md5 ($ctx1));
  783. }
  784. $passwd = "";
  785. $passwd .= to64 (((ord ($final[0]) << 16) | (ord ($final[6]) << 8) | (ord ($final[12]))), 4);
  786. $passwd .= to64 (((ord ($final[1]) << 16) | (ord ($final[7]) << 8) | (ord ($final[13]))), 4);
  787. $passwd .= to64 (((ord ($final[2]) << 16) | (ord ($final[8]) << 8) | (ord ($final[14]))), 4);
  788. $passwd .= to64 (((ord ($final[3]) << 16) | (ord ($final[9]) << 8) | (ord ($final[15]))), 4);
  789. $passwd .= to64 (((ord ($final[4]) << 16) | (ord ($final[10]) << 8) | (ord ($final[5]))), 4);
  790. $passwd .= to64 (ord ($final[11]), 2);
  791. return "$magic$salt\$$passwd";
  792. }
  793. /*
  794. function hex2bin ($str)
  795. {
  796. $len = strlen ($str);
  797. $nstr = "";
  798. for ($i=0;$i<$len;$i+=2)
  799. {
  800. $num = sscanf (substr ($str,$i,2), "%x");
  801. $nstr.=chr ($num[0]);
  802. }
  803. return $nstr;
  804. }
  805. */
  806. function to64 ($v, $n)
  807. {
  808. $ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  809. $ret = "";
  810. while (($n - 1) >= 0)
  811. {
  812. $n--;
  813. $ret .= $ITOA64[$v & 0x3f];
  814. $v = $v >> 6;
  815. }
  816. return $ret;
  817. }
  818. function has_new_messages($dbpdo, $user_id)
  819. {
  820. $unread = $dbpdo->query("SELECT COUNT(*) FROM associations WHERE child_id = ? AND (type = ? OR type = ?)",array($user_id, 'unread_message', 'unread_mass_message'));
  821. return !($unread[0]['COUNT(*)'] == '0');
  822. }
  823. function smtp_get_response ($fh)
  824. {
  825. $res ='';
  826. do
  827. {
  828. $line = fgets($fh, 256);
  829. $res .= $line;
  830. }
  831. while (preg_match("/^\d\d\d\-/", $line));
  832. return $res;
  833. }
  834. ?>