PageRenderTime 68ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/db/library/dbscript/_functions.php

https://github.com/tjgillies/openmicroblogger
PHP | 3602 lines | 2351 code | 756 blank | 495 comment | 423 complexity | 552a6833cb3322980582cc89a74fbed7 MD5 | raw file
Possible License(s): LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * dbscript -- restful openid framework
  4. * @version 0.6.0 -- 22-October-2008
  5. * @author Brian Hendrickson <brian@dbscript.net>
  6. * @link http://dbscript.net/
  7. * @copyright Copyright 2009 Brian Hendrickson
  8. * @package dbscript
  9. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  10. */
  11. /**
  12. * classify
  13. *
  14. * takes a table/resource name ('entries')
  15. * makes it singular & capitalized ('Entry')
  16. * massively crude, needs replacing with actual inflector
  17. *
  18. * @access public
  19. * @param string $resource
  20. * @return string
  21. */
  22. function classify( $resource ) {
  23. $inflector =& Inflector::getInstance();
  24. if (substr($resource,2,1) == '_')
  25. $resouce = substr($resource,3);
  26. return $inflector->classify($resource);
  27. }
  28. /**
  29. * tableize
  30. *
  31. * takes a (CamelCase or not) name ('DbSession')
  32. * makes it lower_case and plural ('db_sessions')
  33. * this implementation is just stupid and needs replacing
  34. *
  35. * @access public
  36. * @param string $table
  37. * @return string
  38. */
  39. function tableize( $object ) {
  40. $inflector =& Inflector::getInstance();
  41. return $inflector->tableize($object);
  42. }
  43. /**
  44. * Error
  45. *
  46. * custom Error handling per-client-type
  47. *
  48. * @author Brian Hendrickson <brian@dbscript.net>
  49. * @access public
  50. * @param integer $errno
  51. * @param string $errstr
  52. * @param string $errfile
  53. * @param integer $errline
  54. * @todo return based on content-negotiation status
  55. */
  56. function dbscript_error( $errno, $errstr, $errfile, $errline ) {
  57. if ( !error_reporting() || $errno == 2048 )
  58. return;
  59. switch ($errno) {
  60. case E_USER_ERROR:
  61. global $request;
  62. $req =& $request;
  63. if (isset($_GET['dbscript_xml_error_continue'])) {
  64. $xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
  65. $xml .= "<root>\n";
  66. $xml .= " <dbscript_error>Fatal error in line $errline of file $errfile<br />: $errstr</dbscript_error>\n";
  67. $xml .= "</root>\n";
  68. print $xml;
  69. } elseif ($req->error) {
  70. $req->handle_error( $errstr );
  71. print "<b>ERROR</b> [$errno] $errstr<br />\n";
  72. print " Fatal error in line $errline of file $errfile<br />\n";
  73. print "Aborting...<br />\n";
  74. } else {
  75. print "<br /><br />$errstr<br /><br />\n";
  76. print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<form><input type=\"submit\" value=\"&lt; &lt; Go Back\" onClick=\"JavaScript:document.history.back();\" /></form>";
  77. if (environment('debug_enabled'))
  78. print " Fatal error in line $errline of file $errfile<br />\n";
  79. }
  80. $path = '/var/www/tweetiepic/logs/';
  81. $file = $path.substr( microtime(), 0, 7);
  82. $fd = fopen($file , "a+");
  83. global $request;
  84. if (isset($request->uri))
  85. $data = "ERROR ".serialize($errstr).' '.serialize($errfile).' '.serialize($errline)." ".$request->uri."\n\n\n";
  86. else
  87. $data = "ERROR ".serialize($errstr).' '.serialize($errfile).' '.serialize($errline)." "."\n\n\n";
  88. if ($fd) {
  89. $result = fwrite( $fd, $data );
  90. fclose($fd);
  91. }
  92. exit(1);
  93. case E_USER_WARNING:
  94. //print "<b>WARNING</b> [$errno] $errstr<br />\n";
  95. $path = '/var/www/tweetiepic/logs/';
  96. $file = $path.substr( microtime(), 0, 7);
  97. $fd = fopen($file , "a+");
  98. $data = "WARNING ".serialize($errstr).' '.serialize($errfile).' '.serialize($errline)."\n\n";
  99. if ($fd) {
  100. $result = fwrite( $fd, $data );
  101. fclose($fd);
  102. }
  103. break;
  104. case E_USER_NOTICE:
  105. print "<b>NOTICE</b> [$errno] $errstr<br />\n";
  106. }
  107. }
  108. function microtime_float() {
  109. list($usec, $sec) = explode(" ", microtime());
  110. return ((float)$usec + (float)$sec);
  111. }
  112. /**
  113. * Trigger Before
  114. *
  115. * trip before filters for a function
  116. *
  117. * @access public
  118. * @param string $func
  119. * @param object $obj_a
  120. * @param object $obj_b
  121. */
  122. function trigger_before( $func, &$obj_a, &$obj_b ) {
  123. if (environment('show_timer')) {
  124. global $exec_time;
  125. $time_end = microtime_float();
  126. $time = $time_end - $exec_time;
  127. $diff = substr($time,1,5);
  128. echo "$diff seconds <br />$func ";
  129. }
  130. if ( isset( $GLOBALS['ASPECTS']['before'][$func] ) ) {
  131. foreach( $GLOBALS['ASPECTS']['before'][$func] as $callback ) {
  132. call_user_func_array( $callback, array( $obj_a, $obj_b ) );
  133. }
  134. }
  135. }
  136. /**
  137. * Trigger After
  138. *
  139. * trip after filters for a function
  140. *
  141. * @access public
  142. * @param string $func
  143. * @param object $obj_a
  144. * @param object $obj_b
  145. */
  146. function trigger_after( $func, &$obj_a, &$obj_b ) {
  147. if ( isset( $GLOBALS['ASPECTS']['after'][$func] ) ) {
  148. foreach( $GLOBALS['ASPECTS']['after'][$func] as $callback ) {
  149. call_user_func_array( $callback, array( $obj_a, $obj_b ) );
  150. }
  151. }
  152. }
  153. /**
  154. * aspect_join_functions
  155. *
  156. * add trigger function name pairs to GLOBALS
  157. *
  158. * @access public
  159. * @param string $func
  160. * @param string $callback
  161. * @param string $type
  162. */
  163. function aspect_join_functions( $func, $callback, $type = 'after' ) {
  164. $GLOBALS['ASPECTS'][$type][$func][] = $callback;
  165. }
  166. /**
  167. * Before Filter
  168. *
  169. * set an aspect function to trigger before another function
  170. *
  171. * @access public
  172. * @param string $name
  173. * @param string $func
  174. * @param string $when
  175. */
  176. function before_filter( $name, $func, $when = 'before' ) {
  177. aspect_join_functions( $func, $name, $when );
  178. }
  179. /**
  180. * After Filter
  181. *
  182. * set an aspect function to trigger after another function
  183. *
  184. * @access public
  185. * @param string $name
  186. * @param string $func
  187. * @param string $when
  188. */
  189. function after_filter( $name, $func, $when = 'after' ) {
  190. aspect_join_functions( $func, $name, $when );
  191. }
  192. /**
  193. * Never
  194. *
  195. * returns false
  196. *
  197. * @access public
  198. * @return boolean false
  199. */
  200. function never() {
  201. return false;
  202. }
  203. /**
  204. * Always
  205. *
  206. * returns true
  207. *
  208. * @access public
  209. * @return boolean true
  210. */
  211. function always() {
  212. return true;
  213. }
  214. /**
  215. * model_path
  216. *
  217. * path to data models
  218. *
  219. * @access public
  220. * @return string
  221. */
  222. function model_path() {
  223. return $GLOBALS['PATH']['models'];
  224. }
  225. /**
  226. * types_path
  227. *
  228. * path to renderers
  229. *
  230. * @access public
  231. * @return string
  232. */
  233. function types_path() {
  234. return $GLOBALS['PATH']['types'];
  235. }
  236. /**
  237. * library_path
  238. *
  239. * path to libraries
  240. *
  241. * @access public
  242. * @return string
  243. */
  244. function library_path() {
  245. return $GLOBALS['PATH']['library'];
  246. }
  247. /**
  248. * dbscript_path
  249. *
  250. * path to library/dbscript
  251. *
  252. * @access public
  253. * @return string
  254. */
  255. function dbscript_path() {
  256. return $GLOBALS['PATH']['dbscript'];
  257. }
  258. /**
  259. * ignore_errors
  260. *
  261. * returns value of ignore_errors environment variable, if set
  262. *
  263. * @access public
  264. * @return boolean
  265. */
  266. function ignore_errors() {
  267. global $env;
  268. if ( isset( $env['ignore_errors'] ) && $env['ignore_errors'] )
  269. return true;
  270. return false;
  271. }
  272. /**
  273. * plugin_path
  274. *
  275. * path to data models
  276. *
  277. * @access public
  278. * @return string
  279. */
  280. function plugin_path() {
  281. return $GLOBALS['PATH']['plugins'];
  282. }
  283. /**
  284. * controller_path
  285. *
  286. * path to controllers
  287. *
  288. * @access public
  289. * @return string
  290. */
  291. function controller_path() {
  292. return $GLOBALS['PATH']['controllers'];
  293. }
  294. function load( $loader ) {
  295. $loader =& loader();
  296. $loader->add_loader($loader);
  297. }
  298. function session_started() {
  299. if(isset($_SESSION)) {
  300. return true;
  301. } else {
  302. return false;
  303. }
  304. }
  305. /**
  306. * loader
  307. *
  308. * get global BootLoader object
  309. *
  310. * @access public
  311. * @return string
  312. */
  313. function &loader() {
  314. global $loader;
  315. return $loader;
  316. }
  317. function environment($name=NULL) {
  318. global $env;
  319. if (!($name == NULL) && isset( $env[$name] ))
  320. return $env[$name];
  321. if (!($name == NULL))
  322. return false;
  323. return $env;
  324. }
  325. function introspect_tables() {
  326. global $db;
  327. $arr = array();
  328. $tables = $db->get_tables();
  329. foreach ($tables as $t) {
  330. if (!(in_array($t, array( 'db_sessions', 'entries', 'categories_entries' )))
  331. && $t != classify($t)) {
  332. //$m =& $db->get_table($t);
  333. //if (!$m->hidden)
  334. $arr[] = $t;
  335. }
  336. }
  337. return $arr;
  338. }
  339. function read_aws_blob( &$request, $value, $coll, $ext ) {
  340. global $prefix;
  341. if (isset($coll[$request->resource])) {
  342. if ($coll[$request->resource]['location'] == 'aws')
  343. redirect_to( 'http://' . environment('awsBucket') . '.s3.amazonaws.com/' . $prefix.$request->resource . $request->id . "." . $ext );
  344. }
  345. }
  346. function read_uploads_blob( &$request, $value, $coll, $ext ) {
  347. if (!(isset($coll[$request->resource]))) {
  348. // use posts location for metadata blobs
  349. global $db;
  350. $model =& $db->get_table($request->resource);
  351. if (array_key_exists( 'target_id', $model->field_array ))
  352. $coll[$request->resource]['location'] = $coll['posts']['location'];
  353. }
  354. if (isset($coll[$request->resource])) {
  355. if ($coll[$request->resource]['location'] == 'uploads') {
  356. $file = 'uploads' . DIRECTORY_SEPARATOR . $request->resource . $request->id;
  357. if (file_exists($file)) {
  358. if (defined('MEMCACHED') && MEMCACHED ) {
  359. global $response;
  360. $timeout = MEMCACHED;
  361. $cache = PCA::get_best_backend();
  362. $cache->add($request->composite_uri(), file_get_contents( $file ), $timeout);
  363. $cache->add($request->composite_uri().'type', type_of($response->pick_template_extension( $request )), $timeout);
  364. }
  365. print file_get_contents( $file );
  366. }
  367. }
  368. }
  369. }
  370. function exists_uploads_blob( $resource,$id ) {
  371. $coll = environment('collection_cache');
  372. if (isset($coll[$resource])) {
  373. if ($coll[$resource]['location'] == 'uploads') {
  374. $file = 'uploads' . DIRECTORY_SEPARATOR . $resource . $id;
  375. if (file_exists($file))
  376. return true;
  377. }
  378. }
  379. return false;
  380. }
  381. function update_uploadsfile( $table, $id, $tmpfile ) {
  382. $coll = environment('collection_cache');
  383. if (!(isset($coll[$table]))) {
  384. // use posts location for metadata blobs
  385. global $db;
  386. $model =& $db->get_table($table);
  387. if (array_key_exists( 'target_id', $model->field_array ))
  388. $coll[$table]['location'] = $coll['posts']['location'];
  389. }
  390. if (!(isset($coll[$table])))
  391. return;
  392. $uploadFile = $coll[$table]['location'].DIRECTORY_SEPARATOR.$table.$id;
  393. if (file_exists($uploadFile))
  394. unlink($uploadFile);
  395. copy($tmpfile,$uploadFile);
  396. }
  397. function unlink_cachefile( $table, $id, $coll ) {
  398. if (isset($coll[$table])) {
  399. $cacheFile = $coll[$table]['location'].DIRECTORY_SEPARATOR.$table.$id;
  400. if (file_exists($cacheFile))
  401. unlink($cacheFile);
  402. }
  403. }
  404. function read_cache_blob( &$request, $value, $coll ) {
  405. if (isset($coll[$request->resource])) {
  406. if ($coll[$request->resource]['duration'] > 0) {
  407. $cacheFile = $coll[$request->resource]['location'].DIRECTORY_SEPARATOR.$request->resource.$request->id;
  408. if (!(is_dir($coll[$request->resource]['location'].DIRECTORY_SEPARATOR)))
  409. return;
  410. if ( file_exists( $cacheFile ) && filemtime( $cacheFile ) > ( time() - $coll[$request->resource]['duration'] ) ) {
  411. // read cacheFile
  412. if ( !$fp = fopen( $coll[$request->resource]['location'].DIRECTORY_SEPARATOR.'hits', 'a' ) ) {
  413. trigger_error( 'Error opening hits file', E_USER_ERROR );
  414. }
  415. if ( !flock( $fp, LOCK_EX ) ) {
  416. trigger_error( 'Unable to lock hits file', E_USER_ERROR );
  417. }
  418. if( !fwrite( $fp, time_of(timestamp())." hit ".$cacheFile."\n" ) ) {
  419. trigger_error( 'Error writing to cache file', E_USER_ERROR );
  420. }
  421. flock( $fp, LOCK_UN );
  422. fclose( $fp );
  423. unset( $fp );
  424. if (defined('MEMCACHED') && MEMCACHED ) {
  425. global $response;
  426. $timeout = MEMCACHED;
  427. $cache = PCA::get_best_backend();
  428. $cache->add($request->composite_uri(), file_get_contents( $cacheFile ), $timeout);
  429. $cache->add($request->composite_uri().'type', type_of($response->pick_template_extension( $request )), $timeout);
  430. }
  431. print file_get_contents( $cacheFile );
  432. exit;
  433. } else {
  434. // write cacheFile
  435. if ( !$fp = fopen( $coll[$request->resource]['location'].DIRECTORY_SEPARATOR.'hits', 'a' ) )
  436. trigger_error( 'Error opening hits file', E_USER_ERROR );
  437. if ( !flock( $fp, LOCK_EX ) )
  438. trigger_error( 'Unable to lock hits file', E_USER_ERROR );
  439. if( !fwrite( $fp, time_of(timestamp())." ".'write '.$cacheFile."\n" ) )
  440. trigger_error( 'Error writing to cache file', E_USER_ERROR );
  441. flock( $fp, LOCK_UN );
  442. fclose( $fp );
  443. unset( $fp );
  444. if ( !$fp = fopen( $cacheFile, 'w' ) )
  445. trigger_error( 'Error opening cache file', E_USER_ERROR );
  446. if ( !flock( $fp, LOCK_EX ) )
  447. trigger_error( 'Unable to lock cache file', E_USER_ERROR );
  448. if( !fwrite( $fp, fetch_blob($value, true) ) )
  449. trigger_error( 'Error writing to cache file', E_USER_ERROR );
  450. flock( $fp, LOCK_UN );
  451. fclose( $fp );
  452. unset( $fp );
  453. return;
  454. }
  455. }
  456. }
  457. }
  458. function download ($file_source, $file_target)
  459. {
  460. // Preparations
  461. $file_source = str_replace(' ', '%20', html_entity_decode($file_source)); // fix url format
  462. if (file_exists($file_target)) { chmod($file_target, 0777); } // add write permission
  463. // Begin transfer
  464. if (($rh = fopen($file_source, 'rb')) === FALSE) { return false; } // fopen() handles
  465. if (($wh = fopen($file_target, 'wb')) === FALSE) { return false; } // error messages.
  466. while (!feof($rh))
  467. {
  468. // unable to write to file, possibly because the harddrive has filled up
  469. if (fwrite($wh, fread($rh, 1024)) === FALSE) { fclose($rh); fclose($wh); return false; }
  470. }
  471. // Finished without errors
  472. fclose($rh);
  473. fclose($wh);
  474. return true;
  475. }
  476. function render_blob( $value, $ext ) {
  477. global $request;
  478. $req =& $request;
  479. global $db;
  480. $coll = environment('collection_cache');
  481. read_aws_blob($req,$value,$coll,$ext);
  482. header( 'Content-Type: ' . type_of( $ext ) );
  483. header( "Content-Disposition: inline" );
  484. read_uploads_blob($req,$value,$coll,$ext);
  485. read_cache_blob($req,$value,$coll);
  486. fetch_blob($value, false);
  487. }
  488. function fetch_blob( $value, $return ) {
  489. global $request;
  490. $req =& $request;
  491. global $db;
  492. if (is_array( $value )) {
  493. return $db->large_object_fetch(
  494. $value['t'],
  495. $value['f'],
  496. $value['k'],
  497. $value['i'],
  498. $return
  499. );
  500. } else {
  501. return $db->large_object_fetch( $value, $return );
  502. }
  503. }
  504. /**
  505. * template_exists
  506. *
  507. * find a template during content-negotiation
  508. *
  509. * @access public
  510. * @param Mapper $request
  511. * @param string $extension
  512. * @return boolean
  513. */
  514. function template_exists( &$request, $extension, $template ) {
  515. #if ($template == 'introspection') print 'ye';
  516. #print "template_exists $template ".$extension."<br />";
  517. $view = $request->get_template_path( $extension, $template );
  518. if ( file_exists( $view ) )
  519. return true;
  520. return false;
  521. }
  522. /**
  523. * Form For
  524. *
  525. * generate a form action string
  526. *
  527. * @access public
  528. * @param string $template
  529. * @todo implement
  530. */
  531. function form_for( &$resource, &$member, $url ) {
  532. global $request;
  533. if (is_object($resource)) {
  534. if ( isset( $resource->table )) {
  535. // remote_form_for :entry, @new_entry, :url => entries_url(:project_id => @project.id )
  536. return "<form method=\"post\" >";
  537. }
  538. }
  539. }
  540. /**
  541. * URL For
  542. *
  543. * generate a url from a Route
  544. *
  545. * @access public
  546. * @param array $params
  547. * @param array $altparams
  548. */
  549. function url_for( $params, $altparams = NULL ) {
  550. global $request;
  551. print $request->url_for( $params, $altparams );
  552. }
  553. function base_path($return = false) {
  554. global $request;
  555. $path = $request->values[1].$request->values[2].$request->path;
  556. if ($return)
  557. return $path;
  558. echo $path;
  559. }
  560. function base_url($return = false) {
  561. global $request;
  562. global $pretty_url_base;
  563. // XXX subdomain upgrade
  564. if (isset($pretty_url_base) && !empty($pretty_url_base))
  565. $base = $pretty_url_base."/".$request->prefix;
  566. else
  567. $base = $request->base;
  568. if ( !( substr( $base, -1 ) == '/' ))
  569. $base = $base . "/";
  570. if ($return)
  571. return $base;
  572. echo $base;
  573. }
  574. // XXX subdomain upgrade
  575. function blog_url($nickname,$return = false) {
  576. global $request;
  577. if (pretty_urls() && environment('subdomains')) {
  578. global $prefix;
  579. if (!empty($prefix))
  580. $base = 'http://' . $request->domain;
  581. else
  582. $base = 'http://'.$nickname . '.' . $request->domain;
  583. } else {
  584. $q = '?';
  585. if (pretty_urls())
  586. $q = '';
  587. $base = base_url(true).$q.'twitter/'.$nickname;
  588. }
  589. if ( !( substr( $base, -1 ) == '/' ))
  590. $base = $base . "/";
  591. if ($return)
  592. return $base;
  593. else
  594. echo $base;
  595. }
  596. /**
  597. * Redirect To
  598. *
  599. * redirect the browser via Routes
  600. *
  601. * @access public
  602. * @param string $template
  603. */
  604. function redirect_to( $param, $altparam = NULL ) {
  605. global $request,$db;
  606. trigger_before( 'redirect_to', $request, $db );
  607. if (is_ajax()){
  608. echo "OK";
  609. exit;
  610. }else{
  611. $request->redirect_to( $param, $altparam );
  612. }
  613. }
  614. function type_of( $file ) {
  615. $types = mime_types();
  616. if (eregi('\.?([a-z0-9]+)$', $file, $match) && isset($types[strtolower($match[1])]))
  617. return $types[strtolower($match[1])];
  618. return "text/html";
  619. }
  620. function type_of_image( $file ) {
  621. if (is_jpg($file))
  622. return 'jpg';
  623. if (is_png($file))
  624. return 'png';
  625. if (is_gif($file))
  626. return 'gif';
  627. return false;
  628. }
  629. function extension_for( $type ) {
  630. $types = mime_types();
  631. foreach($types as $key=>$val) {
  632. if ($val == $type)
  633. return $key;
  634. }
  635. return "html";
  636. }
  637. function is_blob( $field ) {
  638. $spleet = split( "\.", $field );
  639. global $db;
  640. if (empty($spleet[0])) return false;
  641. $model =& $db->get_table($spleet[0]);
  642. if ($model && !empty($spleet[1]))
  643. if ($model->is_blob($spleet[1]))
  644. return true;
  645. return false;
  646. }
  647. function mime_types() {
  648. return array (
  649. 'aif' => 'audio/x-aiff',
  650. 'aiff' => 'audio/x-aiff',
  651. 'aifc' => 'audio/x-aiff',
  652. 'm3u' => 'audio/x-mpegurl',
  653. 'mp3' => 'audio/mp3',
  654. 'ra' => 'audio/x-realaudio',
  655. 'ram' => 'audio/x-pn-realaudio',
  656. 'rm' => 'audio/x-pn-realaudio',
  657. 'wav' => 'audio/wav',
  658. 'avi' => 'video/x-ms-wm',
  659. 'mp4' => 'video/mp4',
  660. 'mpeg' => 'video/mpeg',
  661. 'mpe' => 'video/mpeg',
  662. 'mpg' => 'video/mpeg',
  663. 'mov' => 'video/quicktime',
  664. 'movie' => 'video/x-sgi-movie',
  665. 'qt' => 'video/quicktime',
  666. 'swa' => 'application/x-director',
  667. 'swf' => 'application/x-shockwave-flash',
  668. 'swfl' => 'application/x-shockwave-flash',
  669. 'wmv' => 'video/x-ms-wmv',
  670. 'asf' => 'video/x-ms-asf',
  671. 'sit' => 'application/x-stuffit',
  672. 'zip' => 'application/zip',
  673. 'tgz' => 'application/g-zip',
  674. 'gz' => 'application/g-zip',
  675. 'gzip' => 'application/g-zip',
  676. 'hqx' => 'application/mac-binhex40',
  677. 'ico' => 'image/vnd.microsoft.icon',
  678. 'bmp' => 'image/bmp',
  679. 'gif' => 'image/gif',
  680. 'jpg' => 'image/jpeg',
  681. 'jpeg' => 'image/jpeg',
  682. 'jpe' => 'image/jpeg',
  683. 'pct' => 'image/pict',
  684. 'pic' => 'image/pict',
  685. 'pict' => 'image/pict',
  686. 'png' => 'image/png',
  687. 'svg' => 'image/svg+xml',
  688. 'svgz' => 'image/svg+xml',
  689. 'tif' => 'image/tiff',
  690. 'tiff' => 'image/tiff',
  691. 'rtf' => 'text/rtf',
  692. 'pdf' => 'application/pdf',
  693. 'xdp' => 'application/pdf',
  694. 'xfd' => 'application/pdf',
  695. 'xfdf' => 'application/pdf',
  696. );
  697. }
  698. /**
  699. * Render
  700. *
  701. * render template or blob using content-negotiation
  702. *
  703. * @access public
  704. * @param string $template
  705. */
  706. /**
  707. * Member Of
  708. *
  709. * check group membership for a Person
  710. *
  711. * @access public
  712. * @param string $template
  713. */
  714. function member_of( $group ) {
  715. global $memberships;
  716. if ( $group == 'everyone' )
  717. return true;
  718. if (!( get_person_id() ))
  719. return false;
  720. if ( $group == 'members' )
  721. return true;
  722. if (!is_array($memberships)) {
  723. $memberships = array();
  724. global $request;
  725. global $db;
  726. $Person =& $db->model('Person');
  727. $Group =& $db->model('Group');
  728. $p = $Person->find( get_person_id() );
  729. if ($p)
  730. while ( $m = $p->NextChild( 'memberships' )) {
  731. $g = $Group->find( $m->group_id );
  732. $memberships[] = $g->name;
  733. if (!$g)
  734. trigger_error( "the Group with id ".$m->group_id." does not exist", E_USER_ERROR );
  735. if ( $g->name == $group )
  736. return true;
  737. }
  738. else
  739. return false;
  740. } else {
  741. if (in_array($group,$memberships))
  742. return true;
  743. }
  744. return false;
  745. }
  746. // add_include_path by ricardo dot ferro at gmail dot com
  747. function add_include_path($path,$prepend = false) {
  748. //foreach (func_get_args() AS $path)
  749. //{
  750. if (!file_exists($path) OR (file_exists($path) && filetype($path) !== 'dir'))
  751. {
  752. trigger_error("Include path '{$path}' not exists", E_USER_WARNING);
  753. continue;
  754. }
  755. $paths = explode(PATH_SEPARATOR, get_include_path());
  756. if (array_search($path, $paths) === false && $prepend)
  757. array_unshift($paths, $path);
  758. if (array_search($path, $paths) === false)
  759. array_push($paths, $path);
  760. set_include_path(implode(PATH_SEPARATOR, $paths));
  761. //}
  762. }
  763. function send_email( $sendto, $subject, $content, $fromemail="", $fromname="", $html=false ) {
  764. if (in_array($fromemail,array('','root@localhost')) || !is_email($fromemail) || empty($fromname))
  765. return;
  766. require_once(library_path().'xpertmailer'.DIRECTORY_SEPARATOR.'MAIL.php');
  767. $mail = new MAIL;
  768. $mail->From($fromemail, $fromname );
  769. $mail->AddTo($sendto);
  770. $mail->Subject($subject);
  771. if ($html)
  772. $mail->HTML($html);
  773. $mail->Text($content);
  774. $c = $mail->Connect(environment('email_server'), environment('email_port'), environment('email_user'), environment('email_pass'));
  775. $send = $mail->Send( $c );
  776. $mail->Disconnect();
  777. }
  778. function is_upload($table,$field) {
  779. return (isset($_FILES[strtolower(classify($table))]['name'][$field])
  780. && !empty($_FILES[strtolower(classify($table))]['name'][$field]));
  781. }
  782. function is_email($email) {
  783. return preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])([-a-z0-9_])+([a-z0-9])*(\.([a-z0-9])([-a-z0-9_-])([a-z0-9])+)*$/i',$email);
  784. }
  785. /**
  786. * Render Partial
  787. *
  788. * render a _template using content-negotiation
  789. *
  790. * @access public
  791. * @param string $template
  792. */
  793. function render_partial( $template ) {
  794. global $request,$response;
  795. if (!(strpos($template,".") === false)) {
  796. $spleet = split("\.",$template);
  797. $template = $spleet[0];
  798. $request->set( 'client_wants', $spleet[1] );
  799. }
  800. $response->render_partial( $request, $template );
  801. }
  802. function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
  803. return true;
  804. }
  805. function add_action( $act, $func ) {
  806. //admin_head, photos_head
  807. if ($act == 'init')
  808. return;
  809. if (!is_array($func) && function_exists($func))
  810. before_filter( $func, $act );
  811. add_filter($act, $func);
  812. return false;
  813. }
  814. function add_options_page($label1, $label2, $level, $parent, $arr ) {
  815. if (!is_array($arr) && function_exists($arr)) {
  816. }
  817. // add_options_page(
  818. // __('Twitter Tools Options', 'twitter-tools')
  819. // , __('Twitter Tools', 'twitter-tools')
  820. // , 10
  821. // , basename(__FILE__)
  822. // , 'aktt_options_form'
  823. // );
  824. // add_options_page(
  825. // __('Twitter Tools Options', 'twitter-tools')
  826. // , __('Twitter Tools', 'twitter-tools')
  827. // , 10
  828. // , basename(__FILE__)
  829. // , 'aktt_options_form'
  830. // );
  831. return false;
  832. }
  833. function app_menu($title,$url='',$role='member') {
  834. if (function_exists('add_management_page')) {
  835. add_management_page( $title, $title, $role, $file, '', $url );
  836. }
  837. }
  838. function render_theme( $theme ) {
  839. // dbscript
  840. global $request, $db;
  841. // wordpress
  842. global $blogdata, $optiondata, $current_user, $user_login, $userdata;
  843. global $user_level, $user_ID, $user_email, $user_url, $user_pass_md5;
  844. global $wpdb, $wp_query, $post, $limit_max, $limit_offset, $comments;
  845. global $req, $wp_rewrite, $wp_version, $openid, $user_identity, $logic;
  846. global $submenu;
  847. global $comment_author;
  848. global $comment_author_email;
  849. global $comment_author_url;
  850. $folder = $GLOBALS['PATH']['themes'] . environment('theme') . DIRECTORY_SEPARATOR;
  851. add_include_path($folder);
  852. global $wpmode;
  853. $wpmode = "posts";
  854. if ($request->resource != 'posts' || !(in_array($request->action,array('replies','index')))) {
  855. $wpmode = "other";
  856. if (is_file($folder . "functions.php" ))
  857. require_once( $folder . "functions.php" );
  858. require_once( $folder . "page.php" );
  859. } else {
  860. if (is_file($folder . "functions.php" ))
  861. require_once( $folder . "functions.php" );
  862. if ( file_exists( $folder . "index.php" ))
  863. require_once( $folder . "index.php" );
  864. else
  865. require_once( $folder . "index.html" );
  866. }
  867. }
  868. function theme_path($noslash = false) {
  869. global $request,$db;
  870. trigger_before('theme_path', $request, $db);
  871. global $pretty_url_base;
  872. if (isset($pretty_url_base) && !empty($pretty_url_base))
  873. $base = $pretty_url_base . DIRECTORY_SEPARATOR;
  874. else
  875. $base = "";
  876. $path = $base . $GLOBALS['PATH']['themes'] . environment('theme') . DIRECTORY_SEPARATOR;
  877. if ($noslash && "/" == substr($path,-1))
  878. $path = substr($path,0,-1);
  879. return $path;
  880. }
  881. function theme_dir(){
  882. return $GLOBALS['PATH']['themes'] . environment('theme') . DIRECTORY_SEPARATOR;
  883. }
  884. /**
  885. * content_for_layout
  886. *
  887. * render a _template using content-negotiation
  888. *
  889. * @access public
  890. * @param string $template
  891. */
  892. function content_for_layout() {
  893. global $request;
  894. render_partial( $request->action );
  895. }
  896. function breadcrumbs() {
  897. global $request;
  898. echo $request->breadcrumbs();
  899. }
  900. function register_type( $arr ) {
  901. global $variants;
  902. $variants[] = $arr;
  903. }
  904. function photoCreateCropThumb ($p_thumb_file, $p_photo_file, $p_max_size, $p_quality = 100, $tmpfile = null ) {
  905. if ($tmpfile == null)
  906. $ext = 'jpg';
  907. else
  908. $ext = type_of_image($tmpfile);
  909. if ($ext == 'jpg')
  910. $pic = imagecreatefromjpeg($p_photo_file);
  911. if ($ext == 'gif')
  912. $pic = imagecreatefromgif($p_photo_file);
  913. if ($ext == 'png'){
  914. $image = imagecreatefromstring(file_get_contents($p_photo_file));
  915. $width = imagesx($image);
  916. $height = imagesy($image);
  917. unset($image);
  918. $size = getimagesize($p_photo_file);
  919. $required_memory = Round($width * $height * $size['bits']) +500000;
  920. unset($size);
  921. $new_limit=memory_get_usage() + $required_memory;
  922. ini_set("memory_limit", $new_limit);
  923. $pic = imagecreatefrompng($p_photo_file);
  924. }
  925. if ($pic) {
  926. $thumb = imagecreatetruecolor ($p_max_size, $p_max_size);
  927. if (!$thumb)
  928. trigger_error('Sorry, the thumbnail photo could not be created', E_USER_ERROR);
  929. $width = imagesx($pic);
  930. $height = imagesy($pic);
  931. if ($width < $height) {
  932. $twidth = $p_max_size;
  933. $theight = $twidth * $height / $width;
  934. imagecopyresized($thumb, $pic, 0, 0, 0, ($height/2)-($width/2), $twidth, $theight, $width, $height);
  935. } else {
  936. $theight = $p_max_size;
  937. $twidth = $theight * $width / $height;
  938. imagecopyresized($thumb, $pic, 0, 0, ($width/2)-($height/2), 0, $twidth, $theight, $width, $height);
  939. }
  940. if ($ext == 'jpg')
  941. imagejpeg($thumb, $p_thumb_file, $p_quality);
  942. if ($ext == 'gif')
  943. imagegif($thumb, $p_thumb_file);
  944. if ($ext == 'png') {
  945. imagepng($thumb, $p_thumb_file);
  946. ini_restore("memory_limit");
  947. }
  948. }
  949. }
  950. function resize_jpeg($file,$dest,$size) {
  951. $new_w = $size;
  952. $new_h = $new_w;
  953. $src_img = imagecreatefromjpeg("$file");
  954. $old_x=imageSX($src_img);
  955. $old_y=imageSY($src_img);
  956. if ($old_x > $old_y)
  957. {
  958. $thumb_w=$new_w;
  959. $thumb_h=$old_y*($new_h/$old_x);
  960. }
  961. if ($old_x < $old_y)
  962. {
  963. $thumb_w=$old_x*($new_w/$old_y);
  964. $thumb_h=$new_h;
  965. }
  966. if ($old_x == $old_y)
  967. {
  968. $thumb_w=$new_w;
  969. $thumb_h=$new_h;
  970. }
  971. $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
  972. imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
  973. imagejpeg($dst_img,$dest);
  974. }
  975. function content_types() {
  976. global $env;
  977. $variants = array(
  978. array(
  979. 'id' => 'html',
  980. 'qs' => 1.000,
  981. 'type' => 'text/html',
  982. 'encoding' => null,
  983. 'charset' => 'iso-8859-1',
  984. 'language' => 'en',
  985. 'size' => 3000
  986. )
  987. );
  988. if (isset($env['content_types']))
  989. return $env['content_types'];
  990. else
  991. return $variants;
  992. }
  993. /**
  994. * db_include
  995. *
  996. * include a dbscript file
  997. *
  998. * @access public
  999. */
  1000. function db_include( $file ) {
  1001. if (is_array($file)) {
  1002. foreach($file as $f)
  1003. require_once dbscript_path() . $f . ".php";
  1004. } else {
  1005. require_once dbscript_path() . $file . ".php";
  1006. }
  1007. }
  1008. function wp_plugin_include( $file, $basedir=NULL ) {
  1009. $wp_plugins = "wp-content" . DIRECTORY_SEPARATOR . "plugins" . DIRECTORY_SEPARATOR . $file;
  1010. if (is_dir($wp_plugins)) {
  1011. $startfile = $wp_plugins.DIRECTORY_SEPARATOR.$file.".php";
  1012. if (is_file($startfile)) {
  1013. require_once $startfile;
  1014. return;
  1015. }
  1016. $startfile = $wp_plugins.DIRECTORY_SEPARATOR.str_replace('wordpress','wp',$file).".php";
  1017. if (is_file($startfile)) {
  1018. require_once $startfile;
  1019. return;
  1020. }
  1021. $file = str_replace('-','_',$file);
  1022. $startfile = $wp_plugins.DIRECTORY_SEPARATOR.str_replace('wordpress','wp',$file).".php";
  1023. if (is_file($startfile)) {
  1024. require_once $startfile;
  1025. return;
  1026. }
  1027. $startfile = $wp_plugins.DIRECTORY_SEPARATOR.'plugin.php';
  1028. if (is_file($startfile)) {
  1029. require_once $startfile;
  1030. return;
  1031. }
  1032. }
  1033. $wp_plugins = "wp-plugins" . DIRECTORY_SEPARATOR . "plugins" . DIRECTORY_SEPARATOR . "enabled";
  1034. if (is_array($file)) {
  1035. foreach($file as $f) {
  1036. if (file_exists(plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $f . DIRECTORY_SEPARATOR . 'plugin.php' ))
  1037. require_once plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $f . DIRECTORY_SEPARATOR . 'plugin.php';
  1038. elseif (file_exists(plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $f . DIRECTORY_SEPARATOR . 'core.php' ))
  1039. require_once plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $f . DIRECTORY_SEPARATOR . 'core.php';
  1040. elseif (file_exists(plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $f . ".php"))
  1041. require_once plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $f . ".php";
  1042. }
  1043. } else {
  1044. if (file_exists(plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR . 'plugin.php' ))
  1045. require_once plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR . 'plugin.php';
  1046. elseif (file_exists(plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR . 'core.php' ))
  1047. require_once plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR . 'core.php';
  1048. elseif (file_exists(plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $file . ".php"))
  1049. require_once plugin_path() . $wp_plugins . DIRECTORY_SEPARATOR . $file . ".php";
  1050. }
  1051. }
  1052. /**
  1053. * lib_include
  1054. *
  1055. * include a library file
  1056. *
  1057. * @access public
  1058. */
  1059. function lib_include( $file ) {
  1060. if ($file == 'json' && class_exists('Services_JSON'))
  1061. return;
  1062. if (is_array($file)) {
  1063. foreach($file as $f) {
  1064. if (file_exists(library_path() . $f . ".php"))
  1065. require_once library_path() . $f . ".php";
  1066. }
  1067. } else {
  1068. if (file_exists(library_path() . $file . ".php"))
  1069. require_once library_path() . $file . ".php";
  1070. }
  1071. }
  1072. function load_plugin( $plugin ) {
  1073. global $request,$db;
  1074. trigger_before('load_plugin',$db,$request);
  1075. $plugin_paths = array();
  1076. if (isset($GLOBALS['PATH']['app_plugins']))
  1077. foreach($GLOBALS['PATH']['app_plugins'] as $path)
  1078. $plugin_paths[] = $path;
  1079. $plugin_paths[] = $GLOBALS['PATH']['plugins'];
  1080. foreach ($plugin_paths as $plugpath) {
  1081. if ( file_exists( $plugpath . $plugin . '.php' ) ) {
  1082. include $plugpath . $plugin . '.php';
  1083. $init = $plugin . "_init";
  1084. if ( function_exists( $init ) )
  1085. $init();
  1086. return;
  1087. }
  1088. }
  1089. }
  1090. /**
  1091. * version
  1092. *
  1093. * get dbscript version
  1094. *
  1095. * @access public
  1096. * @return string
  1097. */
  1098. function version() {
  1099. global $version;
  1100. return $version;
  1101. }
  1102. function timestamp() {
  1103. return date( "Y-m-d H:i:s", strtotime( "now" ));
  1104. }
  1105. /**
  1106. * magic_quotes_stripslashes_b
  1107. *
  1108. * @access public
  1109. * @param array $a
  1110. * @return array $r
  1111. */
  1112. function magic_quotes_stripslashes_b($a) { // Back
  1113. $r=array();
  1114. foreach ($a as $k=>$v) {
  1115. if (!is_array($v)) $r[stripslashes($k)] = stripslashes($v);
  1116. else $r[stripslashes($k)] = magic_quotes_stripslashes_b($v);
  1117. }
  1118. return $r;
  1119. }
  1120. /**
  1121. * magic_quotes_stripslashes
  1122. *
  1123. * @access public
  1124. * @param array $a
  1125. * @return array $r
  1126. */
  1127. function magic_quotes_stripslashes($a) { // Top
  1128. $r=array();
  1129. foreach ($a as $k=>$v) {
  1130. if (!is_array($v)) $r[$k] = stripslashes($v);
  1131. else $r[$k] = magic_quotes_stripslashes_b($v);
  1132. }
  1133. return $r;
  1134. }
  1135. /**
  1136. * magic_quotes_stripquotes_b
  1137. *
  1138. * @access public
  1139. * @param array $a
  1140. * @return array $r
  1141. */
  1142. function magic_quotes_stripquotes_b($a) { // Back
  1143. $r=array();
  1144. foreach ($a as $k=>$v) {
  1145. if (!is_array($v)) $r[str_replace('\'\'','\'',$k)] = str_replace('\'\'','\'',$v);
  1146. else $r[str_replace('\'\'','\'',$k)] = magic_quotes_stripquotes_b($v);
  1147. }
  1148. return $r;
  1149. }
  1150. /**
  1151. * magic_quotes_stripquotes
  1152. *
  1153. * @access public
  1154. * @param array $a
  1155. * @return array $r
  1156. */
  1157. function magic_quotes_stripquotes($a) { // Top
  1158. $r=array();
  1159. foreach ($a as $k=>$v) {
  1160. if (!is_array($v)) $r[$k] = str_replace('\'\'','\'',$v);
  1161. else $r[$k] = magic_quotes_stripquotes_b($v);
  1162. }
  1163. return $r;
  1164. }
  1165. /**
  1166. * header_status
  1167. *
  1168. * @access public
  1169. * @param string $status
  1170. */
  1171. function header_status( $status ) {
  1172. if (!headers_sent($filename, $linenum)) {
  1173. // this is disabled because it breaks on Dreamhost
  1174. #header( "Status: ".$status );
  1175. // THIS "works" on DH but it's not up to HTTP spec
  1176. #header( "HTTP/1.0 Status: ".$status );
  1177. } else {
  1178. echo "Headers already sent in $filename on line $linenum\nCannot set HTTP status\n";
  1179. exit;
  1180. }
  1181. }
  1182. /**
  1183. * set_cookie
  1184. *
  1185. * make a fresh Cookie
  1186. *
  1187. * @access public
  1188. * @param integer $userid
  1189. */
  1190. function set_cookie($userid) {
  1191. $cookie = new Cookie();
  1192. $cookie->userid = $userid;
  1193. $cookie->set();
  1194. }
  1195. /**
  1196. * unset_cookie
  1197. *
  1198. * throw the Cookie away? noo..
  1199. *
  1200. * @access public
  1201. */
  1202. function unset_cookie() {
  1203. $cookie = new Cookie();
  1204. $cookie->logout();
  1205. }
  1206. /**
  1207. * check_cookie
  1208. *
  1209. * is the Cookie fit for consumption?
  1210. *
  1211. * @access public
  1212. * @return boolean
  1213. */
  1214. function check_cookie() {
  1215. $cookie = new Cookie();
  1216. if ($cookie->validate()) {
  1217. return true;
  1218. } else {
  1219. return false;
  1220. }
  1221. }
  1222. function print_email( $mail ) {
  1223. if ($mail=='') return '';
  1224. $mail = str_replace(array('@',':','.'), array('&#064;','&#058;','&#046;'), $mail);
  1225. $mail = '<a href=mailto&#058;'.$mail.'>'.$mail.'</a>';
  1226. $len = strlen($mail);
  1227. $i=0;
  1228. while($i<$len)
  1229. {
  1230. $c = mt_rand(1,4);
  1231. $par[] = (substr($mail, $i, $c));
  1232. $i += $c;
  1233. }
  1234. $join = implode('"+ "', $par);
  1235. return '<script language=javascript>
  1236. <!--
  1237. document.write("'.$join.'")
  1238. //-->
  1239. </script>';
  1240. }
  1241. function signed_in() {
  1242. return member_of('members');
  1243. }
  1244. function public_resource() {
  1245. global $db;
  1246. global $request;
  1247. $req =& $request;
  1248. if ( $req->resource == 'introspection' )
  1249. return true;
  1250. $datamodel =& $db->get_table($req->resource);
  1251. $action = $request->action;
  1252. if ( !( in_array( $action, $datamodel->allowed_methods, true )))
  1253. $action = 'get';
  1254. if (!($action == 'get'))
  1255. return false;
  1256. if (!(isset($datamodel->access_list['read']['id'])))
  1257. return false;
  1258. if (in_array('always',$datamodel->access_list['read']['id']))
  1259. return true;
  1260. if (in_array('everyone',$datamodel->access_list['read']['id']))
  1261. return true;
  1262. if (isset($req->client_wants))
  1263. if (in_array($req->action.".".$req->client_wants,$datamodel->access_list['read']['id']))
  1264. return true;
  1265. else
  1266. return false;
  1267. if (in_array($req->action,$datamodel->access_list['read']['id']))
  1268. return true;
  1269. // if ((!(file_exists($this->template_path . $resource . "_" . $action . "." . $ext)))
  1270. return false;
  1271. }
  1272. function virtual_resource() {
  1273. global $request;
  1274. $model = model_path() . classify($request->resource) . ".php";
  1275. if (!file_exists($model))
  1276. return true;
  1277. return false;
  1278. }
  1279. function can_read( $resource ) {
  1280. if (!(isset($this->access_list['read'][$resource]))) return false;
  1281. foreach ( $this->access_list['read'][$resource] as $callback ) {
  1282. if ( function_exists( $callback ) ) {
  1283. if ($callback())
  1284. return true;
  1285. } else {
  1286. if ( member_of( $callback ))
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. function can_edit( $post ) {
  1293. global $db;
  1294. $pid = get_person_id();
  1295. $e = $post->FirstChild('entries');
  1296. $m =& $db->get_table($post->table);
  1297. return (($pid == $e->person_id) || $m->can_superuser($post->table));
  1298. }
  1299. function entry_for( &$obj ) {
  1300. global $db;
  1301. if (isset($obj->entry_id)) {
  1302. // it's a Record with metadata
  1303. $Entry =& $db->model('Entry');
  1304. return $Entry->find($obj->entry_id);
  1305. }
  1306. return false;
  1307. }
  1308. function owner_of( &$obj ) {
  1309. global $db;
  1310. $Person =& $db->model('Person');
  1311. if (isset($obj->entry_id)) {
  1312. // it's a Record
  1313. $Entry =& $db->model('Entry');
  1314. $e = $Entry->find($obj->entry_id);
  1315. $p = $Person->find($e->person_id);
  1316. } else {
  1317. // it's an Entry
  1318. $p = $Person->find($obj->person_id);
  1319. }
  1320. if ($p) {
  1321. $i = $p->FirstChild('identities');
  1322. if ($i)
  1323. return $i;
  1324. }
  1325. return false;
  1326. }
  1327. /**
  1328. * get_profile
  1329. *
  1330. * get the Identity of a person
  1331. *
  1332. * @access public
  1333. * @return integer
  1334. */
  1335. function get_profile($id=NULL) {
  1336. global $db,$response;
  1337. if (!($id == NULL)) {
  1338. $Identity =& $db->get_table( 'identities' );
  1339. return $Identity->find($id);
  1340. } elseif ( isset( $response->named_vars['profile'] )) {
  1341. $profile =& $response->named_vars['profile'];
  1342. if ($profile->id > 0)
  1343. return $profile;
  1344. }
  1345. $pid = get_person_id();
  1346. if (!$pid)
  1347. return false;
  1348. $Person =& $db->get_table( 'people' );
  1349. $p = $Person->find($pid);
  1350. if ($p) {
  1351. $i = $p->FirstChild('identities');
  1352. if ($i)
  1353. $response->named_vars['profile'] = $i;
  1354. if ($i)
  1355. return $i;
  1356. }
  1357. return false;
  1358. }
  1359. function get_profile_id() {
  1360. $profile = get_profile();
  1361. return $profile->id;
  1362. }
  1363. function return_ok() {
  1364. header( 'Status: 200 OK' );
  1365. exit;
  1366. }
  1367. /**
  1368. * get_person_id
  1369. *
  1370. * get the person_id of the profile owner
  1371. *
  1372. * @access public
  1373. * @return integer
  1374. */
  1375. function get_person_id() {
  1376. global $response,$request;
  1377. if (isset($response->named_vars['profile'])) {
  1378. $i = $response->named_vars['profile'];
  1379. if ($i)
  1380. return $i->person_id;
  1381. }
  1382. if (isset($_SERVER['PHP_AUTH_USER'])) {
  1383. global $person_id;
  1384. if ($person_id) {
  1385. before_filter( 'return_ok', 'redirect_to' );
  1386. return $person_id;
  1387. }
  1388. }
  1389. $p = get_cookie_id();
  1390. if ($p)
  1391. return $p;
  1392. if (isset($_SESSION['fb_person_id'])
  1393. && $_SESSION['fb_person_id'] >0) {
  1394. return $_SESSION['fb_person_id'];
  1395. }
  1396. if (isset($_SESSION['oauth_person_id'])
  1397. && $_SESSION['oauth_person_id'] >0) {
  1398. return $_SESSION['oauth_person_id'];
  1399. }
  1400. if (isset($_SERVER['PHP_AUTH_USER'])) {
  1401. global $person_id;
  1402. if ($person_id)
  1403. return $person_id;
  1404. }
  1405. if (isset($_POST['auth']) && $_POST['auth'] == 'omb')
  1406. authenticate_with_omb();
  1407. if (isset($_POST['auth']) && $_POST['auth'] == 'oauth')
  1408. authenticate_with_oauth();
  1409. global $person_id;
  1410. if ($person_id) {
  1411. before_filter( 'return_ok', 'redirect_to' );
  1412. return $person_id;
  1413. }
  1414. return 0;
  1415. }
  1416. /**
  1417. * get_cookie_id
  1418. *
  1419. * get the person_id of the cookie owner
  1420. *
  1421. * @access public
  1422. * @return integer
  1423. */
  1424. function get_cookie_id() {
  1425. $cookie = new Cookie();
  1426. if ($cookie->validate())
  1427. return $cookie->userid;
  1428. return 0;
  1429. }
  1430. /**
  1431. * Vars
  1432. *
  1433. * mutator function makes an array of local variables extractable
  1434. *
  1435. * @access public
  1436. * @param string $var
  1437. * @return string
  1438. */
  1439. function render($varios, $scope=false, $prefix='unique', $suffix='value') {
  1440. if ($varios == 'action'){
  1441. $param = $varios;
  1442. $value = $scope;
  1443. global $db,$response,$request;
  1444. if ( $param == 'action' && !(strpos($value,".") === false ) ) {
  1445. $spleet = split( "\.", $value );
  1446. $value = $spleet[0];
  1447. $request->set( 'client_wants', $spleet[1] );
  1448. }
  1449. $request->set_param( $param, $value );
  1450. $response->render( $request );
  1451. exit;
  1452. }
  1453. if ( $scope )
  1454. $vals = $scope;
  1455. else
  1456. $vals = $GLOBALS;
  1457. $i = 0;
  1458. foreach ($varios as $orig) {
  1459. $var =& $varios[$i];
  1460. $old = $var;
  1461. $var = $new = $prefix . rand() . $suffix;
  1462. $vname = FALSE;
  1463. foreach( $vals as $key => $val ) {
  1464. if ( $val === $new ) $vname = $key;
  1465. }
  1466. $var = $old;
  1467. if ($vname) {
  1468. $varios[$vname] = $var;
  1469. }
  1470. $i++;
  1471. }
  1472. return $varios;
  1473. }
  1474. function vars($varios, $scope=false, $prefix='unique', $suffix='value') {
  1475. if ( $scope )
  1476. $vals = $scope;
  1477. else
  1478. $vals = $GLOBALS;
  1479. $i = 0;
  1480. foreach ($varios as $orig) {
  1481. $var =& $varios[$i];
  1482. $old = $var;
  1483. $var = $new = $prefix . rand() . $suffix;
  1484. $vname = FALSE;
  1485. foreach( $vals as $key => $val ) {
  1486. if ( $val === $new ) $vname = $key;
  1487. }
  1488. $var = $old;
  1489. if ($vname) {
  1490. $varios[$vname] = $var;
  1491. }
  1492. $i++;
  1493. }
  1494. return $varios;
  1495. }
  1496. /**
  1497. * Randomstring
  1498. *
  1499. * give it a string length and you will receive a random string!
  1500. *
  1501. * @access public
  1502. * @param integer $len
  1503. * @return string
  1504. */
  1505. function randomstring($len) {
  1506. srand(date("s"));
  1507. $i = 0;
  1508. $str = "";
  1509. while($i<$len)
  1510. {
  1511. $str.=chr((rand()%26)+97);
  1512. $i++;
  1513. }
  1514. return $str;
  1515. }
  1516. function getEtag($id) {
  1517. return "ci-".dechex(crc32($id.microtime()));
  1518. }
  1519. /**
  1520. * drop_array_element
  1521. *
  1522. * returns the array minus the named element
  1523. *
  1524. * @access public
  1525. * @param string $str
  1526. */
  1527. function drop_array_element($array_with_elements, $key_name) {
  1528. $key_index = array_keys(array_keys($array_with_elements), $key_name);
  1529. if (count($key_index) != '') {
  1530. array_splice($array_with_elements, $key_index[0], 1);
  1531. }
  1532. return $array_with_elements;
  1533. }
  1534. /**
  1535. * dictionary_parse
  1536. *
  1537. * Parses an xml dictionary.
  1538. * First argument is file name OR xml data.
  1539. * Second argument must be 'true' if the first arg is file name.
  1540. *
  1541. * <code>
  1542. * $array = dictionary_parse( $file_name, true );
  1543. * </code>
  1544. *
  1545. * @author Brian Hendrickson <brian@dbscript.net>
  1546. * @access public
  1547. * @param string $data
  1548. * @return array
  1549. */
  1550. function dictionary_parse( $data ) { /* parse XML dictionaries (lookup tables) */
  1551. $dict = array();
  1552. $xml_parser = xml_parser_create();
  1553. xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
  1554. xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 0);
  1555. if (!$xml_parser) {
  1556. trigger_error("error creating xml parser (xml_parser_create) in dictionary_parse", E_USER_ERROR );
  1557. }
  1558. $func_args = func_get_args();
  1559. if (count($func_args) > 1) {
  1560. if ($func_args[1] == true) {
  1561. $data = file_get_contents($data);
  1562. if (!$data) {
  1563. trigger_error("error reading file contents in dictionary_parse, file name was: ".$func_args[0], E_USER_ERROR );
  1564. }
  1565. }
  1566. }
  1567. $int = xml_parse_into_struct($xml_parser, $data, $values, $tags);
  1568. if (!($int > 0)) {
  1569. trigger_error("error parsing XML in dictionary_parse: ".xml_error_string(xml_get_error_code($xml_parser)), E_USER_ERROR )." ". $data;
  1570. }
  1571. foreach ($tags as $tagname=>$valuelocations) {
  1572. if ($tagname == "KEY") {
  1573. $i = 0;
  1574. foreach ($valuelocations as $valkey=>$valloc) {
  1575. $map[$i] = $values[$valloc]['value'];
  1576. $dict[$values[$valloc]['value']] = "";
  1577. $i++;
  1578. }
  1579. }
  1580. if ($tagname == "STRING") {
  1581. $i = 0;
  1582. foreach ($valuelocations as $valkey=>$valloc) {
  1583. if (isset($values[$valloc]['value'])) {
  1584. $dict[$map[$i]] = $values[$valloc]['value'];
  1585. } else {
  1586. $dict[$map[$i]] = "";
  1587. }
  1588. $i++;
  1589. }
  1590. }
  1591. }
  1592. xml_parser_free($xml_parser);
  1593. return $dict;
  1594. }
  1595. function load_model( &$model, &$model2 ) {
  1596. global $db;
  1597. $tab = tableize(get_class($model));
  1598. if ($tab == 'models') return;
  1599. if (!($db->models[$tab]->exists))
  1600. $model->register($tab);
  1601. }
  1602. /**
  1603. * in_string
  1604. *
  1605. * search for a substring
  1606. *
  1607. * @access public
  1608. * @param string $needle
  1609. * @param array $haystack
  1610. * @param integer $insensitive
  1611. * @return boolean
  1612. */
  1613. function in_string($needle, $haystack, $insensitive = 0) {
  1614. if ($insensitive) {
  1615. return (false !== stristr($haystack, $needle)) ? true : false;
  1616. } else {
  1617. return (false !== strpos($haystack, $needle)) ? true : false;
  1618. }
  1619. }
  1620. /**
  1621. * get_script_name
  1622. *
  1623. * the name of the current script
  1624. *
  1625. * @access public
  1626. * @return string
  1627. */
  1628. function get_script_name() {
  1629. if (!empty($_SERVER['PHP_SELF'])) {
  1630. $strScript = $_SERVER['PHP_SELF'];
  1631. } else if (!empty($_SERVER['SCRIPT_NAME'])) {
  1632. $strScript = @$_SERVER['SCRIPT_NAME'];
  1633. } else {
  1634. trigger_error("error reading script name in get_script_name", E_USER_ERROR );
  1635. }
  1636. $intLastSlash = strrpos($strScript, "/");
  1637. if (strrpos($strScript, "\\")>$intLastSlash) {
  1638. $intLastSlash = strrpos($strScript, "\\");
  1639. }
  1640. return substr($strScript, $intLastSlash+1, strlen($strScript));
  1641. }
  1642. function dircopy($srcdir, $dstdir, $verbose = false) {
  1643. $num = 0;
  1644. if(!is_dir($dstdir)) mkdir($dstdir);
  1645. if($curdir = opendir($srcdir)) {
  1646. while($file = readdir($curdir)) {
  1647. if($file != '.' && $file != '..') {
  1648. $srcfile = $srcdir . DIRECTORY_SEPARATOR . $file;
  1649. $dstfile = $dstdir . DIRECTORY_SEPARATOR . $file;
  1650. if(is_file($srcfile)) {
  1651. if(is_file($dstfile)) $ow = filemtime($srcfile) - filemtime($dstfile); else $ow = 1;
  1652. if($ow > 0) {
  1653. if($verbose) echo "Copying '$srcfile' to '$dstfile'...";
  1654. if(copy($srcfile, $dstfile)) {
  1655. touch($dstfile, filemtime($srcfile)); $num++;
  1656. if($verbose) echo "OK\n";
  1657. }
  1658. else echo "Error: File '$srcfile' could not be copied!\n";
  1659. }
  1660. }
  1661. else if(is_dir($srcfile)) {
  1662. $num += dircopy($srcfile, $dstfile, $verbose);
  1663. }
  1664. }
  1665. }
  1666. closedir($curdir);
  1667. }
  1668. return $num;
  1669. }
  1670. function unzip($dir, $file, $verbose = 0) {
  1671. $dir_path = "$dir$file";
  1672. $zip_path = "$dir$file.zip";
  1673. $ERROR_MSGS[0] = "OK";
  1674. $ERROR_MSGS[1] = "Zip path $zip_path doesn't exists.";
  1675. $ERROR_MSGS[2] = "Directory $dir_path for unzip the pack already exists, impossible continue.";
  1676. $ERROR_MSGS[3] = "Error while opening the $zip_path file.";
  1677. $ERROR = 0;
  1678. if (file_exists($zip_path)) {
  1679. if (!file_exists($dir_path)) {
  1680. mkdir($dir_path);
  1681. if (($link = zip_open($zip_path))) {
  1682. while (($zip_entry = zip_read($link)) && (!$ERROR)) {
  1683. if (zip_entry_open($link, $zip_entry, "r")) {
  1684. $data = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
  1685. $dir_name = dirname(zip_entry_name($zip_entry));
  1686. $name = zip_entry_name($zip_entry);
  1687. if ($name[strlen($name)-1] == '/') {
  1688. $base = "$dir_path/";
  1689. foreach ( explode("/", $name) as $k) {
  1690. $base .= "$k/";
  1691. if (!file_exists($base))
  1692. mkdir($base);
  1693. }
  1694. }
  1695. else {
  1696. $name = "$dir_path/$name";
  1697. if ($verbose)
  1698. echo "extracting: $name<br />";
  1699. $stream = fopen($name, "w");
  1700. fwrite($stream, $data);
  1701. }
  1702. zip_entry_close($zip_entry);
  1703. }
  1704. else
  1705. $ERROR = 4;
  1706. }
  1707. zip_close($link);

Large files files are truncated, but you can click here to view the full file