hooks[$hook][$entity_type] as $key => $hook_function) {
if ($hook_function == $function) {
unset($CONFIG->hooks[$hook][$entity_type][$key]);
}
}
}
/**
*
* Roles and permissions section
*
* */
// Serve all possible roles as an array
function getAvailableRoles() {
$roles = array(
/*translation:No role*/
elgg_echo('koolielu:user_role_none') => 'none',
/*translation:Moderator*/
elgg_echo('koolielu:user_role_moderator') => 'moderator',
/*translation:Editor*/
elgg_echo('koolielu:user_role_editor') => 'editor'
);
return $roles;
}
// Return true if user is Editor or has subject section Moderator role
function isModerator($subject_ids=null) {
if (!isloggedin()) {
return false;
}
if (isEditor()) {
return true;
}
$user = get_loggedin_user();
if ($user->roles != "moderator") {
return false;
}
if ($user->roles == "moderator" && is_null($subject_ids)) {
return true;
}
$user_subjects = $user->subjects;
// In case of string >>> make an array out of it
if (!is_array($user_subjects)) {
$user_subjects = array($user_subjects);
}
if (!is_array($subject_ids)) {
if (in_array($subject_ids, $user_subjects)) {
return true;
}
} else {
foreach($user_subjects as $user_subject) {
if (in_array($user_subject, $subject_ids)) {
return true;
}
}
}
return false;
}
// Return true if user is Editor or has Tools moderator role
function isToolsModerator() {
if (!isloggedin()) {
return false;
}
if (isEditor()) {
return true;
}
$user = get_loggedin_user();
if ($user->roles != "moderator") {
return false;
}
if (($user->roles == "moderator") && ($user->can_moderate_tools == 'true')) {
return true;
}
return false;
}
// Return true if user is Editor or has External group moderator role (used only to add news external groups)
function isExternalGroupModerator() {
if (!isloggedin()) {
return false;
}
if (isEditor()) {
return true;
}
$user = get_loggedin_user();
if ($user->roles != "moderator") {
return false;
}
if (($user->roles == "moderator") && ($user->can_add_external_groups == 'true')) {
return true;
}
return false;
}
// Return true if user is Admin or has Editor role
function isEditor() {
if (!isloggedin()) {
return false;
}
if (isadminloggedin()) {
return true;
}
$user = get_loggedin_user();
if ($user->roles == "editor") {
return true;
}
return false;
}
// Custom gatekeeper functions for our own roles
function moderator_gatekeeper($subject_id=null) {
if (!isModerator($subject_id)) {
$_SESSION['last_forward_from'] = current_page_url();
forward();
}
}
function editor_gatekeeper() {
if (!isEditor()) {
$_SESSION['last_forward_from'] = current_page_url();
forward();
}
}
// This works for any Moderator or Editor
function editor_or_moderator_gatekeeper() {
if (!(isEditor() || isModerator($subject_id=null))) {
$_SESSION['last_forward_from'] = current_page_url();
forward();
}
}
// This works for any ToolsModerators or Editor
function editor_or_toolsmoderator_gatekeeper() {
if (!(isEditor() || isToolsModerator())) {
$_SESSION['last_forward_from'] = current_page_url();
forward();
}
}
function editor_or_externalgroupsmoderator_gatekeeper() {
if (!(isEditor() || isExternalGroupModerator())) {
$_SESSION['last_forward_from'] = current_page_url();
forward();
}
}
// Prerendered searches for Editors and Moderators
function getAllEditors() {
$res = get_entities_from_metadata('roles', 'editor', 'user', "", 0, 9999);
return $res;
}
function getAllModerators($subject_ids=false) {
$res = array();
if ($subject_ids) {
if (is_array($subject_ids)) {
foreach($subject_ids as $subject_id) {
$moderators = get_entities_from_metadata_multi(array("roles" => "moderator", "subjects" => $subject_id), "user", "", 0, 9999);
foreach ( $moderators as $mod ) {
$res[$mod->getGUID()] = $mod;
}
}
$res = array_values($res);
} else {
$res = get_entities_from_metadata_multi(array("roles" => "moderator", "subjects" => $subject_ids), "user", "", 0, 9999);
}
} else {
$res = get_entities_from_metadata("roles", "moderator", "user", "", 0, 9999);
}
return $res;
}
/**
*
* Categories, curriculum, logos and subject management
*
* */
function koolielu_add_category($title) {
global $CONFIG;
// adds category into the table
$previous_data = get_data("SELECT * from {$CONFIG->dbprefix}koolielu_categories where parent is NULL");
$pos = 1;
if (is_array($previous_data))
$pos = count($previous_data) + 1;
return insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_categories (title, pos) VALUES ('$title', $pos)");
}
function koolielu_edit_category($id, $title, $locked) {
global $CONFIG;
if (!$locked)
$locked = 0;
return update_data("UPDATE {$CONFIG->dbprefix}koolielu_categories SET title = '$title', locked= $locked WHERE guid = $id");
}
function koolielu_update_category_position($id, $pos) {
global $CONFIG;
return update_data("UPDATE {$CONFIG->dbprefix}koolielu_categories SET pos = $pos WHERE guid = $id");
}
function koolielu_add_subcategory($title, $parent) {
global $CONFIG;
$previous_data = get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_categories WHERE parent = $parent");
$pos = 1;
if (is_array($previous_data))
$pos = count($previous_data) + 1;
return insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_categories (title, parent, pos) VALUES ('$title', $parent, $pos)");
}
function koolielu_delete_category($guid) {
global $CONFIG;
$guid = mysql_real_escape_string($guid);
// deleted existing category
return delete_data("DELETE from {$CONFIG->dbprefix}koolielu_categories where guid=$guid;");
}
function get_koolielu_category($guid) {
global $CONFIG;
// returns category
$guid = mysql_real_escape_string($guid);
return get_data_row("SELECT * from {$CONFIG->dbprefix}koolielu_categories where guid='$guid'");
}
function get_koolielu_categories($guids_only = false) {
global $CONFIG;
$data = get_data("SELECT * from {$CONFIG->dbprefix}koolielu_categories where parent is NULL and locked = 0 ORDER BY pos");
if ($guids_only) {
$returned = array();
foreach ($data as $cat) {
array_push($returned, $cat->guid);
}
return $returned;
}
return $data;
}
function get_koolielu_main_categories() {
global $CONFIG;
return get_data("SELECT * from {$CONFIG->dbprefix}koolielu_categories where parent is NULL ORDER BY pos");
}
function get_koolielu_subcategories($parent_guid='') {
global $CONFIG;
if ($parent_guid) {
$parent_guid = mysql_real_escape_string($parent_guid);
return get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_categories WHERE parent = {$parent_guid} and locked = 0 ORDER BY pos");
}
return get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_categories WHERE parent is not NULL ORDER BY pos");
}
/**
* Returns array of selectable categories (usable for category selection)
* eg. array(1 => 'Bioloogia', 22 => 'Geograafia');
* */
function get_selectable_categories($all = false) {
global $CONFIG;
$categories = get_koolielu_categories();
$returned = array();
foreach ($categories as $category) {
if ($all) {
$returned[$category->guid] = $category->title;
}
$subcategories = get_koolielu_subcategories($category->guid);
foreach ($subcategories as $subcategory) {
$returned[$subcategory->guid] = $subcategory->title;
}
}
return $returned;
}
function _is_curriculum_subject($id, $return_title=false) {
$all_subjects = getSubjects();
if (array_key_exists($id, $all_subjects)) {
if ($return_title)
return $all_subjects[$id];
else
return true;
}
return false;
}
/**
* Returns an list of subjects
* eg. array(1 => 'eesti keel', 123 => 'vene keel', ...)
* */
function getSubjectsOnDefault() {
global $CONFIG;
//$data = get_data("SELECT * from {$CONFIG->dbprefix}curriculum where cid=".getCurrentCurriculumID()." and isSubject=1 ORDER BY title");
$data = get_data("SELECT DISTINCT eid, title FROM {$CONFIG->dbprefix}subjectmap WHERE cid=".getCurrentCurriculumID()." ORDER BY title");
$subjects = array();
foreach($data as $elem) {
$subjects[$elem->eid] = $elem->title;
}
return $subjects;
}
function getSubjects() {
global $CONFIG;
//$data = get_data("SELECT * from {$CONFIG->dbprefix}curriculum where cid=".getCurrentCurriculumID()." and isSubject=1 ORDER BY title");
$data = get_data("SELECT DISTINCT id, title FROM {$CONFIG->dbprefix}subjectmap ORDER BY title");
$subjects = array();
foreach($data as $elem) {
$subjects[$elem->id] = $elem->title;
}
return $subjects;
}
function getSubjectID($eid) {
global $CONFIG;
if (!is_numeric($eid))
return null;
$data = get_data("SELECT id FROM {$CONFIG->dbprefix}subjectmap WHERE eid=".$eid." ORDER BY cid");
return $data[0]->id;
}
function getSubjectOnDefault($id) {
global $CONFIG;
$data = get_data("SELECT eid FROM {$CONFIG->dbprefix}subjectmap WHERE cid=".getCurrentCurriculumID()." and id=".$id);
return $data[0]->eid;
}
function getSubject($id) {
if (!is_numeric($id))
return null;
global $CONFIG;
$data = get_data("SELECT * FROM {$CONFIG->dbprefix}subjectmap WHERE eid=".$id." ORDER BY cid");
return $data[0];
}
/**
* Returns list of curriculum objects
* */
function getCurriculum() {
global $CONFIG;
return get_data("SELECT * from {$CONFIG->dbprefix}curriculum where cid=".getCurrentCurriculumID()." ORDER BY eid");
}
function getCurriculumSubject($id, $param=false) {
global $CONFIG;
if ( !$id ) return false;
$wh = "= ".$id;
if ( is_array($id) ) $wh = "IN (".join(array_filter($id), ",").")";
$pm = "*";
if ($param) $pm = $param;
return get_data("SELECT ".$pm." from {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid ".$wh);
}
function getCurriculumDescription($id) {
global $CONFIG;
$id = mysql_real_escape_string($id);
$r = get_data("SELECT description FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid={$id}");
return nl2br($r[0]->description);
}
function getCurriculumChildren($id=null) {
global $CONFIG;
if ( is_null($id) ) {
$subs = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and level=1 ORDER BY title");
} else {
$id = mysql_real_escape_string($id);
//print "SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE level=(SELECT level FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id)+1 AND eid>(SELECT start FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) AND eid<(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) ORDER BY eid";
$subs = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE level=(SELECT level FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id)+1 AND eid>(SELECT start FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) AND eid<(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) ORDER BY eid");
}
return $subs;
}
function getAllCurriculumChildren($id=null) {
global $CONFIG;
if ( is_null($id) ) {
$subs = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and level=1 ORDER BY title");
} else {
$id = mysql_real_escape_string($id);
$subs = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE level>(SELECT level FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) AND eid>(SELECT start FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) AND eid<(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid=$id) ORDER BY eid");
}
return $subs;
}
function getCurriculumTree($id) {
global $CONFIG;
$id = mysql_real_escape_string($id);
if (!is_numeric($id))
die('dead');
$elems = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and (eid={$id} OR (start<={$id} AND end>=(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid={$id}))) ORDER BY level");
return $elems;
}
function getCurriculumTreeNS($ns, $id) {
global $CONFIG;
if (!is_numeric($id))
die('dead');
$cid = getCurriculumIDFor($ns);
$id = mysql_real_escape_string($id);
//print "SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE cid=".$cid." and (eid={$id} OR (start<={$id} AND end>=(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".$cid." and eid={$id}))) ORDER BY level";
$elems = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE cid=".$cid." and (eid={$id} OR (start<={$id} AND end>=(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".$cid." and eid={$id}))) ORDER BY level");
return $elems;
}
/**
* get curriculum siblings. eg. providing first level curriculum eid.
* returns an array of all siblings. with id, title, level
* eg. array(12, 'title', 2);
* */
function getCurriculumSiblings($id, $level) {
global $CONFIG;
$id = mysql_real_escape_string($id);
$level = mysql_real_escape_string($level);
$res = array();
$elems = get_data("SELECT * FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and start>={$id} and end<=(SELECT end FROM {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and eid={$id}) AND level>{$level} ORDER BY eid");
foreach ( $elems as $elem ) {
$id = $elem->eid;
$title = $elem->title;
$level = $elem->level;
$res[] = array($id, $title, $level);
}
return $res;
}
/**
* returns level 1 eid
* */
function getCurriculumMainSubject($id) {
global $CONFIG;
$id = mysql_real_escape_string($id);
$elem = get_data("SELECT * from {$CONFIG->dbprefix}curriculum WHERE cid=".getCurrentCurriculumID()." and start<={$id} and end>={$id} AND level=1");
return $elem[0]->eid;
}
/**
* returns level 1 eid from NS
* */
function getCurriculumMainSubjectNS($ns, $id) {
global $CONFIG;
$id = mysql_real_escape_string($id);
$cid = getCurriculumIDFor($ns);
$elem = get_data("SELECT * from {$CONFIG->dbprefix}curriculum WHERE cid=".$cid." and start<={$id} and end>={$id} AND level=1");
return $elem[0]->eid;
}
// Helper functions for logos handling
function koolielu_add_logo($address, $placeid, $pageid, $userid, $url, $alt_text) {
global $CONFIG;
$previous_data = get_data("SELECT * from {$CONFIG->dbprefix}koolielu_logos where placeid = '$placeid' and pageid = '$pageid'");
$position = 1;
if (is_array($previous_data))
$position = count($previous_data) + 1;
return insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_logos (address, placeid, position, pageid, userid, url, alt) VALUES ('$address', '$placeid', $position, '$pageid', '$userid', '$url', '$alt_text')");
}
function koolielu_update_logo_position($id, $position) {
global $CONFIG;
return update_data("UPDATE {$CONFIG->dbprefix}koolielu_logos SET position = '$position' WHERE ID = '$id'");
}
function koolielu_delete_logo($id){
global $CONFIG;
// Delete database entry
return delete_data("DELETE from {$CONFIG->dbprefix}koolielu_logos where ID = '$id'");
}
function get_koolielu_logo($id) {
global $CONFIG;
$id = mysql_real_escape_string($id);
return get_data("SELECT * from {$CONFIG->dbprefix}koolielu_logos where ID = '$id'");
}
function get_koolielu_logos($placeid, $pageid) {
global $CONFIG;
$placeid = mysql_real_escape_string($placeid);
$pageid = mysql_real_escape_string($pageid);
$data = get_data("SELECT * from {$CONFIG->dbprefix}koolielu_logos where placeid = '$placeid' and pageid = '$pageid' ORDER BY position");
return $data;
}
function reposition_koolielu_logos($placeid, $pageid) {
$placeid = mysql_real_escape_string($placeid);
$pageid = mysql_real_escape_string($pageid);
$logos = get_koolielu_logos($placeid, $pageid);
$position = 1;
foreach ($logos as $logo) {
koolielu_update_logo_position($logo->ID, $position);
$position++;
}
}
/**
*
* Subcomments
*
**/
function koolielu_get_comment_subcomments($comment_id, $count = false) {
global $CONFIG;
$comment_id = (int)$comment_id;
if ($count) {
$query = "SELECT COUNT(id) as total FROM {$CONFIG->dbprefix}koolielu_subcomments WHERE comment_id = {$comment_id}";
$total = get_data_row($query);
return $total->total;
} else {
$query = "SELECT * FROM {$CONFIG->dbprefix}koolielu_subcomments WHERE comment_id = {$comment_id} ORDER BY time_created ASC";
return get_data($query);
}
}
function koolielu_get_entity_subcomments($entity_guid, $count = false) {
global $CONFIG;
$entity_guid = (int)$entity_guid;
if ($count) {
$query = "SELECT COUNT(id) as total FROM {$CONFIG->dbprefix}koolielu_subcomments WHERE entity_guid = {$entity_guid}";
$total = get_data_row($query);
return $total->total;
} else {
$query = "SELECT * FROM {$CONFIG->dbprefix}koolielu_subcomments WHERE entity_guid = {$entity_guid}";
return get_data($query);
}
}
function koolielu_get_subcomment($id) {
global $CONFIG;
$id = (int)$id;
$query = "SELECT * FROM {$CONFIG->dbprefix}koolielu_subcomments WHERE id = {$id}";
return get_data_row($query);
}
function koolielu_can_edit_subcomment($id) {
if (!isloggedin()) {
return false;
}
if (isadminloggedin()) {
return true;
}
// Editor can edit
if (isEditor()) {
return true;
}
$subcomment = koolielu_get_subcomment($id);
if ($subcomment) {
// Owner can edit
if (get_loggedin_userid() == $subcomment->owner_guid) {
return true;
}
// Anyone who can edit entity, can edit
$entity = get_entity($subcomment->entity_guid);
if ($entity instanceof ElggEntity) {
if ($entity->canEdit()) {
return true;
}
}
}
return false;
}
/**
*
* Polls management
*
**/
function koolielu_add_poll($question, $variants_array) {
global $CONFIG;
$previous_data = get_data("SELECT * from {$CONFIG->dbprefix}koolielu_polls");
$pos = 1;
if (is_array($previous_data))
$pos = count($previous_data) + 1;
// adds poll into the table
insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_polls (ID, questiontext) VALUES ($pos, '$question')");
$var_pos = 0;
foreach ($variants_array as $var) {
$var = trim($var);
if ($var != '') {
$var_pos = $var_pos + 1;
insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_polls_variants (poll_id, variant, pos) VALUES ('$pos', '$var', '$var_pos') ");
}
}
}
function koolielu_edit_poll($poll_id, $question, $variants_array) {
global $CONFIG;
update_data("UPDATE {$CONFIG->dbprefix}koolielu_polls set questiontext='{$question}' WHERE ID={$poll_id}");
delete_data("DELETE FROM {$CONFIG->dbprefix}koolielu_polls_variants WHERE poll_id={$poll_id}");
$pos = 0;
foreach ($variants_array as $var) {
$var = trim($var);
if ($var != '') {
$pos = $pos + 1;
insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_polls_variants (poll_id, variant, pos) VALUES ($poll_id, '$var', $pos) ");
}
}
}
function koolielu_activate_poll($poll_id) {
global $CONFIG;
$poll_id = mysql_real_escape_string($poll_id);
$current_time = time();
update_data("UPDATE {$CONFIG->dbprefix}koolielu_polls set isActive=0 where isActive=1");
update_data("UPDATE {$CONFIG->dbprefix}koolielu_polls set isActive=1 where ID=$poll_id");
update_data("UPDATE {$CONFIG->dbprefix}koolielu_polls set time=current_timestamp where ID=$poll_id");
}
function koolielu_deactivate_poll($poll_id) {
global $CONFIG;
$poll_id = mysql_real_escape_string($poll_id);
update_data("UPDATE {$CONFIG->dbprefix}koolielu_polls set isActive=0 where ID=$poll_id");
}
function koolielu_get_poll($poll_id) {
global $CONFIG;
$poll_id = mysql_real_escape_string($poll_id);
return get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls WHERE ID=$poll_id");
}
function koolielu_update_poll($poll_id) {
global $CONFIG;
$poll_id = mysql_real_escape_string($poll_id);
update_data("UPDATE {$CONFIG->dbprefix}koolielu_polls set isActive=1 where ID=$poll_id");
}
function get_all_koolielu_polls() {
global $CONFIG;
return get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls ORDER BY time DESC");
}
function get_poll_var_percents($poll_id) {
global $CONFIG;
$poll_id = mysql_real_escape_string($poll_id);
if ($poll_id) {
$active_poll = get_data_row("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls WHERE ID=$poll_id");
} else {
$active_poll = get_data_row("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls WHERE isActive=1");
}
$poll_id = $active_poll->ID;
$poll_variants = get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls_variants WHERE poll_id = $poll_id ORDER BY pos");
$variants = array();
$all_poll_answers = get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls_answers WHERE poll_id = $poll_id");
$all_answers_count = count($all_poll_answers);
foreach($poll_variants as $var) {
$var_answers = get_data("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls_answers WHERE poll_id = $poll_id AND answer_id = {$var->ID}");
if (is_array($var_answers)) {
$var_answers_count = count($var_answers);
$var_percent = ($var_answers_count / $all_answers_count) * 100;
$var_percent = round($var_percent);
} else {
$var_percent = 0;
$var_answers_count = 0;
}
$var_results = array();
$var_results["percent"] = $var_percent;
$var_results["answer_count"] = $var_answers_count;
$variants[$var->variant] = $var_results;
}
return $variants;
}
function poll_results_html($poll_id=NULL) {
global $CONFIG;
if ($poll_id) {
$poll_id = mysql_real_escape_string($poll_id);
$active_poll = get_data_row("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls WHERE ID=$poll_id");
} else {
$active_poll = get_data_row("SELECT * FROM {$CONFIG->dbprefix}koolielu_polls WHERE isActive=1");
}
$var_percents = get_poll_var_percents($active_poll->ID);
$var_divs = "";
$var_divs .= "
" . $active_poll->questiontext . "
";
foreach ($var_percents as $var => $var_results) {
$var_divs .= "". $var ."
";
$percent = $var_results["percent"];
$var_divs .= "
";
$var_divs .= "" . $percent . "% ";
$var_divs .= "(" . $var_results["answer_count"]. ")
";
}
return $var_divs;
}
/**
*
* Object management and system messages
*
*/
// Add information about decision about object moderation request result for generation statistics
function koolielu_add_review_decision($user_guid, $resolution, $subtype, $object_guid) {
global $CONFIG;
// Add information about moderation decision
// user_guid >>> reviewer
// resolution can be >>> accept ot decline
// subtype >>> object subtype name
// object_guid >>> reviewable object id (in case of decline choice >>> omited and set to NULL
if ($object_guid) {
return insert_data("INSERT into {$CONFIG->dbprefix}koolielu_moderation (user_guid, resolution, subtype, object_guid) values ($user_guid, '$resolution', '$subtype', $object_guid)");
} else {
return insert_data("INSERT into {$CONFIG->dbprefix}koolielu_moderation (user_guid, resolution, subtype) values ($user_guid, '$resolution', '$subtype')");
}
}
// recipient >>> GUID, messages >>> array >>> title and description, notification >>> not set if not provided
function send_system_message($recipient, $messages, $notification=false) {
// using function from messages plugin
$success = messages_send($messages['title'], $messages['description'], $recipient, 0, 0, false, false);
if ($success) {
// Message sent
if ($notification) {
system_message($notification);
}
return true;
}
return false;
}
// object >>> reviewed object, messages >>> array >>> title and description, recipient >>> GUID
function accept_object_review($object, $messages, $recipient) {
$object->access_id = 2;// Set object to public
$object->save();//Saving object
$object->approved = 1;// Object approved
// Deal with approved elements count by subtype
koolielu_add_review_decision($_SESSION['user']->getGUID(), 'accept', $object->getSubtype(), $object->getGUID());
$res = send_system_message($recipient, $messages, false);
if ($res) {
//Message sent
/*translation:Approved.*/
system_message(elgg_echo('koolielu:message_approved'));
return true;
}
return false;
}
// object >>> reviewed object, messages >>> array >>> title and description, recipient >>> GUID
function reject_object_review($object, $messages, $recipient) {
// Deal with disapproved elements count by subtype
koolielu_add_review_decision($_SESSION['user']->getGUID(), 'decline', $object->getSubtype());
$res = send_system_message($recipient, $messages, false);
if ($res) {
// Message sent
/*translation:Disapproved.*/
system_message(elgg_echo('koolielu:message_disapproved'));
// Delete object
$object->delete();
/*translation:Deleted.*/
system_message(elgg_echo('koolielu:message_deleted'));
return true;
}
return false;
}
/**
*
* Search functions
*
**/
function get_entities_from_metadata_and_subtypes($meta_array, $entity_type = "", $entity_subtypes = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false)
{
global $CONFIG;
//if (!is_array($meta_array) || sizeof($meta_array) == 0) {
// return false;
//}
$entity_type = sanitise_string($entity_type);
$subtypes = array();
if (is_array($entity_subtypes) && sizeof($entity_subtypes) > 0) {
foreach($entity_subtypes as $subtype) {
$subtype_id = get_subtype_id($entity_type, $subtype);
array_push($subtypes, $subtype_id);
}
}
$limit = (int)$limit;
$offset = (int)$offset;
if ($order_by == "") $order_by = "e.time_created desc";
$order_by = sanitise_string($order_by);
$site_guid = (int) $site_guid;
if ((is_array($owner_guid) && (count($owner_guid)))) {
foreach($owner_guid as $key => $guid) {
$owner_guid[$key] = (int) $guid;
}
} else {
$owner_guid = (int) $owner_guid;
}
if ($site_guid == 0)
$site_guid = $CONFIG->site_guid;
$where = array();
$mindex = 1;
$join = "";
foreach($meta_array as $meta_name => $meta_value) {
$meta_n = get_metastring_id($meta_name);
// in case value is array, find entities which metadata value is in that array
if (is_array($meta_value)) {
$meta_v = array();
foreach($meta_value as $mval) {
$mval = get_metastring_id($mval);
$meta_v[] = "'".$mval."'";
}
} else {
$meta_v = get_metastring_id($meta_value);
}
$join .= " JOIN {$CONFIG->dbprefix}metadata m{$mindex} on e.guid = m{$mindex}.entity_guid ";
if ($meta_name!="")
$where[] = "m{$mindex}.name_id='$meta_n'";
if ($meta_value!="")
if (is_array($meta_v) && sizeof($meta_v) > 0) {
$where[] = "m{$mindex}.value_id in (".implode(",",$meta_v).")";
} else {
$where[] = "m{$mindex}.value_id='$meta_v'";
}
$mindex++;
}
if ($entity_type!="")
$where[] = "e.type = '$entity_type'";
if (is_array($subtypes) && sizeof($subtypes) > 0)
$where[] = "e.subtype in (".implode(",",$subtypes).")";
if ($site_guid > 0)
$where[] = "e.site_guid = {$site_guid}";
if (is_array($owner_guid)) {
$where[] = "e.container_guid in (".implode(",",$owner_guid).")";
} else if ($owner_guid > 0)
$where[] = "e.container_guid = {$owner_guid}";
if (!$count) {
$query = "SELECT distinct e.* ";
} else {
$query = "SELECT count(distinct e.guid) as total ";
}
$query .= "from {$CONFIG->dbprefix}entities e {$join} where";
foreach ($where as $w)
$query .= " $w and ";
$query .= get_access_sql_suffix("e"); // Add access controls
$query .= ' and ' . get_access_sql_suffix("e"); // Add access controls
if (!$count) {
$query .= " order by $order_by limit $offset, $limit"; // Add order and limit
return get_data($query, "entity_row_to_elggstar");
} else {
if ($row = get_data_row($query))
return $row->total;
}
return false;
}
function list_entities_from_metadata_and_subtypes($meta_array, $entity_type = "", $entity_subtypes = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true, $order_by = "") {
$offset = (int) get_input('offset');
$limit = (int) $limit;
$count = get_entities_from_metadata_and_subtypes($meta_array, $entity_type, $entity_subtypes, $owner_guid, $limit, $offset, "", 0, true);
$entities = get_entities_from_metadata_and_subtypes($meta_array, $entity_type, $entity_subtypes, $owner_guid, $limit, $offset, $order_by, 0, false);
return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination);
}
/**
* Filesystem data handling
**/
// Returns system path to Koolielu data folder
function getKeDataPath() {
global $CONFIG;
$path = $CONFIG->path . "ke_data/";
return $path;
}
// Return system data path for RSS cache
function getRssCacheLocation() {
return getKeDataPath() . "rss_cache/";
}
// Returnr system data path for images storage
function getKeImagesDataPath($owner_guid) {
if (!is_dir(getKeDataPath() . "images/" . $owner_guid . "/")) {
mkdir(getKeDataPath() . "images/" . $owner_guid . "/", 0755);
}
return getKeDataPath() . "images/" . $owner_guid . "/" ;
}
// Returns true if file exists
function getImageFileExists($name, $owner_guid) {
if (file_exists(getKeImagesDataPath($owner_guid) . $name)) {
return true;
}
return false;
}
// Returns image file from Koolielu data folder
function getImageFile($name, $owner_guid) {
if (!$handle = fopen(getKeImagesDataPath($owner_guid) . $name, "rb")) {
return false;
}
$contents = fread($handle, filesize(getKeImagesDataPath($owner_guid) . $name));
fclose($handle);
return $contents;
}
// Serv url to image, using the name
function getImageFileURL($name, $owner_guid, $add_timestamp=true) {
global $CONFIG;
$url = $CONFIG->url . "ke_data/images/" . $owner_guid . "/" . $name;
if ($add_timestamp) {
$url .= '?timestamp=' . time();
}
return $url;
}
// Saves image file into Koolielu data folder
function saveImageFile($name, $data, $owner_guid) {
if (!$handle = fopen(getKeImagesDataPath($owner_guid) . $name, "wb")) {
return false;
}
if (fwrite($handle, $data) === FALSE) {
return false;
}
fclose($handle);
return true;
}
// Deteles image file from Koolielu data folder
function deleteImageFile($name, $owner_guid) {
//TODO ADD TRY - EXCEPT. NOT TO GET WARNINGS IN CASE IMAGES DO NOT EXIST
if(unlink(getKeImagesDataPath($owner_guid) . $name) === FALSE) {
return false;
}
return true;
}
/**
* All kind of helpers
* */
// Returns array with supported image formats
function getSupportedImageFormats() {
return array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
}
function saveKeObjectImages($input_name, $entity_guid, $owner_guid) {
// save original
$original_image = get_uploaded_file($input_name);
$original = saveImageFile($entity_guid . '.original', $original_image, $owner_guid);
if (!$original) {
/*translation:Original image could not be saved.*/
register_error(elgg_echo('koolielu:error_original_image_not_saved'));
}
// save resized image
$small_image = get_resized_image_from_uploaded_file($input_name, 150, 150, false);
$small = saveImageFile("small_" . $entity_guid . ".jpg", $small_image, $owner_guid);
if (!$small) {
/*translation:Resized image could not be saved.*/
register_error(elgg_echo("koolielu:error_resized_image_not_saved"));
}
// save listing image
$listing_image = get_resized_image_from_uploaded_file($input_name, 40, 40, false);
$listing = saveImageFile("listing_" . $entity_guid . ".jpg", $listing_image, $owner_guid);
if (!$listing) {
/*translation:Resized image could not be saved.*/
register_error(elgg_echo("koolielu:error_resized_image_not_saved"));
}
}
// Deleted both .original and small_GUID.jpg files
function deleteKeObjectImages($guid, $owner_guid) {
deleteImageFile($guid . ".original", $owner_guid);
deleteImageFile("small_" . $guid . ".jpg", $owner_guid);
deleteImageFile("listing_" . $guid . ".jpg", $owner_guid);
}
function get_user_ip_address() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
function getDayCalendarEvents($date, $filters=array()) {
// Date should be provided in a form of timestamp
global $CONFIG;
$date = mysql_real_escape_string($date);
$cal_event_query = "SELECT * FROM {$CONFIG->dbprefix}koolielu_calendar_objects ";
$cal_event_query .= "LEFT JOIN {$CONFIG->dbprefix}koolielu_calendar_subject_refs ON {$CONFIG->dbprefix}koolielu_calendar_objects.guid={$CONFIG->dbprefix}koolielu_calendar_subject_refs.cal_object_id WHERE ";
// approved
$cal_event_query .= "approved ";
//date
$cal_event_query .= "AND time1_begin AND time1_end AND time1_begin<='".$date."' AND time1_end>='".$date."' ";
$cal_event_query .= "AND (!time2_end OR time2_end>='".time()."') ";
foreach ($filters as $fi => $fiva) { // filters
if($fi=="subjects") {
$subs = array();
foreach ($fiva as $subject) {
$subject = mysql_real_escape_string($subject);
$subs []= "subject_id='".$subject."' ";
}
$cal_event_query .= "AND (".join(" OR ", $subs).") ";
}
}
$cal_event_query .= "GROUP BY guid ORDER BY time1_begin DESC";
//var_dump($cal_event_query);
$res = get_data($cal_event_query);
$results = array();
foreach ($res as $r) {
$s_obj = get_entity($r->guid);
if ($s_obj) { // if getting entity fails
$results []= $s_obj;
}
}
return $results;
}
function getPeriodCalendarEvents($beginning, $end, $filters = array()) {
// Dates should be provided in a form of timestamp
global $CONFIG;
$beginning = mysql_real_escape_string($beginning);
$end = mysql_real_escape_string($end);
$cal_event_query = "SELECT * FROM {$CONFIG->dbprefix}koolielu_calendar_objects ";
$cal_event_query .= "LEFT JOIN {$CONFIG->dbprefix}koolielu_calendar_subject_refs ON {$CONFIG->dbprefix}koolielu_calendar_objects.guid={$CONFIG->dbprefix}koolielu_calendar_subject_refs.cal_object_id WHERE ";
// approved
$cal_event_query .= "approved ";
//date
$cal_event_query .= "AND time1_begin AND time1_end ";
$cal_event_query .= "AND ((time1_begin<='".$beginning."' AND time1_end>='".$end."') ";
$cal_event_query .= "OR (time1_begin<='".$beginning."' AND time1_end>='".$beginning."' AND time1_end<='".$end."') ";
$cal_event_query .= "OR (time1_begin>='".$beginning."' AND time1_begin<='".$end."' AND time1_end>='".$end."') ";
$cal_event_query .= "OR (time1_begin>='".$beginning."' AND time1_begin<='".$end."' AND time1_end>='".$beginning."' AND time1_end<='".$end."')) ";
$cal_event_query .= "AND (!time2_end OR time2_end>='".time()."') ";
foreach ($filters as $fi => $fiva) { // filters
if($fi=="subjects") {
$subs = array();
foreach ($fiva as $subject) {
$subject = mysql_real_escape_string($subject);
$subs []= "subject_id='".$subject."' ";
}
$cal_event_query .= "AND (".join(" OR ", $subs).") ";
}
}
$cal_event_query .= "GROUP BY guid ORDER BY time1_begin ASC";
//var_dump($cal_event_query);
$res = get_data($cal_event_query);
$results = array();
foreach ($res as $r) {
$s_obj = get_entity($r->guid);
if ($s_obj) { // if getting entity fails
$results []= $s_obj;
}
}
return $results;
}
// Shortens text and strips all teh tags
function shortenText($text, $max_length) {
// Let us strip tags at first
$text = strip_tags($text);
// If the text length is smaller than we need, just return the text
if (strlen($text)<=$max_length)
return $text;
// Shorten the text
$text = $text."";
$text = substr($text, 0, $max_length);
$text = substr($text, 0, strrpos($text, ' '));
$text = $text."...";
return $text;
}
// Shorten one line of text or one word
function dumbWordShorten($text, $max_length) {
if (strlen($text)<=$max_length)
return $text;
// Shorten
return substr($text, 0, $max_length-3) . "...";
}
// Convert date format into the timestamp
function dateIntoTimestamp($date) {
// If for some reason timestamp is provided, just do nothing
if ($date > 86400)
return $date;
$replacables = array(".", " ", "/", ",");
$date = str_replace($replacables, "-", $date);
return strtotime($date);
}
// If provided timestamp is empty, function will return that
function timestampIntoDate($timestamp) {
if (empty($timestamp))
return $timestamp;
return date("d.m.Y", $timestamp);
}
// Serve an array of options for profile
function getKeProfileRoles() {
return array(
/*translation:Teacher*/
"teacher" => elgg_echo("koolielu:selectable_role_teacher"),
/*translation:Principal*/
"principal" => elgg_echo("koolielu:selectable_role_principal"),
/*translation:Interest manager*/
"interestmanager" => elgg_echo("koolielu:selectable_role_interestmanager"),
/*translation:Scout master*/
"scoutmaster" => elgg_echo("koolielu:selectable_role_scoutmaster"),
/*translation:Parent*/
"parent" => elgg_echo("koolielu:selectable_role_parent"),
/*translation:Student*/
"student" => elgg_echo("koolielu:selectable_role_student"),
/*translation:Other*/
"other" => elgg_echo("koolielu:selectable_role_other")
);
}
// Server translated role name for role id
function getRoleNameFromID($id) {
$data = array(
/*translation:Teacher*/
"teacher" => elgg_echo("koolielu:selectable_role_teacher"),
/*translation:Principal*/
"principal" => elgg_echo("koolielu:selectable_role_principal"),
/*translation:Interest manager*/
"interestmanager" => elgg_echo("koolielu:selectable_role_interestmanager"),
/*translation:Scout master*/
"scoutmaster" => elgg_echo("koolielu:selectable_role_scoutmaster"),
/*translation:Parent*/
"parent" => elgg_echo("koolielu:selectable_role_parent"),
/*translation:Student*/
"student" => elgg_echo("koolielu:selectable_role_student"),
/*translation:Other*/
"other" => elgg_echo("koolielu:selectable_role_other")
);
return $data[$id];
}
// Search schools by multiple ids
function getSchoolsFromIDs($schools) {
global $CONFIG;
$suitable_schools = false;
// Check that the comma separated string with school ids is not empty
if (!empty($schools)) {
$schools = mysql_real_escape_string($schools);
$school_array = split(',', $schools);
$search_criteria = "SELECT * FROM {$CONFIG->dbprefix}koolielu_schools WHERE school_id = '";
// Now add up the criteria
$search_criteria .= implode("' or school_id = '", $school_array);
$search_criteria .= "'";
$suitable_schools = get_data($search_criteria);
}
return $suitable_schools;
}
// Helper parser function used for saving guidelines for tool subtype object
function keParseGuidelines($guidelines) {
$parsed_guidelines = array();
if (is_array($guidelines) && count($guidelines) > 0) {
foreach ($guidelines as $key => $value) {
if (!empty($value)) {
// Identify the link case and deal with it
if (substr_count($value, 'http://') > 0) {
$tmp_value = explode("waramu/view", $value);
$value = end($tmp_value);
$value = str_replace("/", "", $value);
$value = trim($value);
} else {
$value = str_replace("/", "", $value);
$value = trim($value);
}
// Now check if what we get is indeed an identifier of existing resource
try {
$resource = waramu_getResource('', $value);
$existing = true;
} catch(Exception $exception) {
$existing = false;
}
// If this resource really exists, accept it
if ($existing) {
array_push($parsed_guidelines, $value);
}
}
}
}
return $parsed_guidelines;
}
function getFrontpageResource(){
global $CONFIG;
if (isloggedin()) {
$user = get_loggedin_user();
$subjects_metadatas = get_metadata_byname($user->getGUID(), 'subjects');
$subject_ids = array();
if (is_array($subjects_metadatas)) {
foreach ($subjects_metadatas as $sm) {
array_push($subject_ids, $sm->value);
}
} else {
array_push($subject_ids, $subjects_metadatas->value);
}
if (sizeof($subject_ids) > 0) {
// Build sceletal
$query = "SELECT * from {$CONFIG->dbprefix}koolielu_frontpage_resource WHERE subtype='waramu_resource'";
if (sizeof($subject_ids) == 1 && $subject_ids[0] ) {
$query .= " and subject=" . $subject_ids[0];
} else if ( sizeof($subject_ids) > 1 ) {
$subjects_str = implode(" or subject=", $subject_ids);
// Add subject part
//$query .= " and subject=" . serialize($subject_ids);
$query .= " and ( subject=" . $subjects_str . " )";
}
// Add limitations and randomization part
$query .= " ORDER BY RAND() LIMIT 1";
return get_data_row($query);
} else {
return get_data_row("SELECT * from {$CONFIG->dbprefix}koolielu_frontpage_resource WHERE subtype='waramu_resource' ORDER BY RAND() LIMIT 1");
}
} else if (!isloggedin()) {
return get_data_row("SELECT * from {$CONFIG->dbprefix}koolielu_frontpage_resource WHERE subtype='waramu_resource' ORDER BY RAND() LIMIT 1");
}
// If we are dealign with some strange case, just return false
return false;
}
function getActiveMenuSection() {
global $CONFIG;
$current_context = get_context();
// Special override for group case, because some other plugins are used with it
if (in_array($current_context, array("file", "pages", "search"))) {
$page_owner = page_owner_entity();
if ($page_owner instanceof ElggGroup) {
return "groups";
}
}
return $current_context;
}
function _get_ke_tinymce_language() {
$current_language = get_current_language();
if ($current_language == "et") {
return $current_language;
}
return "en";
}
/**
*
* Array sorting by key name
*
**/
function sksort(&$array, $subkey="id", $sort_ascending=false) {
if (count($array))
$temp_array[key($array)] = array_shift($array);
foreach($array as $key => $val){
$offset = 0;
$found = false;
foreach($temp_array as $tmp_key => $tmp_val)
{
if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
{
$temp_array = array_merge( (array)array_slice($temp_array,0,$offset),
array($key => $val),
array_slice($temp_array,$offset)
);
$found = true;
}
$offset++;
}
if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
}
if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array;
}
// Produces paginated listing of all portal users, ordered by name
function ke_list_all_portal_users() {
$offset = get_input('offset',0);
$count = search_for_user("", 9999, 0, "u.name", true);
$objects = search_for_user("", 10, $offset, "LOWER(u.name) COLLATE utf8_bin", false);
if ($objects) {
return elgg_view_entity_list($objects, $count,$offset,10,false);
}
}
function ke_fieldhelp($id, $text, $button=true) {
if ($button)
$help .= '?';
$htitle = elgg_echo('koolielu:label_'.$id);
$help .= '';
/*translation:Help*/
$help .= '';
$help .= '
';
$help .= '
'.$htitle.'
';
$help .= $text.'
';
$help .= '
';
return $help;
}
// Function only available to user with administrator privileges
function koolielu_add_certificate_generated($creator, $persona, $materials) {
global $CONFIG;
if (isadminloggedin()) {
return insert_data("INSERT INTO {$CONFIG->dbprefix}koolielu_generated_certificates (creator, persona, materials) VALUES ('$creator', '$persona', '$materials')");
}
}
function sort_by($ar, $kn) {
$res = array();
$keyvals = array();
foreach ($ar as $a) {
$keyvals[(int)$a->$kn] = $a;
}
ksort($keyvals);
foreach ($keyvals as $a => $o) {
$res[] = $o;
}
return $res;
}
function get_prioval_value() {
if (!isEditor())
return '9';
$pval = get_input('prioval');
if (!in_array($pval, array('1','2','3','4','5')))
return '9';
return $pval;
}
function unassociate_prioval($pval) {
if (!in_array($pval, array('1','2','3','4','5')))
return;
$news = get_entities_from_metadata('prioval', $pval, "object", "news");
foreach($news as $no) {
$no->prioval = '9';
$no->save();
}
$news = get_entities_from_metadata('prioval', $pval, "object", "infopage");
foreach($news as $no) {
$no->prioval = '9';
$no->save();
}
}
/**
* Return entities matching a given query, or the number thereof
*
* @param string $type The type of entity (eg "user", "object" etc)
* @param string|array $subtype The arbitrary subtype of the entity or array(type1 => array('subtype1', ...'subtypeN'), ...)
* @param int $owner_guid The GUID of the owning user
* @param string $order_by The field to order by; by default, time_created desc
* @param int $limit The number of entities to return; 10 by default
* @param int $offset The indexing offset, 0 by default
* @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false.
* @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites.
* @param int|array $container_guid The container or containers to get entities from (default: all containers).
* @param int $timelower The earliest time the entity can have been created. Default: all
* @param int $timeupper The latest time the entity can have been created. Default: all
* @return array A list of entities.
*/
function koolielu_get_entities($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null, $timelower = 0, $timeupper = 0)
{
global $CONFIG;
if ($subtype === false || $subtype === null || $subtype === 0)
return false;
if ($order_by == "") $order_by = "time_created desc";
$order_by = sanitise_string($order_by);
$limit = (int)$limit;
$offset = (int)$offset;
$site_guid = (int) $site_guid;
$timelower = (int) $timelower;
$timeupper = (int) $timeupper;
if ($site_guid == 0)
$site_guid = $CONFIG->site_guid;
$where = array();
if (is_array($subtype)) {
$tempwhere = "";
if (sizeof($subtype))
foreach($subtype as $typekey => $subtypearray) {
foreach($subtypearray as $subtypeval) {
$typekey = sanitise_string($typekey);
if (!empty($subtypeval)) {
if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval))
return false;
} else {
// @todo: Setting subtype to 0 when $subtype = '' returns entities with
// no subtype. This is different to the non-array behavior
// but may be required in some cases.
$subtypeval = 0;
}
if (!empty($tempwhere)) $tempwhere .= " or ";
$tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})";
}
}
if (!empty($tempwhere)) $where[] = "({$tempwhere})";
} else {
$type = sanitise_string($type);
if ($subtype !== "" AND !$subtype = get_subtype_id($type, $subtype))
return false;
if ($type != "")
$where[] = "type='$type'";
if ($subtype!=="")
$where[] = "subtype=$subtype";
}
if ($owner_guid != "") {
if (!is_array($owner_guid)) {
$owner_array = array($owner_guid);
$owner_guid = (int) $owner_guid;
// $where[] = "owner_guid = '$owner_guid'";
} else if (sizeof($owner_guid) > 0) {
$owner_array = array_map('sanitise_int', $owner_guid);
// Cast every element to the owner_guid array to int
// $owner_guid = array_map("sanitise_int", $owner_guid);
// $owner_guid = implode(",",$owner_guid);
// $where[] = "owner_guid in ({$owner_guid})";
}
if (is_null($container_guid)) {
$container_guid = $owner_array;
}
}
if ($site_guid > 0)
$where[] = "site_guid = {$site_guid}";
if (!is_null($container_guid)) {
if (is_array($container_guid)) {
foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val;
$where[] = "container_guid in (" . implode(",",$container_guid) . ")";
} else {
$container_guid = (int) $container_guid;
$where[] = "container_guid = {$container_guid}";
}
}
if ($timelower)
$where[] = "time_created >= {$timelower}";
if ($timeupper)
$where[] = "time_created <= {$timeupper}";
//XXX
$additional_join ="";
if ($type == "object") {
$additional_join = " e join {$CONFIG->dbprefix}objects_entity o on e.guid=o.guid ";
} else if ($type == "group") {
$additional_join = " e join {$CONFIG->dbprefix}groups_entity g on e.guid=g.guid ";
} else if ($type == "user") {
$additional_join = " e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid ";
} else if ($type == 'site') {
$additional_join = " e join {$CONFIG->dbprefix}sites_entity s on e.guid=s.guid ";
}
//XXX
if (!$count) {
$query = "SELECT * from {$CONFIG->dbprefix}entities {$additional_join}where ";
} else {
$query = "SELECT count(guid) as total from {$CONFIG->dbprefix}entities where ";
}
foreach ($where as $w)
$query .= " $w and ";
$query .= get_access_sql_suffix(); // Add access controls
if (!$count) {
$query .= " order by $order_by";
if ($limit) $query .= " limit $offset, $limit"; // Add order and limit
$dt = get_data($query, "entity_row_to_elggstar");
return $dt;
} else {
$total = get_data_row($query);
return $total->total;
}
}
/**
* Return entities matching a given query, or the number thereof
*
* @param string $type The type of entity (eg "user", "object" etc)
* @param string|array $subtype The arbitrary subtype of the entity or array(type1 => array('subtype1', ...'subtypeN'), ...)
* @param int $owner_guid The GUID of the owning user
* @param string $order_by The field to order by; by default, time_created desc
* @param int $limit The number of entities to return; 10 by default
* @param int $offset The indexing offset, 0 by default
* @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false.
* @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites.
* @param int|array $container_guid The container or containers to get entities from (default: all containers).
* @param int $timelower The earliest time the entity can have been created. Default: all
* @param int $timeupper The latest time the entity can have been created. Default: all
* @return array A list of entities.
*/
function koolielu_get_entities_by_author($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null, $timelower = 0, $timeupper = 0)
{
global $CONFIG;
if ($subtype === false || $subtype === null || $subtype === 0)
return false;
if ($order_by == "") $order_by = "time_created desc";
$order_by = sanitise_string($order_by);
$limit = (int)$limit;
$offset = (int)$offset;
$site_guid = (int) $site_guid;
$timelower = (int) $timelower;
$timeupper = (int) $timeupper;
if ($site_guid == 0)
$site_guid = $CONFIG->site_guid;
$where = array();
if (is_array($subtype)) {
$tempwhere = "";
if (sizeof($subtype))
foreach($subtype as $typekey => $subtypearray) {
foreach($subtypearray as $subtypeval) {
$typekey = sanitise_string($typekey);
if (!empty($subtypeval)) {
if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval))
return false;
} else {
// @todo: Setting subtype to 0 when $subtype = '' returns entities with
// no subtype. This is different to the non-array behavior
// but may be required in some cases.
$subtypeval = 0;
}
if (!empty($tempwhere)) $tempwhere .= " or ";
$tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})";
}
}
if (!empty($tempwhere)) $where[] = "({$tempwhere})";
} else {
$type = sanitise_string($type);
if ($subtype !== "" AND !$subtype = get_subtype_id($type, $subtype))
return false;
if ($type != "")
$where[] = "type='$type'";
if ($subtype!=="")
$where[] = "subtype=$subtype";
}
if ($owner_guid != "") {
if (!is_array($owner_guid)) {
$owner_array = array($owner_guid);
$owner_guid = (int) $owner_guid;
// $where[] = "owner_guid = '$owner_guid'";
} else if (sizeof($owner_guid) > 0) {
$owner_array = array_map('sanitise_int', $owner_guid);
// Cast every element to the owner_guid array to int
// $owner_guid = array_map("sanitise_int", $owner_guid);
// $owner_guid = implode(",",$owner_guid);
// $where[] = "owner_guid in ({$owner_guid})";
}
if (is_null($container_guid)) {
$container_guid = $owner_array;
}
}
if ($site_guid > 0)
$where[] = "site_guid = {$site_guid}";
if (!is_null($container_guid)) {
if (is_array($container_guid)) {
foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val;
$where[] = "container_guid in (" . implode(",",$container_guid) . ")";
} else {
$container_guid = (int) $container_guid;
$where[] = "container_guid = {$container_guid}";
}
}
if ($timelower)
$where[] = "time_created >= {$timelower}";
if ($timeupper)
$where[] = "time_created <= {$timeupper}";
//XXX
$additional_join = " e join (SELECT name, guid as joined_guid FROM {$CONFIG->dbprefix}users_entity) u on e.owner_guid=u.joined_guid ";
//XXX
if (!$count) {
$query = "SELECT * from {$CONFIG->dbprefix}entities {$additional_join}where ";
} else {
$query = "SELECT count(guid) as total from {$CONFIG->dbprefix}entities where ";
}
foreach ($where as $w)
$query .= " $w and ";
$query .= get_access_sql_suffix(); // Add access controls
if (!$count) {
$query .= " order by $order_by";
if ($limit) $query .= " limit $offset, $limit"; // Add order and limit
$dt = get_data($query, "entity_row_to_elggstar");
return $dt;
} else {
$total = get_data_row($query);
return $total->total;
}
}
?>