PageRenderTime 64ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  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);
  1708. }
  1709. else
  1710. $ERROR = "3";
  1711. }
  1712. else
  1713. $ERROR = 2;
  1714. }
  1715. else
  1716. $ERROR = 1;
  1717. return $ERROR_MSGS[$ERROR];
  1718. }
  1719. #---
  1720. #example:
  1721. #$error = unzip("d:/www/dir/", "zipname", 1);
  1722. /**
  1723. * is_obj
  1724. *
  1725. * more flexible is_object
  1726. *
  1727. * @access public
  1728. * @param object $object
  1729. * @param boolean $check
  1730. * @param boolean $strict
  1731. * @return boolean
  1732. */
  1733. function is_obj( &$object, $check=null, $strict=true ) {
  1734. if (is_object($object)) {
  1735. if ($check == null) {
  1736. return true;
  1737. } else {
  1738. $object_name = get_class($object);
  1739. return ($strict === true)?
  1740. ( $object_name == $check ):
  1741. ( strtolower($object_name) == strtolower($check) );
  1742. }
  1743. } else {
  1744. return false;
  1745. }
  1746. }
  1747. function resource_group_members( $gid=NULL ) {
  1748. global $db;
  1749. global $request;
  1750. $req =& $request;
  1751. $Person =& $db->model('Person');
  1752. $Group =& $db->model('Group');
  1753. $Group->find();
  1754. $added = array();
  1755. $result = array();
  1756. $datamodel =& $db->get_table($req->resource);
  1757. if ($gid == NULL) {
  1758. while ( $g =& $Group->MoveNext() ) {
  1759. if (in_array($g->name,$datamodel->access_list['read']['id'])) {
  1760. while ( $m = $g->NextChild( 'memberships' )) {
  1761. if (!(in_array($m->person_id,$added))) {
  1762. $p =& $Person->find( $m->person_id );
  1763. $result[] = $p->FirstChild('identities');
  1764. $added[] = $m->person_id;
  1765. }
  1766. }
  1767. }
  1768. }
  1769. } else {
  1770. while ( $g =& $Group->MoveNext() ) {
  1771. if (($g->id == $gid)) {
  1772. while ( $m = $g->NextChild( 'memberships' )) {
  1773. if (!(in_array($m->person_id,$added))) {
  1774. $p =& $Person->find( $m->person_id );
  1775. $result[] = $p->FirstChild('identities');
  1776. $added[] = $m->person_id;
  1777. }
  1778. }
  1779. }
  1780. }
  1781. }
  1782. return $result;
  1783. }
  1784. function _t($t) {
  1785. return $t;
  1786. }
  1787. function laconica_time($ts) {
  1788. include 'wp-content/language/lang_chooser.php'; //Loads the language-file
  1789. $t = strtotime($ts);
  1790. $now = time();
  1791. $diff = $now - $t;
  1792. if ($diff < 60) {
  1793. return _t($txt['functions_few_seconds']);
  1794. } else if ($diff < 92) {
  1795. return _t($txt['functions_about_a_minute']);
  1796. } else if ($diff < 3300) {
  1797. return _t($txt['functions_about_mins_1']) . round($diff/60) . _t($txt['functions_about_mins_2']);
  1798. } else if ($diff < 5400) {
  1799. return _t($txt['functions_about_an_hour']);
  1800. } else if ($diff < 22 * 3600) {
  1801. return _t($txt['functions_about_hours_1']) . round($diff/3600) . _t($txt['functions_about_hours_2']);
  1802. } else if ($diff < 37 * 3600) {
  1803. return _t($txt['functions_about_a_day']);
  1804. } else if ($diff < 24 * 24 * 3600) {
  1805. return _t($txt['functions_about_days_1']) . round($diff/(24*3600)) . _t($txt['functions_about_days_2']);
  1806. } else if ($diff < 46 * 24 * 3600) {
  1807. return _t($txt['functions_about_a_month']);
  1808. } else if ($diff < 330 * 24 * 3600) {
  1809. return _t($txt['functions_about_months_1']) . round($diff/(30*24*3600)) . _t($txt['functions_about_months_2']);
  1810. } else if ($diff < 480 * 24 * 3600) {
  1811. return _t($txt['functions_about_a_year']);
  1812. }
  1813. }
  1814. function time_3339($str) {
  1815. $timestamp = strtotime($str);
  1816. if (!$timestamp) {
  1817. $timestamp = time();
  1818. }
  1819. $date = date('Y-m-d\TH:i:s', $timestamp);
  1820. $matches = array();
  1821. if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
  1822. $date .= $matches[1].$matches[2].':'.$matches[3];
  1823. } else {
  1824. $date .= 'Z';
  1825. }
  1826. return $date;
  1827. }
  1828. function time_2822($str) {
  1829. return strftime ("%a, %d %b %Y %H:%M:%S %z", strtotime($str));
  1830. }
  1831. function time_of($str) {
  1832. return strftime ("%a %b %e %I:%M %p", strtotime($str));
  1833. }
  1834. /**
  1835. * getLocaltime
  1836. *
  1837. * echo ' Server Time: '.date("F d, Y - g:i A",time());;
  1838. * echo " || GMT Time: " . gmdate("F d Y - g:i A", time());
  1839. * echo ' || Localtime: '.getLocaltime('+5.5',0);
  1840. *
  1841. * @author http://techjunk.websewak.com/
  1842. * @access public
  1843. * @param string $GMT
  1844. * @param string $dst
  1845. * @return string
  1846. */
  1847. function getLocaltime($GMT,$dst){
  1848. if(preg_match('/-/i',$GMT))
  1849. {
  1850. $sign = "-";
  1851. }
  1852. else
  1853. {
  1854. $sign = "+";
  1855. }
  1856. $h = round((float)$GMT,2);
  1857. $dst = "true";
  1858. if ($dst)
  1859. {
  1860. $daylight_saving = date('I');
  1861. if ($daylight_saving)
  1862. {
  1863. if ($sign == "-"){ $h=$h-1; }
  1864. else { $h=$h+1; }
  1865. }
  1866. }
  1867. // FIND DIFFERENCE FROM GMT
  1868. $hm = $h * 60;
  1869. $ms = $hm * 60;
  1870. // SET CURRENT TIME
  1871. if ($sign == "-"){ $timestamp = time()-($ms); }
  1872. else { $timestamp = time()+($ms); }
  1873. // SAMPLE OUTPUT
  1874. $gmdate = gmdate("F d, Y - g:i A", $timestamp);
  1875. return $gmdate;
  1876. }
  1877. function make_token($int='99') {
  1878. return dechex(crc32($int.microtime()));
  1879. }
  1880. function normalize_username($username) {
  1881. $username = preg_replace('|[^https?://]?[^\/]+/(xri.net/([^@]!?)?)?/?|', '', $username);
  1882. return trim($username);
  1883. }
  1884. function is_jpg( $file ) {
  1885. return (exif_imagetype($file) == IMAGETYPE_JPEG);
  1886. }
  1887. function is_gif( $file ) {
  1888. return (exif_imagetype($file) == IMAGETYPE_GIF);
  1889. }
  1890. function is_png( $file ) {
  1891. return (exif_imagetype($file) == IMAGETYPE_PNG);
  1892. }
  1893. if ( ! function_exists( 'exif_imagetype' ) ) {
  1894. function exif_imagetype ( $filename ) {
  1895. if ( ( list($width, $height, $type, $attr) = getimagesize( $filename ) ) !== false ) {
  1896. return $type;
  1897. }
  1898. return false;
  1899. }
  1900. }
  1901. function isset_admin_email() {
  1902. return (! (environment('email_from') == 'root@localhost' ));
  1903. }
  1904. function admin_alert($text) {
  1905. global $request;
  1906. if (!isset_admin_email())
  1907. return;
  1908. send_email( environment('email_from'), "admin alert for ".$request->base, $text, environment('email_from'), environment('email_name'), false );
  1909. }
  1910. function omb_dev_alert($text) {
  1911. global $request;
  1912. if (!isset_admin_email() || $request->domain != 'openmicroblogger.com')
  1913. return;
  1914. send_email( environment('email_from'), "admin alert for ".$request->base, $text, environment('email_from'), environment('email_name'), false );
  1915. }
  1916. // for Cake libs
  1917. function uses( $var ) {
  1918. return;
  1919. }
  1920. class Object {
  1921. }
  1922. // end Cake libs
  1923. // if REST PUT is only one field, via Ajax
  1924. // then show the field value after saving
  1925. function ajax_put_field( &$model, &$rec ) {
  1926. global $request;
  1927. if (!(is_ajax()))
  1928. return;
  1929. $fields = $model->fields_from_request( $request );
  1930. if (isset($fields[$request->resource]))
  1931. $fieldsarr = $fields[$request->resource];
  1932. if (count($fieldsarr) == 1) {
  1933. list($field,$type) = each($fieldsarr);
  1934. if (strpos('password',$field)) {
  1935. $chars = split('',$rec->$field);
  1936. foreach($chars as $c)
  1937. echo "*";
  1938. } else {
  1939. echo $rec->$field;
  1940. }
  1941. exit;
  1942. }
  1943. }
  1944. function migrate() {
  1945. global $db,$request;
  1946. $db->just_get_objects();
  1947. foreach($db->models as $model)
  1948. if ($model){
  1949. $model->migrate();
  1950. if (method_exists( $model, 'init' ))
  1951. $model->init();
  1952. }
  1953. echo "<br />The database schema is now synced to the data models. <a href=\"".$request->url_for('admin')."\">Return to Admin</a><br /><br />";
  1954. exit;
  1955. }
  1956. function is_ajax() {
  1957. return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest");
  1958. }
  1959. /**
  1960. * Reference Value
  1961. *
  1962. * get a value from another table
  1963. *
  1964. * @author Brian Hendrickson <brian@dbscript.net>
  1965. * @access public
  1966. * @param string table
  1967. * @param string field
  1968. * @param integer pkval
  1969. * @return string[]
  1970. */
  1971. function reference_value( $table, $field, $pkval ) {
  1972. global $db;
  1973. $rec = $db->get_record( $table, $pkval );
  1974. return $rec->$field;
  1975. }
  1976. function app_profile_show($resource,$action) {
  1977. global $request;
  1978. echo '<script type="text/javascript">'."\n\n";
  1979. echo '// <![CDATA['."\n\n";
  1980. echo ' $(document).ready(function() {'."\n\n";
  1981. echo " var url = '".$request->url_for(array('resource'=>$resource,'action'=>$action))."' + '/partial';"."\n\n";
  1982. echo ' $("#'.$resource.'_profile").html("<img src=\''.base_path(true).'resource/jeditable/indicator.gif\'>");'."\n\n";
  1983. echo ' $.get(url, function(str) {'."\n\n";
  1984. echo ' $("#'.$resource.'_profile").html(str);'."\n\n";
  1985. echo ' });'."\n\n";
  1986. echo '});'."\n\n";
  1987. echo '// ]]>'."\n\n";
  1988. echo '</script>'."\n\n";
  1989. echo '<p class="'.$resource.'_profile" id="'.$resource.'_profile"></p>';
  1990. }
  1991. function app_register_init($resource,$action,$button,$appname,$group) {
  1992. // this func will be triggered by 'init' crosscut
  1993. global $request;
  1994. // make a url from the resource/action Route pattern
  1995. $url = $request->url_for(array(
  1996. 'resource' => $resource,
  1997. 'action' => $action
  1998. ));
  1999. // todo this should be expressable in the url-for XXX
  2000. $url = $url."/partial";
  2001. // add button to menu
  2002. add_management_page( $button, $appname, $group, '', '', $url );
  2003. }
  2004. function get_nav_links() {
  2005. global $request;
  2006. $pid = get_app_id();
  2007. $links = array();
  2008. $i = get_profile($pid);
  2009. $links["Public"] = base_url(true);
  2010. if ($i && $i->id > 0) {
  2011. $links["Personal"] = $request->url_for(array(
  2012. "resource"=>"posts",
  2013. "forid"=>$i->id,
  2014. "page"=>1 ));
  2015. if (empty($i->post_notice))
  2016. $links["Profile"] = $request->url_for(array("resource"=>$i->nickname));
  2017. else
  2018. $links["Profile"] = $i->profile;
  2019. if (empty($i->post_notice))
  2020. $links["@".$i->nickname] = $request->url_for(array("resource"=>$i->nickname))."/replies";
  2021. else
  2022. $links["@".$i->nickname] = $i->profile."/replies";
  2023. }
  2024. if ($pid > 0) {
  2025. if (member_of('administrators'))
  2026. $links["Admin"] = $request->url_for(array('resource'=>'admin'));
  2027. $links["Upload"] = $request->url_for(array('resource'=>'posts','action'=>'upload'));
  2028. $links["Logout"] = $request->url_for("openid_logout");
  2029. } else {
  2030. $links["Register"] = $request->url_for("register");
  2031. $links["Login"] = $request->url_for("email_login");
  2032. }
  2033. return $links;
  2034. }
  2035. function get_app_id() {
  2036. global $db;
  2037. global $request;
  2038. $id = false;
  2039. if (!($request->resource == 'identities')) {
  2040. if ($request->params['byid'] > 0)
  2041. $id = $request->params['byid'];
  2042. elseif ($request->params['forid'] > 0)
  2043. $id = $request->params['forid'];
  2044. elseif (get_profile_id())
  2045. $id = get_profile_id();
  2046. if ($id && !(strpos($id,".") === false )) {
  2047. $parts = split('\.',$id);
  2048. $id = $parts[0];
  2049. }
  2050. if (!$id) {
  2051. //authenticate_with_http();
  2052. //$id = get_profile_id();
  2053. }
  2054. return $id;
  2055. }
  2056. // looking some profile page
  2057. // load its apps
  2058. if ($request->id > 0)
  2059. return $request->id;
  2060. elseif (get_profile_id())
  2061. return get_profile_id();
  2062. else
  2063. return false;
  2064. }
  2065. function app_path() {
  2066. return $GLOBALS['PATH']['app'];
  2067. }
  2068. function load_apps() {
  2069. global $apps_loaded;
  2070. if ($apps_loaded == true)
  2071. return;
  2072. // enable wp-style callback functions
  2073. global $db,$request,$env;
  2074. if (in_array($request->action,array(
  2075. 'replies','following','followers'
  2076. ))) return;
  2077. $identity = get_app_id();
  2078. if (!$identity){
  2079. global $api_methods;
  2080. if (array_key_exists($request->action,$api_methods)){
  2081. authenticate_with_http();
  2082. $identity = get_app_id();
  2083. }
  2084. }
  2085. if (!$identity)
  2086. return;
  2087. $Identity =& $db->model('Identity');
  2088. $Setting =& $db->model('Setting');
  2089. $i = $Identity->find($identity);
  2090. $activated = array();
  2091. while ($s = $i->NextChild('settings')){
  2092. $s = $Setting->find($s->id);
  2093. if ($s->name == 'app') {
  2094. app_init( $s->value );
  2095. $activated[] = $s->value;
  2096. }
  2097. }
  2098. if (isset($env['installed'])){
  2099. $list = $env['installed'];
  2100. foreach($list as $app)
  2101. if (!in_array($app,$activated))
  2102. app_init( $app );
  2103. }
  2104. global $current_user;
  2105. trigger_before( 'init', $current_user, $current_user );
  2106. $apps_loaded = true;
  2107. }
  2108. function app_init($appname) {
  2109. $startfile = app_path() . $appname . DIRECTORY_SEPARATOR . $appname . ".php";
  2110. if (is_file($startfile))
  2111. require_once $startfile;
  2112. $pluginsdir = app_path() . $appname . DIRECTORY_SEPARATOR . 'plugins';
  2113. if (is_dir($pluginsdir)) {
  2114. $GLOBALS['PATH']['app_plugins'][] = $pluginsdir;
  2115. $startfile = $pluginsdir.DIRECTORY_SEPARATOR.$appname.".php";
  2116. if (is_file($startfile))
  2117. require_once $startfile;
  2118. }
  2119. $events = array(
  2120. 'admin_head' => 'head',
  2121. 'admin_menu' => 'menu',
  2122. 'wp_head' => 'head',
  2123. 'publish_post' => 'post',
  2124. 'the_content' => 'show'
  2125. );
  2126. foreach( $events as $wpevent=>$dbevent )
  2127. if (function_exists($appname.'_'.$dbevent))
  2128. add_action( $wpevent, $appname.'_'.$dbevent);
  2129. if (function_exists($appname."_init"))
  2130. before_filter( $appname."_init", 'init' );
  2131. }
  2132. function array_sort($array, $key, $max=false)
  2133. {
  2134. for ($i = 0; $i < sizeof($array); $i++) {
  2135. $sort_values[$i] = $array[$i][$key];
  2136. }
  2137. asort ($sort_values);
  2138. reset ($sort_values);
  2139. while (list ($arr_key, $arr_val) = each ($sort_values)) {
  2140. if ($max) {
  2141. if (count($sorted_arr) < $max)
  2142. $sorted_arr[] = $array[$arr_key];
  2143. } else {
  2144. $sorted_arr[] = $array[$arr_key];
  2145. }
  2146. }
  2147. return $sorted_arr;
  2148. }
  2149. global $timezone_offsets;
  2150. $timezone_offsets = array(
  2151. '-12' => 'Baker Island',
  2152. '-11' => 'Niue, Samoa',
  2153. '-10' => 'Hawaii-Aleutian, Cook Island',
  2154. '-9.5' => 'Marquesas Islands',
  2155. '-9' => 'Alaska, Gambier Island',
  2156. '-8' => 'Pacific',
  2157. '-7' => 'Mountain',
  2158. '-6' => 'Central',
  2159. '-5' => 'Eastern',
  2160. '-4' => 'Atlantic',
  2161. '-3.5' => 'Newfoundland',
  2162. '-3' => 'Amazon, Central Greenland',
  2163. '-2' => 'Fernando de Noronha, South Georgia',
  2164. '-1' => 'Azores, Cape Verde, Eastern Greenland',
  2165. '0' => 'Western European, Greenwich Mean',
  2166. '+1' => 'Central European, West African',
  2167. '+2' => 'Eastern European, Central African',
  2168. '+3' => 'Moscow, Eastern African',
  2169. '+3.5' => 'Iran',
  2170. '+4' => 'Gulf, Samara',
  2171. '+4.5' => 'Afghanistan',
  2172. '+5' => 'Pakistan, Yekaterinburg',
  2173. '+5.5' => 'Indian, Sri Lanka',
  2174. '+5.75' => 'Nepal',
  2175. '+6' => 'Bangladesh, Bhutan, Novosibirsk',
  2176. '+6.5' => 'Cocos Islands, Myanmar',
  2177. '+7' => 'Indochina, Krasnoyarsk',
  2178. '+8' => 'Chinese, Australian Western, Irkutsk',
  2179. '+8.75' => 'Southeastern Western Australia',
  2180. '+9' => 'Japan, Korea, Chita',
  2181. '+9.5' => 'Australian Central',
  2182. '+10' => 'Australian Eastern, Vladivostok',
  2183. '+10.5' => 'Lord Howe',
  2184. '+11' => 'Solomon Island, Magadan',
  2185. '+11.5' => 'Norfolk Island',
  2186. '+12' => 'New Zealand, Fiji, Kamchatka',
  2187. '+12.75' => 'Chatham Islands',
  2188. '+13' => 'Tonga, Phoenix Islands',
  2189. '+14' => 'Line Island'
  2190. );
  2191. function pretty_urls() {
  2192. global $pretty_url_base;
  2193. if (isset($pretty_url_base) && !empty($pretty_url_base))
  2194. return true;
  2195. return false;
  2196. }
  2197. function setting($name) {
  2198. if (!signed_in())
  2199. return false;
  2200. global $db;
  2201. global $ombsettings;
  2202. if (!is_array($ombsettings))
  2203. $ombsettings = array();
  2204. if (isset($ombsettings[$name]))
  2205. return $ombsettings[$name];
  2206. $Setting =& $db->model('Setting');
  2207. $sett = $Setting->find_by(array('name'=>$name,'profile_id'=>get_profile_id()));
  2208. if ($sett) {
  2209. $ombsettings[$name] = $sett->value;
  2210. return $ombsettings[$name];
  2211. }
  2212. $ombsettings[$name] = false;
  2213. return false;
  2214. }
  2215. function profile_setting($name) {
  2216. global $db;
  2217. $Setting =& $db->model('Setting');
  2218. $sett = $Setting->find_by(array('name'=>$name,'profile_id'=>get_app_id()));
  2219. if ($sett)
  2220. return $sett->value;
  2221. return false;
  2222. }
  2223. function md5_encrypt($plain_text, $password, $iv_len = 16){
  2224. $plain_text .= "\x13";
  2225. $n = strlen($plain_text);
  2226. if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
  2227. $i = 0;
  2228. $enc_text = get_rnd_iv($iv_len);
  2229. $iv = substr($password ^ $enc_text, 0, 512);
  2230. while ($i < $n) {
  2231. $block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
  2232. $enc_text .= $block;
  2233. $iv = substr($block . $iv, 0, 512) ^ $password;
  2234. $i += 16;
  2235. }
  2236. return base64_encode($enc_text);
  2237. }
  2238. function md5_decrypt($enc_text, $password, $iv_len = 16){
  2239. $enc_text = base64_decode($enc_text);
  2240. $n = strlen($enc_text);
  2241. $i = $iv_len;
  2242. $plain_text = '';
  2243. $iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
  2244. while ($i < $n) {
  2245. $block = substr($enc_text, $i, 16);
  2246. $plain_text .= $block ^ pack('H*', md5($iv));
  2247. $iv = substr($block . $iv, 0, 512) ^ $password;
  2248. $i += 16;
  2249. }
  2250. return preg_replace('/\\x13\\x00*$/', '', $plain_text);
  2251. }
  2252. function get_rnd_iv($iv_len){
  2253. $iv = '';
  2254. while ($iv_len-- > 0) {
  2255. $iv .= chr(mt_rand() & 0xff);
  2256. }
  2257. return $iv;
  2258. }
  2259. function curl_redir_exec( $ch ) {
  2260. $curl_loops = 0;
  2261. $curl_max_loops = 20;
  2262. if ($curl_loops++ >= $curl_max_loops) {
  2263. $curl_loops = 0;
  2264. return FALSE;
  2265. }
  2266. curl_setopt( $ch, CURLOPT_HEADER, true );
  2267. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  2268. $data = curl_exec( $ch );
  2269. list( $header, $data ) = explode( "\n\n", $data, 2 );
  2270. $http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
  2271. if ( $http_code == 301 || $http_code == 302 ) {
  2272. $matches = array();
  2273. preg_match('/Location:(.*?)\n/', $header, $matches);
  2274. $url = @parse_url(trim(array_pop($matches)));
  2275. if (!$url) {
  2276. //couldn't process the url to redirect to
  2277. $curl_loops = 0;
  2278. return $data;
  2279. }
  2280. $last_url = parse_url( curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL ));
  2281. if (!$url['scheme'])
  2282. $url['scheme'] = $last_url['scheme'];
  2283. if (!$url['host'])
  2284. $url['host'] = $last_url['host'];
  2285. if (!$url['path'])
  2286. $url['path'] = $last_url['path'];
  2287. $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
  2288. curl_setopt( $ch, CURLOPT_URL, $new_url );
  2289. return curl_redir_exec( $ch );
  2290. } else {
  2291. $curl_loops=0;
  2292. return $data;
  2293. }
  2294. }
  2295. function set_tz_by_offset($offset) {
  2296. $offset = $offset * 3600;
  2297. $abbrarray = timezone_abbreviations_list();
  2298. foreach ($abbrarray as $abbr) {
  2299. foreach ($abbr as $city) {
  2300. if ($city['offset'] == $offset) { // remember to multiply $offset by -1 if you're getting it from js
  2301. date_default_timezone_set($city['timezone_id']);
  2302. return true;
  2303. }
  2304. }
  2305. }
  2306. date_default_timezone_set("ust");
  2307. return false;
  2308. }
  2309. function setting_widget_text_helper($nam,$nammode,$namurl,$namentry) {
  2310. global $request;
  2311. echo '
  2312. var submit_to'.$nam.' = "'. $namurl.'";
  2313. $(".jeditable_'.$nam.'").mouseover(function() {
  2314. $(this).highlightFade({end:\'#def\'});
  2315. });
  2316. $(".jeditable_'.$nam.'").mouseout(function() {
  2317. $(this).highlightFade({end:\'#fff\', speed:200});
  2318. });
  2319. $(".jeditable_'.$nam.'").editable(submit_to'.$nam.', {
  2320. indicator : "<img src=\''. base_path(true).'resource/jeditable/indicator.gif\'>",
  2321. submitdata : function() {
  2322. return {"entry[etag]" : "'.$namentry->etag.'"};
  2323. },
  2324. name : "setting[value]",
  2325. type : "textarea",
  2326. noappend : "true",
  2327. submit : "OK",
  2328. tooltip : "Click to edit...",
  2329. cancel : "Cancel",
  2330. callback : function(value, settings) {
  2331. return(value);
  2332. }
  2333. }); ';
  2334. };
  2335. function setting_widget_text_post_helper($nam,$namurl) {
  2336. global $request;
  2337. echo '
  2338. var submit_to'.$nam.' = "'. $namurl.'";
  2339. $(".jeditable_'.$nam.'").mouseover(function() {
  2340. $(this).highlightFade({end:\'#def\'});
  2341. });
  2342. $(".jeditable_'.$nam.'").mouseout(function() {
  2343. $(this).highlightFade({end:\'#fff\', speed:200});
  2344. });
  2345. $(".jeditable_'.$nam.'").editable(submit_to'.$nam.', {
  2346. indicator : "<img src=\''. base_path(true).'resource/jeditable/indicator.gif\'>",
  2347. submitdata : function() {
  2348. return {"setting[name]" : "'.'config.env.'.$nam.'"};
  2349. },
  2350. name : "setting[value]",
  2351. type : "textarea",
  2352. noappend : "true",
  2353. submit : "OK",
  2354. tooltip : "Click to edit...",
  2355. cancel : "Cancel",
  2356. callback : function(value, settings) {
  2357. return(value);
  2358. }
  2359. }); ';
  2360. };
  2361. function tinymce_widget_text_post_helper($nam,$namurl,$post,$field,$namentry) {
  2362. echo '
  2363. var submit_to'.$nam.' = "'. $namurl.'";
  2364. $(".jeditable_'.$nam.'").editable(submit_to'.$nam.', {
  2365. indicator : "<img src=\''. base_path(true).'resource/jeditable/indicator.gif\'>",
  2366. submitdata : function() {
  2367. return {"method":"put","entry[etag]" : "'.$namentry->etag.'"};
  2368. },
  2369. name : "'.$post.'['.$field.']",
  2370. type : "mce",
  2371. noappend : "true",
  2372. width : "500px",
  2373. height : "100px",
  2374. submit : "OK",
  2375. tooltip : "Click to edit...",
  2376. cancel : "Cancel",
  2377. callback : function(value, settings) {
  2378. return(value);
  2379. }
  2380. });
  2381. ';
  2382. return;
  2383. echo '
  2384. var submit_to'.$nam.' = "'. $namurl.'";
  2385. $(".jeditable_'.$nam.'").editable(submit_to'.$nam.', {
  2386. indicator : "<img src=\''. base_path(true).'resource/jeditable/indicator.gif\'>",
  2387. submitdata : function() {
  2388. return {"method":"put","entry[etag]" : "'.$namentry->etag.'"};
  2389. },
  2390. name : "'.$post.'['.$field.']",
  2391. type : "mce",
  2392. noappend : "true",
  2393. width : "500px",
  2394. height : "100px",
  2395. submit : "OK",
  2396. tooltip : "Click to edit...",
  2397. cancel : "Cancel",
  2398. callback : function(value, settings) {
  2399. return(value);
  2400. }
  2401. }); ';
  2402. };
  2403. function setting_widget_helper($nam,$nammode,$namurl,$namentry,$listdata) {
  2404. if (!class_exists("Services_JSON")) lib_include("json"); $json = new Services_JSON();
  2405. global $request;
  2406. echo '
  2407. var submit_to'.$nam.' = "'. $namurl.'";
  2408. $(".jeditable_'.$nam.'").mouseover(function() {
  2409. $(this).highlightFade({end:\'#def\'});
  2410. });
  2411. $(".jeditable_'.$nam.'").mouseout(function() {
  2412. $(this).highlightFade({end:\'#fff\', speed:200});
  2413. });
  2414. $(".jeditable_'.$nam.'").editable(submit_to'.$nam.', {
  2415. indicator : "<img src=\''. base_path(true).'resource/jeditable/indicator.gif\'>",
  2416. data : \''
  2417. .$json->encode( $listdata ).
  2418. '\',
  2419. submitdata : function() {
  2420. return {"entry[etag]" : "'.$namentry->etag.'"};
  2421. },
  2422. name : "setting[value]",
  2423. type : "select",
  2424. placeholder : "'.placeholder_value($nammode,$listdata).'",
  2425. noappend : "true",
  2426. submit : "OK",
  2427. tooltip : "Click to edit...",
  2428. cancel : "Cancel",
  2429. callback : function(value, settings) {
  2430. $(this).html(settings[\'jsonarr\'][value-0]);
  2431. return(value);
  2432. }
  2433. }); ';
  2434. }
  2435. function placeholder_value(&$setting,$listdata) {
  2436. if ($listdata[0] == 'false' && $listdata[1] == 'true')
  2437. return $listdata[$setting->value];
  2438. return $setting->value;
  2439. }
  2440. function authenticate_with_omb() {
  2441. //
  2442. }
  2443. function authenticate_with_http() {
  2444. global $db,$request;
  2445. global $person_id;
  2446. global $api_methods,$api_method_perms;
  2447. if (array_key_exists($request->action,$api_method_perms)) {
  2448. $arr = $api_method_perms[$request->action];
  2449. if ($db->models[$arr['table']]->can($arr['perm']))
  2450. return;
  2451. }
  2452. if (!isset($_SERVER['PHP_AUTH_USER'])) {
  2453. header('WWW-Authenticate: Basic realm="your username/password"');
  2454. } else {
  2455. $Identity =& $db->get_table( 'identities' );
  2456. $Person =& $db->get_table( 'people' );
  2457. $Identity->set_param('find_by',array(
  2458. 'nickname'=>$_SERVER['PHP_AUTH_USER'],
  2459. 'password'=>md5($_SERVER['PHP_AUTH_PW'])
  2460. ));
  2461. $Identity->find();
  2462. $i = $Identity->MoveFirst();
  2463. $p = $Person->find( $i->person_id );
  2464. if (!(isset( $p->id ) && $p->id > 0)) {
  2465. header('HTTP/1.1 401 Unauthorized');
  2466. echo 'BAD LOGIN';
  2467. exit;
  2468. }
  2469. $person_id = $p->id;
  2470. }
  2471. }
  2472. function authenticate_with_oauth() {
  2473. //
  2474. }
  2475. function mu_url() {
  2476. global $request;
  2477. if ((!strpos($request->uri, 'ak_twitter/') && strpos($request->uri, '?twitter/')) ||
  2478. (strpos($request->uri, 'ak_twitter/') && strpos($request->uri, '?twitter/')))
  2479. return true;
  2480. return false;
  2481. }
  2482. function mb_unserialize($serial_str) {
  2483. $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
  2484. return unserialize($out);
  2485. }
  2486. function handle_posted_file($filename="",$att,$profile) {
  2487. global $db,$request,$response;
  2488. $response->set_var('profile',$profile);
  2489. load_apps();
  2490. if (isset($_FILES['media']['tmp_name']))
  2491. $table = 'uploads';
  2492. else
  2493. $table = 'posts';
  2494. $modelvar = classify($table);
  2495. $_FILES = array(
  2496. strtolower($modelvar) => array(
  2497. 'name' => array( 'attachment' => $filename ),
  2498. 'tmp_name' => array( 'attachment' => $att )
  2499. ));
  2500. $Post =& $db->model( 'Post' );
  2501. $Upload =& $db->model( 'Upload' );
  2502. $field = 'attachment';
  2503. $request->set_param('resource',$table);
  2504. $request->set_param( array( strtolower(classify($table)), $field ),
  2505. $att );
  2506. if (!isset($_FILES['media']['tmp_name']))
  2507. trigger_before( 'insert_from_post', $$modelvar, $request );
  2508. $content_type = 'text/html';
  2509. $rec = $$modelvar->base();
  2510. $content_type = type_of( $filename );
  2511. $rec->set_value('profile_id',get_profile_id());
  2512. $rec->set_value( 'parent_id', 0 );
  2513. if (isset($request->params['message']))
  2514. $rec->set_value( 'title', $request->params['message'] );
  2515. else
  2516. $rec->set_value( 'title', '' );
  2517. if ($table == 'uploads')
  2518. $rec->set_value( 'tmp_name', 'new' );
  2519. $upload_types = environment('upload_types');
  2520. if (!$upload_types)
  2521. $upload_types = array('jpg','jpeg','png','gif');
  2522. $ext = extension_for( type_of($filename));
  2523. if (!(in_array($ext,$upload_types)))
  2524. trigger_error('Sorry, this site only allows the following file types: '.implode(',',$upload_types), E_USER_ERROR);
  2525. $rec->set_value( $field, $att );
  2526. $rec->save_changes();
  2527. $tmp = $att;
  2528. if (is_jpg($tmp)) {
  2529. $thumbsize = environment('max_pixels');
  2530. $Thumbnail =& $db->model('Thumbnail');
  2531. $t = $Thumbnail->base();
  2532. $newthumb = tempnam( "/tmp", "new".$rec->id.".jpg" );
  2533. resize_jpeg($tmp,$newthumb,$thumbsize);
  2534. $t->set_value('target_id',$atomentry->id);
  2535. $t->save_changes();
  2536. update_uploadsfile( 'thumbnails', $t->id, $newthumb );
  2537. $t->set_etag();
  2538. }
  2539. $atomentry = $$modelvar->set_metadata($rec,$content_type,$table,'id');
  2540. $$modelvar->set_categories($rec,$request,$atomentry);
  2541. // $url = $request->url_for(array(
  2542. // 'resource'=>$table,
  2543. // 'id'=>$rec->id
  2544. // ));
  2545. // $title = substr($rec->title,0,140);
  2546. // $over = ((strlen($title) + strlen($url) + 1) - 140);
  2547. // if ($over > 0)
  2548. // $rec->set_value('title',substr($title,0,-$over)." ".$url);
  2549. // else
  2550. // $rec->set_value('title',$title." ".$url);
  2551. // $rec->save_changes();
  2552. if (!isset($_FILES['media']['tmp_name']))
  2553. trigger_after( 'insert_from_post', $$modelvar, $rec );
  2554. return true;
  2555. }
  2556. function ent2ncr($text) {
  2557. return $text;
  2558. }
  2559. function esc_html($text) {
  2560. return $text;
  2561. }
  2562. function wp_remote_post( $url, $paramarr ){
  2563. return wp_remote_get( $url, $paramarr, true );
  2564. }
  2565. function esc_url($url){
  2566. return urlencode($url);
  2567. }
  2568. function wp_remote_get( $url, $paramarr, $post=false ){
  2569. $method = $paramarr['method'];
  2570. $timeout = $paramarr['timeout'];
  2571. $agent = $paramarr['user-agent'];
  2572. $port = $paramarr['port'];
  2573. $ch = curl_init();
  2574. curl_setopt ($ch, CURLOPT_URL, $url);
  2575. curl_setopt ($ch, CURLOPT_HEADER, 0); /// Header control
  2576. curl_setopt ($ch, CURLOPT_PORT, $port);
  2577. if ($post){
  2578. curl_setopt ($ch, CURLOPT_POST, true); /// tell it to make a POST, not a GET
  2579. curl_setopt ($ch, CURLOPT_POSTFIELDS, $paramarr['body']);
  2580. }
  2581. if (isset($paramarr['headers']))
  2582. curl_setopt($ch, CURLOPT_HTTPHEADER, $paramarr['headers']);
  2583. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2584. curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout);
  2585. curl_setopt($ch, CURLOPT_USERAGENT, $agent);
  2586. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  2587. $xml_response = curl_exec ($ch);
  2588. $response = curl_getinfo( $ch );
  2589. curl_close ( $ch );
  2590. $result = array();
  2591. $result['response'] = array('code'=>$response['http_code']);
  2592. $result['body']=$xml_response;
  2593. return $result;
  2594. }
  2595. function readUrl($url){
  2596. $timeout = 10;
  2597. $ch = curl_init();
  2598. curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
  2599. curl_setopt( $ch, CURLOPT_URL, $url );
  2600. curl_setopt( $ch, CURLOPT_ENCODING, "" );
  2601. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  2602. curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
  2603. curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
  2604. curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
  2605. curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
  2606. $content = curl_exec( $ch );
  2607. $response = curl_getinfo( $ch );
  2608. curl_close ( $ch );
  2609. if($response['http_code'] == 200)
  2610. {
  2611. return $content;
  2612. }
  2613. return false;
  2614. }
  2615. function realtime($callback,$payload,$prefix=false){
  2616. if (defined('PING') && !PING)
  2617. return;
  2618. if (defined('REALTIME_HOST') && !REALTIME_HOST )
  2619. return;
  2620. global $db;
  2621. if ($prefix)
  2622. $chan = $prefix;
  2623. elseif (!empty($db->prefix))
  2624. $chan = $db->prefix;
  2625. else
  2626. $chan = "chan";
  2627. if (!(class_exists('Services_JSON')))
  2628. lib_include( 'json' );
  2629. $json = new Services_JSON();
  2630. $payload['callback'] = $callback;
  2631. $load = $json->encode($payload);
  2632. $curl = curl_init( "http://".REALTIME_HOST.":".REALTIME_PORT );
  2633. curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
  2634. curl_setopt( $curl, CURLOPT_TIMEOUT, 1);
  2635. curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'ADDMESSAGE '.$chan.' '.addslashes($load) );
  2636. curl_exec($curl);
  2637. }
  2638. function echo_home_timeline_tweet($tweet,$user){
  2639. echo ' <status>
  2640. <created_at>'.$tweet['created_at'].'</created_at>
  2641. <id>'.$tweet['id'].'</id>
  2642. <text>'.$tweet['text'].'</text>
  2643. <source>'.$tweet['source'].'</source>
  2644. <truncated>'.$tweet['truncated'].'</truncated>
  2645. <in_reply_to_status_id>'.$tweet['in_reply_to_status_id'].'</in_reply_to_status_id>
  2646. <in_reply_to_user_id>'.$tweet['in_reply_to_user_id'].'</in_reply_to_user_id>
  2647. <favorited>'.$tweet['favorited'].'</favorited>
  2648. <in_reply_to_screen_name>'.$tweet['in_reply_to_screen_name'].'</in_reply_to_screen_name>
  2649. <user>
  2650. <id>'.$user['id'].'</id>
  2651. <name>'.$user['name'].'</name>
  2652. <screen_name>'.$user['screen_name'].'</screen_name>
  2653. <description>'.$user['description'].'</description>
  2654. <profile_image_url>'.$user['profile_image_url'].'</profile_image_url>
  2655. <url>'.$user['url'].'</url>
  2656. <protected>'.$user['protected'].'</protected>
  2657. <followers_count>'.$user['followers_count'].'</followers_count>
  2658. <profile_background_color>'.$user['profile_background_color'].'</profile_background_color>
  2659. <profile_text_color>'.$user['profile_text_color'].'</profile_text_color>
  2660. <profile_link_color>'.$user['profile_link_color'].'</profile_link_color>
  2661. <profile_sidebar_fill_color>'.$user['profile_sidebar_fill_color'].'</profile_sidebar_fill_color>
  2662. <profile_sidebar_border_color>'.$user['profile_sidebar_border_color'].'</profile_sidebar_border_color>
  2663. <friends_count>'.$user['friends_count'].'</friends_count>
  2664. <created_at>'.$user['created_at'].'</created_at>
  2665. <favourites_count>'.$user['favourites_count'].'</favourites_count>
  2666. <utc_offset>'.$user['utc_offset'].'</utc_offset>
  2667. <time_zone>'.$user['time_zone'].'</time_zone>
  2668. <profile_background_image_url>'.$user['profile_background_image_url'].'</profile_background_image_url>
  2669. <profile_background_tile>'.$user['profile_background_tile'].'</profile_background_tile>
  2670. <notifications>'.$user['notifications'].'</notifications>
  2671. <geo_enabled>'.$user['geo_enabled'].'</geo_enabled>
  2672. <verified>'.$user['verified'].'</verified>
  2673. <following>'.$user['following'].'</following>
  2674. <statuses_count>'.$user['statuses_count'].'</statuses_count>
  2675. <lang>en</lang>
  2676. <contributors_enabled>false</contributors_enabled>
  2677. </user>
  2678. <geo/>
  2679. <coordinates/>
  2680. <place/>
  2681. <contributors/>
  2682. </status>
  2683. ';
  2684. }
  2685. function render_home_timeline($single=false,$id=null){
  2686. global $request,$db;
  2687. $profile = get_profile();
  2688. $nick = $profile->nickname;
  2689. $Identity =& $db->model( 'Identity' );
  2690. $Identity->set_param('find_by',array(
  2691. 'nickname' => $nick,
  2692. 'eq'=>'IS',
  2693. 'post_notice' => 'NULL',
  2694. ));
  2695. $Post =& $db->model( 'Post' );
  2696. //$Post->set_param( 'find_by', array(
  2697. // 'entries.person_id' => $profile->person_id
  2698. //));
  2699. $Setting =& $db->model('Setting');
  2700. if (!$single)
  2701. echo '<?xml version="1.0" encoding="UTF-8"?>
  2702. <statuses type="array">
  2703. ';
  2704. else
  2705. echo '<?xml version="1.0" encoding="UTF-8"?>
  2706. ';
  2707. //$Post->set_order('desc');
  2708. if (isset($_GET['count'])){
  2709. $Post->set_limit($_GET['count']);
  2710. }else {
  2711. $Post->set_limit(100);
  2712. }
  2713. $Post->has_one('profile_id:'.$prefix.'identities');
  2714. if (!$single) {
  2715. if (isset($_GET['since_id'])){
  2716. $Post->set_param( 'find_by', array(
  2717. 'eq'=>'>',
  2718. 'posts.id' => $_GET['since_id']
  2719. ));
  2720. }
  2721. // echo $Post->get_query(); exit;
  2722. $Post->find();
  2723. } else {
  2724. $Post->find($id);
  2725. }
  2726. $tweets = array();
  2727. while ($p = $Post->MoveNext()) {
  2728. $profile = $p->FirstChild('identities');
  2729. $tweet = array();
  2730. $user = array();
  2731. $tit = iconv('UTF-8', 'ASCII//TRANSLIT', $p->title);
  2732. $tweet['text'] = htmlentities($tit);
  2733. $tweet['truncated'] = 'false';
  2734. $tweet['created_at'] = date( "D M d G:i:s O Y", strtotime( $p->created ));
  2735. $tweet['in_reply_to_status_id'] = '';
  2736. $tweet['source'] = 'web';
  2737. $tweet['id'] = intval( $p->id );
  2738. $tweet['favorited'] ='false';
  2739. $tweet['user'] = htmlentities($nick);
  2740. $tweet['in_reply_to_user_id'] = '';
  2741. $tweet['in_reply_to_screen_name'] = '';
  2742. $bio = iconv('UTF-8', 'ASCII//TRANSLIT', $profile->bio);
  2743. $user['id'] = $profile->id;
  2744. $user['name'] = htmlentities(iconv('UTF-8', 'ASCII//TRANSLIT', $profile->fullname));
  2745. $user['screen_name'] = htmlentities(iconv('UTF-8', 'ASCII//TRANSLIT', $profile->nickname));
  2746. $user['location'] = htmlentities(iconv('UTF-8', 'ASCII//TRANSLIT', $profile->locality));
  2747. $user['description'] = htmlentities($bio);
  2748. $user['profile_image_url'] = htmlentities(iconv('UTF-8', 'ASCII//TRANSLIT', $profile->avatar));
  2749. $user['url'] = htmlentities(iconv('UTF-8', 'ASCII//TRANSLIT', $profile->homepage));
  2750. $user['protected'] = 'false';
  2751. $user['followers_count'] = '0';
  2752. $user['profile_background_color'] = 'FFFFFF';
  2753. $user['profile_text_color'] = '000000';
  2754. $user['profile_link_color'] = '405991';
  2755. $user['profile_sidebar_fill_color'] = 'FFFFFF';
  2756. $user['profile_sidebar_border_color'] = 'FFFFFF';
  2757. $user['friends_count'] = '0';
  2758. $user['created_at'] = date( "D M d G:i:s O Y", strtotime( $profile->created ));
  2759. $user['favourites_count'] = '0';
  2760. $user['utc_offset'] = '-28800';
  2761. $user['time_zone'] = 'Pacific Time (US &amp; Canada)';
  2762. $settingvalue = $Setting->find_by(array('name'=>'background_image','profile_id'=>$profile->id));
  2763. $user['profile_background_image_url'] = $settingvalue->value;
  2764. $settingvalue = $Setting->find_by(array('name'=>'background_tile','profile_id'=>$profile->id));
  2765. $user['profile_background_tile'] = $settingvalue->value;
  2766. $user['notifications'] = 'false';
  2767. $user['geo_enabled'] = 'false';
  2768. $user['verified'] = 'false';
  2769. $user['following'] = 'true';
  2770. $user['statuses_count'] = '0';
  2771. $tweets[] = array($tweet,$user);
  2772. echo_home_timeline_tweet($tweet,$user);
  2773. if ($single)
  2774. break;
  2775. }
  2776. if (!$single)
  2777. echo '</statuses>';
  2778. exit;
  2779. }
  2780. class AuthToken {
  2781. var $token;
  2782. var $secret;
  2783. }