KXStudio Website https://kx.studio/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Model.php 19KB

9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  2. /**
  3. * Class: Model
  4. * The basis for the Models system.
  5. */
  6. class Model {
  7. # Array: $caches
  8. # Caches every loaded module into a clone of the object.
  9. static $caches = array();
  10. # Array: $belongs_to
  11. # An array of models that this Model belongs to.
  12. # This model should have a [modelname]_id column.
  13. public $belongs_to = array();
  14. # Array: $has_many
  15. # An array of models that belong to this Model.
  16. # They should have a [thismodel]_id column.
  17. public $has_many = array();
  18. # Array: $has_one
  19. # An array of models that this model has only one of.
  20. # The models should have a [thismodel]_id column.
  21. public $has_one = array();
  22. /**
  23. * Function: __get
  24. * Automatically handle model relationships when grabbing attributes of an object.
  25. *
  26. * Returns:
  27. * @mixed@
  28. */
  29. public function __get($name) {
  30. $model_name = get_class($this);
  31. $placeholders = (isset($this->__placeholders) and $this->__placeholders);
  32. Trigger::current()->filter($filtered, $model_name."_".$name."_attr", $this);
  33. if ($filtered !== false)
  34. $this->$name = $filtered;
  35. $this->belongs_to = (array) $this->belongs_to;
  36. $this->has_many = (array) $this->has_many;
  37. $this->has_one = (array) $this->has_one;
  38. if (in_array($name, $this->belongs_to) or isset($this->belongs_to[$name])) {
  39. $class = (isset($this->belongs_to[$name])) ? $this->belongs_to[$name] : $name ;
  40. if (isset($this->belongs_to[$name])) {
  41. $opts =& $this->belongs_to[$name];
  42. $model = oneof(@$opts["model"], $name);
  43. if (preg_match("/^\(([a-z0-9_]+)\)$/", $model, $match))
  44. $model = $this->$match[1];
  45. $match = oneof(@$opts["by"], strtolower($name));
  46. fallback($opts["where"], array("id" => $this->{$match."_id"}));
  47. $opts["where"] = (array) $opts["where"];
  48. foreach ($opts["where"] as &$val)
  49. if (preg_match("/^\(([a-z0-9_]+)\)$/", $val, $match))
  50. $val = $this->$match[1];
  51. fallback($opts["placeholders"], $placeholders);
  52. } else {
  53. $model = $name;
  54. $opts = array("where" => array("id" => $this->{$name."_id"}));
  55. }
  56. return $this->$name = new $model(null, $opts);
  57. } elseif (in_array($name, $this->has_many) or isset($this->has_many[$name])) {
  58. if (isset($this->has_many[$name])) {
  59. $opts =& $this->has_many[$name];
  60. $model = oneof(@$opts["model"], depluralize($name));
  61. if (preg_match("/^\(([a-z0-9_]+)\)$/", $model, $match))
  62. $model = $this->$match[1];
  63. $match = oneof(@$opts["by"], strtolower($name));
  64. fallback($opts["where"], array($match."_id" => $this->id));
  65. $opts["where"] = (array) $opts["where"];
  66. foreach ($opts["where"] as &$val)
  67. if (preg_match("/^\(([a-z0-9_]+)\)$/", $val, $match))
  68. $val = $this->$match[1];
  69. fallback($opts["placeholders"], $placeholders);
  70. } else {
  71. $model = depluralize($name);
  72. $match = $model_name;
  73. $opts = array("where" => array(strtolower($match)."_id" => $this->id),
  74. "placeholders" => $placeholders);
  75. }
  76. return $this->$name = call_user_func(array($model, "find"), $opts);
  77. } elseif (in_array($name, $this->has_one) or isset($this->has_one[$name])) {
  78. if (isset($this->has_one[$name])) {
  79. $opts =& $this->has_one[$name];
  80. $model = oneof(@$opts["model"], depluralize($name));
  81. if (preg_match("/^\(([a-z0-9_]+)\)$/", $model, $match))
  82. $model = $this->$match[1];
  83. $match = oneof(@$opts["by"], strtolower($name));
  84. fallback($opts["where"], array($match."_id" => $this->id));
  85. $opts["where"] = (array) $opts["where"];
  86. foreach ($opts["where"] as &$val)
  87. if (preg_match("/^\(([a-z0-9_]+)\)$/", $val, $match))
  88. $val = $this->$match[1];
  89. } else {
  90. $model = depluralize($name);
  91. $match = $model_name;
  92. $opts = array("where" => array(strtolower($match)."_id" => $this->id));
  93. }
  94. return $this->$name = new $model(null, $opts);
  95. }
  96. if (isset($this->$name))
  97. return $this->$name;
  98. }
  99. /**
  100. * Function: __getPlaceholders
  101. * Calls __get with the requested $name, but grabs everything as placeholders.
  102. *
  103. * Parameters:
  104. * $name - Name to call <Model.__get> with.
  105. *
  106. * Returns:
  107. * @mixed@
  108. *
  109. * See Also:
  110. * <Model.__get>
  111. */
  112. public function __getPlaceholders($name) {
  113. $this->__placeholders = true;
  114. $return = $this->__get($name);
  115. unset($this->__placeholders);
  116. return $return;
  117. }
  118. /**
  119. * Function: grab
  120. * Grabs a single model from the database.
  121. *
  122. * Parameters:
  123. * $model - The instantiated model class to pass the object to (e.g. Post).
  124. * $id - The ID of the model to grab. Can be null.
  125. * $options - An array of options, mostly SQL things.
  126. *
  127. * Options:
  128. * select - What to grab from the table. @(modelname)s@ by default.
  129. * from - Which table(s) to grab from? @(modelname)s.*@ by default.
  130. * left_join - A @LEFT JOIN@ associative array. Example: @array("table" => "foo", "where" => "foo = :bar")@
  131. * where - A string or array of conditions. @array("__(modelname)s.id = :id")@ by default.
  132. * params - An array of parameters to pass to PDO. @array(":id" => $id)@ by default.
  133. * group - A string or array of "GROUP BY" conditions.
  134. * order - What to order the SQL result by. @__(modelname)s.id DESC@ by default.
  135. * offset - Offset for SQL query.
  136. * read_from - An array to read from instead of performing another query.
  137. */
  138. protected static function grab($model, $id, $options = array()) {
  139. $model_name = strtolower(get_class($model));
  140. if ($model_name == "visitor")
  141. $model_name = "user";
  142. if (!isset($id) and isset($options["where"]["id"]))
  143. $id = $options["where"]["id"];
  144. $cache = (is_numeric($id) and isset(self::$caches[$model_name][$id])) ?
  145. self::$caches[$model_name][$id] :
  146. ((isset($options["read_from"]["id"]) and isset(self::$caches[$model_name][$options["read_from"]["id"]])) ?
  147. self::$caches[$model_name][$options["read_from"]["id"]] :
  148. (isset(self::$caches[$model_name][serialize($id)]) ?
  149. self::$caches[$model_name][serialize($id)] :
  150. array())) ;
  151. # Is this model already in the cache?
  152. if (!empty($cache)) {
  153. foreach ($cache as $attr => $val)
  154. $model->$attr = $val;
  155. return;
  156. }
  157. fallback($options["select"], "*");
  158. fallback($options["from"], ($model_name == "visitor" ? "users" : pluralize($model_name)));
  159. fallback($options["left_join"], array());
  160. fallback($options["where"], array());
  161. fallback($options["params"], array());
  162. fallback($options["group"], array());
  163. fallback($options["order"], "id DESC");
  164. fallback($options["offset"], null);
  165. fallback($options["read_from"], array());
  166. fallback($options["ignore_dupes"], array());
  167. $options["where"] = (array) $options["where"];
  168. $options["from"] = (array) $options["from"];
  169. $options["select"] = (array) $options["select"];
  170. if (is_numeric($id))
  171. $options["where"]["id"] = $id;
  172. elseif (is_array($id))
  173. $options["where"] = array_merge($options["where"], $id);
  174. $trigger = Trigger::current();
  175. $trigger->filter($options, $model_name."_grab");
  176. $sql = SQL::current();
  177. if (!empty($options["read_from"]))
  178. $read = $options["read_from"];
  179. else {
  180. $query = $sql->select($options["from"],
  181. $options["select"],
  182. $options["where"],
  183. $options["order"],
  184. $options["params"],
  185. null,
  186. $options["offset"],
  187. $options["group"],
  188. $options["left_join"]);
  189. $all = $query->fetchAll();
  190. if (count($all) == 1)
  191. $read = $all[0];
  192. else {
  193. $merged = array();
  194. foreach ($all as $index => $row)
  195. foreach ($row as $column => $val)
  196. $merged[$row["id"]][$column][] = $val;
  197. foreach ($all as $index => &$row)
  198. $row = $merged[$row["id"]];
  199. if (count($all)) {
  200. $keys = array_keys($all);
  201. $read = $all[$keys[0]];
  202. foreach ($read as $name => &$column) {
  203. $column = (!in_array($name, $options["ignore_dupes"]) ?
  204. array_unique($column) :
  205. $column);
  206. $column = (count($column) == 1) ?
  207. $column[0] :
  208. $column ;
  209. }
  210. } else
  211. $read = false;
  212. }
  213. }
  214. if (!count($read) or !$read)
  215. return $model->no_results = true;
  216. else
  217. $model->no_results = false;
  218. foreach ($read as $key => $val)
  219. if (!is_int($key))
  220. $model->$key = $val;
  221. if (isset($query) and isset($query->queryString))
  222. $model->queryString = $query->queryString;
  223. if (isset($model->updated_at))
  224. $model->updated = (!empty($model->updated_at) and $model->updated_at != "0000-00-00 00:00:00");
  225. $clone = clone $model;
  226. self::$caches[$model_name][$read["id"]] = $clone;
  227. if (!is_numeric($id) and !isset($options["read_from"]["id"]) and $id !== null)
  228. self::$caches[$model_name][serialize($id)] = $clone;
  229. }
  230. /**
  231. * Function: search
  232. * Returns an array of model objects that are found by the $options array.
  233. *
  234. * Parameters:
  235. * $options - An array of options, mostly SQL things.
  236. * $options_for_object - An array of options for the instantiation of the model.
  237. *
  238. * Options:
  239. * select - What to grab from the table. @(modelname)s@ by default.
  240. * from - Which table(s) to grab from? @(modelname)s.*@ by default.
  241. * left_join - A @LEFT JOIN@ associative array. Example: @array("table" => "foo", "where" => "foo = :bar")@
  242. * where - A string or array of conditions. @array("__(modelname)s.id = :id")@ by default.
  243. * params - An array of parameters to pass to PDO. @array(":id" => $id)@ by default.
  244. * group - A string or array of "GROUP BY" conditions.
  245. * order - What to order the SQL result by. @__(modelname)s.id DESC@ by default.
  246. * offset - Offset for SQL query.
  247. * limit - Limit for SQL query.
  248. *
  249. * See Also:
  250. * <Model.grab>
  251. */
  252. protected static function search($model, $options = array(), $options_for_object = array()) {
  253. $model_name = strtolower($model);
  254. fallback($options["select"], "*");
  255. fallback($options["from"], pluralize(strtolower($model)));
  256. fallback($options["left_join"], array());
  257. fallback($options["where"], null);
  258. fallback($options["params"], array());
  259. fallback($options["group"], array());
  260. fallback($options["order"], "id DESC");
  261. fallback($options["offset"], null);
  262. fallback($options["limit"], null);
  263. fallback($options["placeholders"], false);
  264. fallback($options["ignore_dupes"], array());
  265. $options["where"] = (array) $options["where"];
  266. $options["from"] = (array) $options["from"];
  267. $options["select"] = (array) $options["select"];
  268. $trigger = Trigger::current();
  269. $trigger->filter($options, pluralize(strtolower($model_name))."_get");
  270. $grab = SQL::current()->select($options["from"],
  271. $options["select"],
  272. $options["where"],
  273. $options["order"],
  274. $options["params"],
  275. $options["limit"],
  276. $options["offset"],
  277. $options["group"],
  278. $options["left_join"])->fetchAll();
  279. $shown_dates = array();
  280. $results = array();
  281. $rows = array();
  282. foreach ($grab as $row)
  283. foreach ($row as $column => $val)
  284. $rows[$row["id"]][$column][] = $val;
  285. foreach ($rows as &$row)
  286. foreach ($row as $name => &$column) {
  287. $column = (!in_array($name, $options["ignore_dupes"]) ?
  288. array_unique($column) :
  289. $column);
  290. $column = (count($column) == 1) ?
  291. $column[0] :
  292. $column ;
  293. }
  294. foreach ($rows as $result) {
  295. if ($options["placeholders"]) {
  296. $results[] = $result;
  297. continue;
  298. }
  299. $options_for_object["read_from"] = $result;
  300. $result = new $model(null, $options_for_object);
  301. if (isset($result->created_at)) {
  302. $pinned = (isset($result->pinned) and $result->pinned);
  303. $shown = in_array(when("m-d-Y", $result->created_at), $shown_dates);
  304. $result->first_of_day = (!$pinned and !$shown and !AJAX);
  305. if (!$pinned and !$shown)
  306. $shown_dates[] = when("m-d-Y", $result->created_at);
  307. }
  308. $results[] = $result;
  309. }
  310. return ($options["placeholders"]) ? array($results, $model_name) : $results ;
  311. }
  312. /**
  313. * Function: delete
  314. * Deletes a given object. Calls the @delete_(model)@ trigger with the objects ID.
  315. *
  316. * Parameters:
  317. * $model - The model name.
  318. * $id - The ID of the object to delete.
  319. */
  320. protected static function destroy($model, $id) {
  321. $model = strtolower($model);
  322. if (Trigger::current()->exists("delete_".$model))
  323. Trigger::current()->call("delete_".$model, new $model($id));
  324. SQL::current()->delete(pluralize($model), array("id" => $id));
  325. }
  326. /**
  327. * Function: deletable
  328. * Checks if the <User> can delete the post.
  329. */
  330. public function deletable($user = null) {
  331. if ($this->no_results)
  332. return false;
  333. $name = strtolower(get_class($this));
  334. fallback($user, Visitor::current());
  335. return $user->group->can("delete_".$name);
  336. }
  337. /**
  338. * Function: editable
  339. * Checks if the <User> can edit the post.
  340. */
  341. public function editable($user = null) {
  342. if ($this->no_results)
  343. return false;
  344. $name = strtolower(get_class($this));
  345. fallback($user, Visitor::current());
  346. return $user->group->can("edit_".$name);
  347. }
  348. /**
  349. * Function: edit_link
  350. * Outputs an edit link for the model, if the visitor's <Group.can> edit_[model].
  351. *
  352. * Parameters:
  353. * $text - The text to show for the link.
  354. * $before - If the link can be shown, show this before it.
  355. * $after - If the link can be shown, show this after it.
  356. * $classes - Extra CSS classes for the link, space-delimited.
  357. */
  358. public function edit_link($text = null, $before = null, $after = null, $classes = "") {
  359. if (!$this->editable())
  360. return false;
  361. fallback($text, __("Edit"));
  362. $name = strtolower(get_class($this));
  363. if (@Feathers::$instances[$this->feather]->disable_ajax_edit)
  364. $classes = empty($classes) ? "no_ajax" : $classes." no_ajax" ;
  365. echo $before.'<a href="'.Config::current()->chyrp_url.'/admin/?action=edit_'.$name.'&amp;id='.$this->id.'" title="Edit" class="'.($classes ? $classes." " : '').$name.'_edit_link edit_link" id="'.$name.'_edit_'.$this->id.'">'.$text.'</a>'.$after;
  366. }
  367. /**
  368. * Function: delete_link
  369. * Outputs a delete link for the post, if the <User.can> delete_[model].
  370. *
  371. * Parameters:
  372. * $text - The text to show for the link.
  373. * $before - If the link can be shown, show this before it.
  374. * $after - If the link can be shown, show this after it.
  375. * $classes - Extra CSS classes for the link, space-delimited.
  376. */
  377. public function delete_link($text = null, $before = null, $after = null, $classes = "") {
  378. if (!$this->deletable())
  379. return false;
  380. fallback($text, __("Delete"));
  381. $name = strtolower(get_class($this));
  382. echo $before.'<a href="'.Config::current()->chyrp_url.'/admin/?action=delete_'.$name.'&amp;id='.$this->id.'" title="Delete" class="'.($classes ? $classes." " : '').$name.'_delete_link delete_link" id="'.$name.'_delete_'.$this->id.'">'.$text.'</a>'.$after;
  383. }
  384. }