/**
  * insert a new organization in database
  * @param array A well format organization 
  * @return a json result as an array. 
  */
 public static function insert($organization, $userId)
 {
     $newOrganization = Organization::getAndCheckOrganization($organization);
     //Manage tags : save any inexistant tag to DB
     if (isset($newOrganization["tags"])) {
         $newOrganization["tags"] = Tags::filterAndSaveNewTags($newOrganization["tags"]);
     }
     //Add the user creator of the organization in the system
     $newOrganization["creator"] = $userId;
     //Insert the organization
     PHDB::insert(Organization::COLLECTION, $newOrganization);
     if (isset($newOrganization["_id"])) {
         $newOrganizationId = (string) $newOrganization["_id"];
     } else {
         throw new CTKException(Yii::t("organisation", "Problem inserting the new organization"));
     }
     //Add the creator as the first member and admin of the organization
     Link::addMember($newOrganizationId, Organization::COLLECTION, $userId, PHType::TYPE_CITOYEN, $userId, true);
     //send Notification Email
     $creator = Person::getById($userId);
     Mail::newOrganization($creator, $newOrganization);
     //TODO ???? : add an admin notification
     Notification::saveNotification(array("type" => "Created", "user" => $newOrganizationId));
     $newOrganization = Organization::getById($newOrganizationId);
     return array("result" => true, "msg" => "Votre organisation est communectée.", "id" => $newOrganizationId, "newOrganization" => $newOrganization);
 }
Beispiel #2
0
 /**
  * adds an entry into the cron collection
  * @param $params : a set of information for a proper cron entry
  */
 public static function save($params)
 {
     //echo "adding Cron entry";
     $new = array("userId" => Yii::app()->session['userId'], "status" => self::STATUS_PENDING, "type" => $params['type']);
     if (isset($params['execTS'])) {
         $new['execTS'] = $params['execTS'];
     }
     if ($params['type'] == self::TYPE_MAIL) {
         $new = array_merge($new, self::addMailParams($params));
     }
     PHDB::insert(self::COLLECTION, $new);
 }
Beispiel #3
0
 public static function addWorkLog($project, $userEmail, $controller, $action)
 {
     if (stripos($_SERVER['SERVER_NAME'], "127.0.0.1") >= 0 || stripos($_SERVER['SERVER_NAME'], "localhost:8080") >= 0) {
         $lastUpdate = PHDB::findOne("cornerDev", array("project" => $project, "person" => $userEmail, "controller" => $controller, "action" => $action, "type" => self::ACTION_WORKLOG, "date" => date("d/m/y")));
         $timespend = 0;
         if ($lastUpdate) {
             $timespend = time() - $lastUpdate["lastUpdate"];
             //if($timespend > ) //seesion closer , maybe should be a button
             $timespend = ($timespend + $lastUpdate["timespend"] * 60) / 60;
         }
         $entry = array("project" => $project, "person" => $userEmail, "controller" => $controller, "action" => $action, "date" => date("d/m/y"), "timespend" => $timespend, "lastUpdate" => time());
         PHDB::updateWithOptions("cornerDev", array("project" => $project, "person" => $userEmail, "controller" => $controller, "action" => $action, "date" => date("d/m/y"), "type" => self::ACTION_WORKLOG), array('$set' => $entry), array("upsert" => true));
         PHDB::insert("cornerLog", array("project" => $project, "person" => $userEmail, "controller" => $controller, "action" => $action, "timestamp" => time(), "type" => self::ACTION_WORKLOG));
     }
 }
Beispiel #4
0
 public static function createMessage($emails, $name, $firstname, $msg, $cp, $module = null)
 {
     //run through emails and validate existing accounts
     $userids = array();
     $messageVit = "messagevitrine";
     $inexistantUsers = array();
     $emails = explode(",", $emails);
     foreach ($emails as $email) {
         //QUESTION : should we validate that a user is registered to the module
         if ($user = Yii::app()->mongodb->citoyens->findOne(array("email" => $email))) {
             array_push($userids, (string) $user["_id"]);
             //$name = $user["name"];
             $image = "";
         } else {
             array_push($inexistantUsers, (string) $user["_id"]);
             $image = "";
         }
     }
     //save message to DB
     $newInfos = array();
     $comment = array();
     $image = array();
     $image["url"] = "";
     $comment['comment'] = $msg;
     $newInfos['name'] = $name;
     $newInfos['firstname'] = $firstname;
     $newInfos['comment'] = $comment;
     $newInfos['image'] = $image;
     //$newInfos['cp'] = $cp;
     $newInfos['created'] = time();
     if (isset($_POST["app"])) {
         $appKey = $_POST["app"];
         $newInfos['applications'] = array($appKey => array("usertype" => "message"));
         $app = Yii::app()->mongodb->applications->findOne(array("key" => $appKey));
         //check for application specifics defined in DBs application entry
         if (isset($app["messagesVitrine"]) && $app["messagesVitrine"] == "mustBeConfirmed") {
             $newInfos['applications'][$appKey]["messageConfirmed"] = false;
         }
     }
     PHDB::insert($messageVit, $newInfos);
     $res = array("result" => true, "msg" => "message send to " . count($userids) . " users");
     if (count($inexistantUsers)) {
         $res["error"] = count($inexistantUsers) . " user doesn't have a PH account.";
     } else {
         $res = array("result" => false, "msg" => "no valid user accounts ");
     }
     return $res;
 }
Beispiel #5
0
 /**
  * save document information
  * @param $params : a set of information for the document (?to define)
  */
 public static function save($params)
 {
     //$id = Yii::app()->session["userId"];
     if (!isset($params["contentKey"])) {
         $params["contentKey"] = "";
     }
     $new = array("id" => $params['id'], "type" => $params['type'], "folder" => $params['folder'], "moduleId" => $params['moduleId'], "doctype" => Document::getDoctype($params['name']), "author" => $params['author'], "name" => $params['name'], "size" => $params['size'], 'created' => time());
     if (isset($params["category"]) && !empty($params["category"])) {
         $new["category"] = $params["category"];
     }
     if (isset($params["contentKey"]) && !empty($params["contentKey"])) {
         $new["contentKey"] = $params["contentKey"];
     }
     PHDB::insert(self::COLLECTION, $new);
     //Link::connect($id, $type, $new["_id"], PHType::TYPE_PROJECTS, $id, "projects" );
     return array("result" => true, "msg" => Yii::t('document', 'Document saved successfully', null, Yii::app()->controller->module->id), "id" => $new["_id"]);
 }
Beispiel #6
0
 public static function createMessage($emails, $msg, $module = null)
 {
     //run through emails and validate existing accounts
     $userids = array();
     $inexistantUsers = array();
     $emails = explode(",", $emails);
     foreach ($emails as $email) {
         //QUESTION : should we validate that a user is registered to the module
         if ($user = Yii::app()->mongodb->citoyens->findOne(array("email" => $email))) {
             array_push($userids, (string) $user["_id"]);
         } else {
             array_push($inexistantUsers, (string) $user["_id"]);
         }
     }
     //save message to DB
     if (count($userids)) {
         array_push($userids, Yii::app()->session["userId"]);
         $newInfos = array();
         $newInfos['from'] = Yii::app()->session["userId"];
         $newInfos['to'] = $userids;
         $newInfos['msg'] = $msg;
         if (isset($_POST["emailCopy"]) && $_POST["emailCopy"]) {
             $newInfos['emailCopy'] = "todo";
         }
         $newInfos['created'] = time();
         if (isset($_POST["app"])) {
             $appKey = $_POST["app"];
             $newInfos['applications'] = array($appKey => array("usertype" => "message"));
             $app = Yii::app()->mongodb->applications->findOne(array("key" => $appKey));
             //check for application specifics defined in DBs application entry
             if (isset($app["messages"]) && $app["messages"] == "mustBeConfirmed") {
                 $newInfos['applications'][$appKey]["messageConfirmed"] = false;
             }
         }
         PHDB::insert(PHType::TYPE_MESSAGES, $newInfos);
         $res = array("result" => true, "msg" => "message send to " . count($userids) . " users");
         if (count($inexistantUsers)) {
             $res["error"] = count($inexistantUsers) . " user doesn't have a PH account.";
         }
     } else {
         $res = array("result" => false, "msg" => "no valid user accounts ");
     }
     return $res;
 }
 public function run()
 {
     //liste des tags de rangements de l'asso
     $tags_rangements = array(array("name" => "Citoyens", "ico" => "male", "color" => "yellow"), array("name" => "Entreprises", "ico" => "briefcase", "color" => "blue"), array("name" => "Collaborateurs", "ico" => "circle", "color" => "purple"), array("name" => "Chercheurs", "ico" => "male", "color" => "green"));
     //liste des tags de rangements de chaque membre
     $tagsR = array("Citoyens", "Citoyens", "Citoyens", "Entreprises", "Entreprises", "Collaborateurs", "Chercheurs", "Chercheurs", "Chercheurs", "Chercheurs");
     $where = array('geo' => array('$exists' => true));
     $citoyens = PHDB::findAndSort(PHType::TYPE_CITOYEN, $where, array('name' => 1), 10);
     $membres = array();
     $i = 0;
     foreach ($citoyens as $citoyen) {
         $membres[] = array("id" => $citoyen["_id"], "tag_rangement" => $tagsR[$i]);
         $i++;
     }
     $where = array('_id' => new MongoId(Yii::app()->session["userId"]));
     $me = PHDB::findOne(PHType::TYPE_CITOYEN, $where);
     $newAsso = array("@context" => array("@vocab" => "http://schema.org", "ph" => "http://pixelhumain.com/ph/ontology/"), "email" => $me["email"], "name" => "asso1", "type" => "association", "cp" => "75000", "address" => array("@type" => "PostalAddress", "postalCode" => "75000", "addressLocality" => "France"), "description" => "Description de l'association", "tags_rangement" => $tags_rangements, "membres" => $membres);
     $res = PHDB::insert(Organization::COLLECTION, $newAsso);
     if ($res["ok"] == 1) {
         $res = "Initialisation des données : OK</br>Rechargez la carte !";
     }
     Rest::json($res);
     Yii::app()->end();
 }
Beispiel #8
0
 /**
  * Insert a new project, checking if the project is well formated
  * @param array $params Array with all fields for a project
  * @param string $userId UserId doing the insertion
  * @return array as result type
  */
 public static function insert($params, $userId)
 {
     $type = Person::COLLECTION;
     $newProject = self::getAndCheckProject($params, $userId);
     // TODO SBAR - If a Link::connect is used why add a link hard coded
     $newProject["links"] = array("contributors" => array($userId => array("type" => $type, "isAdmin" => true)));
     PHDB::insert(self::COLLECTION, $newProject);
     Link::connect($userId, $type, $newProject["_id"], self::COLLECTION, $userId, "projects", true);
     return array("result" => true, "msg" => "Votre projet est communecté.", "id" => $newProject["_id"]);
 }
 /**
  * Saves part of an entry genericlly based on 
  * - collection and id value
  */
 public function actionSave()
 {
     if (Yii::app()->request->isAjaxRequest && isset(Yii::app()->session["userId"])) {
         //var_dump($_POST);
         $id = null;
         $data = null;
         $collection = $_POST["collection"];
         if (!empty($_POST["id"])) {
             $id = $_POST["id"];
         }
         $key = $_POST["key"];
         unset($_POST['id']);
         if ($_POST['collection'] == PHType::TYPE_MICROFORMATS) {
             $_POST['collection'] = $_POST['MFcollection'];
             unset($_POST['MFcollection']);
         } else {
             unset($_POST['collection']);
             unset($_POST['key']);
         }
         //empty fields aren't properly validated and must be removed
         /*foreach ($_POST as $k => $v) {
               echo $k." => ".$v."\n";
               if(empty($v))
                   unset($_POST[$k]);
           }*/
         $microformat = PHDB::findOne(PHType::TYPE_MICROFORMATS, array("key" => $key));
         $validate = !isset($microformat) || !isset($microformat["jsonSchema"]) ? false : true;
         //validation process based on microformat defeinition of the form
         //by default dont perform validation test
         $valid = array("result" => true);
         if ($validate) {
             $valid = PHDB::validate($key, json_decode(json_encode($_POST), FALSE));
         }
         if ($valid["result"]) {
             if ($id) {
                 //update a single field
                 //else update whole map
                 $changeMap = !$microformat && isset($key) ? array('$set' => array($key => $_POST[$key])) : array('$set' => $_POST);
                 PHDB::update($collection, array("_id" => new MongoId($id)), $changeMap);
                 $res = array("result" => true, "msg" => "Vos données ont été mise à jour.", "reload" => true, "map" => $_POST, "id" => (string) $_POST["_id"]);
             } else {
                 $_POST["created"] = time();
                 PHDB::insert($collection, $_POST);
                 $res = array("result" => true, "msg" => "Vos données ont bien été enregistré.", "reload" => true, "map" => $_POST, "id" => (string) $_POST["_id"]);
             }
         } else {
             $res = $valid;
         }
         echo json_encode($res);
     }
 }
Beispiel #10
0
 public function run()
 {
     $email = $_POST["email"];
     $res = null;
     if (Yii::app()->request->isAjaxRequest) {
         //creating user must exist
         if ($user = PHDB::findOne(PHType::TYPE_CITOYEN, array("email" => $email))) {
             //udate the new app specific fields
             $newInfos = array();
             if (isset($_POST['email'])) {
                 $newInfos['email'] = $_POST['email'];
             }
             if (isset($_POST['email']) && $_POST['email'] != Yii::app()->session["userEmail"]) {
                 $newInfos['createdByEmail'] = Yii::app()->session["userEmail"];
             }
             if (isset($_POST['cp'])) {
                 $newInfos['cp'] = $_POST['cp'];
             }
             if (isset($_POST['name'])) {
                 $newInfos['name'] = $_POST['name'];
             }
             if (isset($_POST['phoneNumber'])) {
                 $newInfos['phoneNumber'] = $_POST['phoneNumber'];
             }
             if (isset($_POST['type'])) {
                 $newInfos['type'] = $_POST['type'];
             }
             if (isset($_POST['tags'])) {
                 $newInfos['tags'] = explode(",", $_POST['tags']);
             }
             if (isset($_POST['when'])) {
                 $newInfos['date'] = $_POST['when'];
             }
             if (isset($_POST['where'])) {
                 $newInfos['where'] = $_POST['where'];
             }
             if (isset($_POST['group'])) {
                 $newInfos['group'] = $_POST['group'];
             }
             if (isset($_POST["app"])) {
                 $appKey = $_POST["app"];
                 $newInfos['applications'] = array($appKey => array("usertype" => $_POST['type']));
                 $app = PHDB::findOne(PHType::TYPE_APPLICATIONS, array("key" => $appKey));
                 //check for application specifics defined in DBs application entry
                 if (isset($app["registration"]) && $app["registration"] == "mustBeConfirmed") {
                     $newInfos['applications'][$appKey]["registrationConfirmed"] = false;
                 }
             }
             //check if group exists else create the new group
             if (!PHDB::findOne(PHType::TYPE_GROUPS, array("type" => $_POST['type'], "name" => $_POST['name']))) {
                 PHDB::insert(PHType::TYPE_GROUPS, $newInfos);
                 $res = array("result" => true, "msg" => $_POST['type'] . " has been created");
             } else {
                 //if there's an email change
                 PHDB::update(PHType::TYPE_GROUPS, array("name" => $_POST['name']), array('$set' => $newInfos));
                 $res = array("result" => true, "msg" => $_POST['type'] . " has been updated");
             }
             //TODO : confirmation email on create
             //TODO : notification on update
         } else {
             $res = array('result' => false, "msg" => "Connected user must exist");
         }
     } else {
         $res = array('result' => false, 'msg' => 'something somewhere went terribly wrong');
     }
     Rest::json($res);
     Yii::app()->end();
 }
Beispiel #11
0
 /**
  *
  * @return [json Map] list
  */
 public static function addEntry($param)
 {
     $param["timestamp"] = time();
     PHDB::insert(PHType::TYPE_ACTIVITYSTREAM, $param);
 }
Beispiel #12
0
 /**
  *
  * @return [json Map] list
  */
 public static function insertData($row, $collection, $type, $isDummy, $linkAllToActiveUser)
 {
     $error = null;
     if (isset($row["_id"]) && isset($row["_id"]['$oid']) && PHDB::isValidMongoId($row["_id"]['$oid'])) {
         $id = $row["_id"]['$oid'];
         unset($row["_id"]);
         try {
             $id = new MongoId($id);
         } catch (MongoException $ex) {
             $id = new MongoId();
         }
     } else {
         $id = new MongoId();
     }
     $row["_id"] = $id;
     /* **************************************
      * always add a key to easily detect and remove dummy data 
      ***************************************** */
     if ($isDummy) {
         $row["dummyData"] = $type;
     }
     if (!$collection) {
         $collection = $fn;
     }
     /* **************************************
      *	Building links with the active User 
      ***************************************** */
     $where = array("_id" => new MongoId((string) $row["_id"]));
     $exist = PHDB::findOne($collection, $where) ? true : false;
     $info = array("collection" => $collection, "id" => (string) $row["_id"], "exist" => $exist, "msg" => array());
     $userId = Yii::app()->session["userId"];
     if ($linkAllToActiveUser) {
         $personType = array("type" => PHType::TYPE_CITOYEN, "isAdmin" => true);
         if (!isset($row["dontLink"]) || !$row["dontLink"]) {
             //Add creator to collection
             $row["creator"] = $userId;
             if ($collection == PHType::TYPE_CITOYEN) {
                 /* **************************************
                  *	KNOWS links for people
                  ***************************************** */
                 if (isset($row["links"])) {
                     if (isset($row["links"]["knows"])) {
                         // Pas d'admin pour le knows
                         unset($personType["isAdmin"]);
                         $row["links"]["knows"][$userId] = $personType;
                     } else {
                         $knows = array();
                         $knows[$userId] = $personType;
                         $row["links"]["knows"] = $knows;
                     }
                 } else {
                     $knows = array();
                     $knows[$userId] = $personType;
                     $row["links"] = array("knows" => $knows);
                 }
                 PHDB::update(PHType::TYPE_CITOYEN, array("_id" => new MongoId($userId)), array('$set' => array(Link::person2person . "." . (string) $row["_id"] => array("type" => $collection))));
                 array_push($info["msg"], "added links.knows activeUser");
             } elseif ($collection == PHType::TYPE_ORGANIZATIONS) {
                 /* **************************************
                  *	MEMBERS links for ORGANISATION
                  ***************************************** */
                 if (isset($row["links"])) {
                     if (isset($row["links"]["members"])) {
                         $row["links"]["members"][$userId] = $personType;
                     } else {
                         $members = array();
                         $members[$userId] = $personType;
                         $row["links"]["members"] = $members;
                     }
                 } else {
                     $members = array();
                     $members[$userId] = $personType;
                     $row["links"] = array("members" => $members);
                 }
                 PHDB::update(PHType::TYPE_CITOYEN, array("_id" => new MongoId($userId)), array('$set' => array(Link::person2organization . "." . (string) $row["_id"] => array("type" => $collection, "isAdmin" => true))));
                 array_push($info["msg"], "added links.members and memberOf for activeUser");
             } elseif ($collection == PHType::TYPE_EVENTS) {
                 /* **************************************
                  *	ATTENDEES links for events
                  ***************************************** */
                 if (isset($row["links"])) {
                     if (isset($row["links"]["attendees"])) {
                         $row["links"]["attendees"][$userId] = $personType;
                     } else {
                         $attendees = array();
                         $attendees[$userId] = $personType;
                         $row["links"]["attendees"] = $attendees;
                     }
                 } else {
                     $attendees = array();
                     $attendees[$userId] = $personType;
                     $row["links"] = array("attendees" => $attendees);
                 }
                 PHDB::update(PHType::TYPE_CITOYEN, array("_id" => new MongoId($userId)), array('$set' => array(Link::person2events . "." . (string) $row["_id"] => array("type" => $collection))));
                 array_push($info["msg"], "added links.events for activeUser");
             } elseif ($collection == PHType::TYPE_PROJECTS) {
                 /* **************************************
                  *	CONTRIBUTORS links for projects
                  ***************************************** */
                 if (isset($row["links"])) {
                     if (isset($row["links"]["contributors"])) {
                         $row["links"]["contributors"][$userId] = $personType;
                     } else {
                         $contributors = array();
                         $contributors[$userId] = $personType;
                         $row["links"]["contributors"] = $contributors;
                     }
                 } else {
                     $contributors = array();
                     $contributors[$userId] = $personType;
                     $row["links"] = array("contributors" => $contributors);
                 }
                 PHDB::update(PHType::TYPE_CITOYEN, array("_id" => new MongoId($userId)), array('$set' => array(Link::person2projects . "." . (string) $row["_id"] => array("type" => $collection))));
                 array_push($info["msg"], "added links.projects for activeUser");
             }
         }
     }
     if ($exist) {
         /* **************************************
          *	remove to renew existing data
          ***************************************** */
         PHDB::remove($collection, $where);
         array_push($info["msg"], "existed removed");
     }
     try {
         /* **************************************
          *	Create entry in DB
          ***************************************** */
         PHDB::insert($collection, $row);
         array_push($info["msg"], "inserted");
     } catch (MongoException $ex) {
         $error = array("id" => (string) $row["_id"], "exist" => $exist, "msg" => $ex->getMessage());
     }
     return array("info" => $info, "error" => $error);
 }
 /**
  * adds an entry into the cron collection
  * @param $params : a set of information for a proper cron entry
  */
 public static function update($params)
 {
     $new = array("id" => $params['id'], "person" => $params['type'], "folder" => $params['folder'], "moduleId" => $params['moduleId'], "doctype" => Document::getDoctype($params['name']), "author" => $params['author'], "name" => $params['name'], "size" => $params['size'], 'created' => time());
     PHDB::insert(self::COLLECTION, $new);
 }
Beispiel #14
0
 /**
  * Gives status messages about the difference between 2 array elements
  * correponding to a collection entry in the database 
  *
  * @return array of message with their types
  */
 public static function compareEntries($entries, $type, $file, $where, $autoApply = false)
 {
     $msg = array();
     $arrayFromDataFolder = PHDB::getArrayFromDataFolder($file, $where);
     if (isset($entries[$type]["_id"])) {
         unset($entries[$type]["_id"]);
     }
     //testing existence
     if (!isset($entries[$type])) {
         array_push($msg, array("type" => "error", "msg" => "no {$type} in DB"));
         if ($autoApply) {
             PHDB::insert($file, $arrayFromDataFolder);
             array_push($msg, array("type" => "action", "msg" => "new {$type} inserted DB"));
             array_push($msg, array("type" => "ok", "msg" => "{$type} entry has been updated in Database, <br/>"));
         }
     } else {
         if ($diff = ArrayHelper::array_diff_assoc_recursive($arrayFromDataFolder, $entries[$type])) {
             array_push($msg, array("type" => "error", "msg" => "{$type} entry isn't up to date , some data has been 'added' to current content <br/>"));
             //var_dump($arrayFromDataFolder);
             //var_dump($entries[$type]);
             var_dump($diff);
             if (!empty($diff) && $autoApply) {
                 PHDB::remove($file, array($where["key"] => $where["value"]));
                 array_push($msg, array("type" => "action", "msg" => "old {$type} removed DB"));
                 PHDB::insert($file, $arrayFromDataFolder);
                 array_push($msg, array("type" => "action", "msg" => "new {$type} inserted DB"));
                 array_push($msg, array("type" => "ok", "msg" => "{$type} entry has been updated in Database, <br/>"));
             }
         } else {
             if ($diff = ArrayHelper::array_diff_assoc_recursive($entries[$type], $arrayFromDataFolder)) {
                 array_push($msg, array("type" => "error", "msg" => "{$type} entry isn't up to date , some data has been 'removed' from current content  <br/>"));
                 //var_dump($arrayFromDataFolder);
                 //var_dump($entries[$type]);
                 var_dump($diff);
                 if (!empty($diff) && $autoApply) {
                     PHDB::remove($file, array($where["key"] => $where["value"]));
                     array_push($msg, array("type" => "action", "msg" => "old {$type} removed DB"));
                     PHDB::insert($file, $arrayFromDataFolder);
                     array_push($msg, array("type" => "action", "msg" => "new {$type} inserted DB"));
                     array_push($msg, array("type" => "ok", "msg" => "{$type} entry has been updated in Database, <br/>"));
                 }
             } else {
                 array_push($msg, array("type" => "ok", "msg" => "nothing to update on {$type}"));
             }
         }
     }
     return $msg;
 }
Beispiel #15
0
 public static function importMongoDB($post)
 {
     $objectImport = json_decode($post['jsonimport']);
     //var_dump($jsonMapping);
     $objectMapping = json_decode($post['jsonmapping']);
     //var_dump($objectMapping);
     $nameFile = explode(".", $objectMapping->nameFile);
     $files_importHistory = scandir("../../modules/cityData/importHistory/");
     $i = 0;
     $nameFolder = false;
     while ($i < count($files_importHistory) && $nameFolder == false) {
         if (strpos($files_importHistory[$i], $nameFile[0]) !== false) {
             $nameFolder = $files_importHistory[$i];
         }
         $i++;
     }
     if ($nameFolder == false) {
         $nameFolder = date("Ymd") . '_' . $nameFile[0];
         mkdir("../../modules/cityData/importHistory/" . $nameFolder, 0775);
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/importHistory.json", $post['jsonmapping']);
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/cityData_1.json", $post['jsonimport']);
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/error_1.json", $post['jsonrejet']);
         $textFileSh = "mongoimport --db pixelhumain --collection importHistory importHistory.json --jsonArray;\n";
         $textFileSh = $textFileSh . "mongoimport --db pixelhumain --collection cityData cityData_1.json --jsonArray;\n";
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/importMongo.sh", $textFileSh);
         if (file_exists("../../modules/cityData/importHistory/importMongoAll.sh") == true) {
             $textImportMongoAll = file_get_contents("../../modules/cityData/importHistory/importMongoAll.sh", FILE_USE_INCLUDE_PATH);
         } else {
             $textImportMongoAll = "";
         }
         $textImportMongoAll = $textImportMongoAll . "cd " . $nameFolder . ";\n";
         $textImportMongoAll = $textImportMongoAll . "sh importMongo.sh;\n";
         $textImportMongoAll = $textImportMongoAll . "cd .. ;\n";
     } else {
         $files = scandir("../../modules/cityData/importHistory/" . $nameFolder);
         $count = 1;
         foreach ($files as $key => $value) {
             $name_file = explode(".", $value);
             if (strpos($name_file[0], "cityData") !== false) {
                 $count++;
             }
         }
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/importHistory.json", $post['jsonmapping']);
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/cityData_" . $count . ".json", $post['jsonimport']);
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/error_" . $count . ".json", $post['jsonrejet']);
         $textFileSh = file_get_contents("../../modules/cityData/importHistory/" . $nameFolder . "/importMongo.sh", FILE_USE_INCLUDE_PATH);
         $textFileSh = $textFileSh . "mongoimport --db pixelhumain --collection cityData cityData_" . $count . ".json --jsonArray;\n";
         file_put_contents("../../modules/cityData/importHistory/" . $nameFolder . "/importMongo.sh", $textFileSh);
         if (file_exists("../../modules/cityData/importHistory/importMongoAll.sh") == true) {
             $textImportMongoAll = file_get_contents("../../modules/cityData/importHistory/importMongoAll.sh", FILE_USE_INCLUDE_PATH);
         } else {
             $textImportMongoAll = "cd " . $nameFolder . ";\n";
             $textImportMongoAll = $textImportMongoAll . "sh importMongo.sh;\n";
             $textImportMongoAll = $textImportMongoAll . "cd .. ;\n";
         }
     }
     //var_dump($textImportMongoAll);
     file_put_contents("../../modules/cityData/importHistory/importMongoAll.sh", $textImportMongoAll);
     if ($post['chooseSelected'] == "new") {
         $resMapping = PHDB::insert(City::COLLECTION_IMPORTHISTORY, $objectMapping);
     } else {
         $resMapping = PHDB::update(City::COLLECTION_IMPORTHISTORY, array("_id" => new MongoId($post['mappingSelected'])), array('$set' => array('src' => $objectMapping->src, 'date_update' => $objectMapping->date_update, 'nameFile' => $objectMapping->nameFile, 'url' => $objectMapping->url, 'separateur' => $objectMapping->separateur, 'idlien' => $objectMapping->idlien, 'fields' => $objectMapping->fields)), array("upsert" => true));
     }
     if (isset($objectImport->insee)) {
         $res = PHDB::findOne(City::COLLECTION_DATA, array("insee" => $objectImport->insee, $post["typeData"] => array('$exists' => 1)));
         echo "</br> 1 : ";
         var_dump($post["typeData"]);
         var_dump($res);
         if ($res == null) {
             $resData = PHDB::insert(City::COLLECTION_DATA, $objectImport);
         } else {
             $resData = PHDB::update(City::COLLECTION_DATA, array("_id" => new MongoId($res["_id"])), array('$set' => $objectImport), array("upsert" => true));
         }
     } else {
         foreach ($objectImport as $key => $value) {
             $res = PHDB::findOne(City::COLLECTION_DATA, array("insee" => $value->insee, $post["typeData"] => array('$exists' => 1)));
             if ($res == null) {
                 $resData = PHDB::insert(City::COLLECTION_DATA, $value);
             } else {
                 $resData = PHDB::update(City::COLLECTION_DATA, array("_id" => new MongoId($res["_id"])), array('$set' => $value), array("upsert" => true));
             }
         }
     }
     return $resMapping;
 }
Beispiel #16
0
 public static function save($params)
 {
     //check a user is loggued
     $user = Person::getById(Yii::app()->session["userId"]);
     //TODO : if type is Organization check the connected user isAdmin
     if (empty($user)) {
         throw new CTKException("You must be loggued in to add a news entry.");
     }
     if (isset($_POST["name"]) && isset($_POST["text"])) {
         $news = array("name" => $_POST["name"], "text" => $_POST["text"], "author" => Yii::app()->session["userId"], "created" => time());
         if (isset($_POST["tags"])) {
             $news["tags"] = $_POST["tags"];
         }
         if (isset($_POST["typeId"])) {
             $news["id"] = $_POST["typeId"];
         }
         if (isset($_POST["type"])) {
             $news["type"] = $_POST["type"];
             if ($_POST["type"] == Person::COLLECTION) {
                 $person = Person::getById($_POST["typeId"]);
                 if (isset($person['geo'])) {
                     $news["from"] = $person['geo'];
                 }
             } else {
                 if ($_POST["type"] == Organization::COLLECTION) {
                     $person = Person::getById($_POST["typeId"]);
                     if (isset($person['geo'])) {
                         $news["from"] = $person['geo'];
                     }
                 }
             }
             /*if( $_POST["type"] == Organization::COLLECTION && Authorisation::isOrganizationAdmin( Yii::app()->session["userId"], $_POST["typeId"]) )
             		throw new CTKException("You must be admin of this organization to post.");*/
         }
         if (isset($_POST["scope"])) {
             foreach ($_POST["scope"] as $scope) {
                 //dans le cas d'un groupe
                 //ajoute un à un chaque membre du groupe demandé (=> contact)
                 if ($scope->scopeType == "groupe") {
                     //pour chacun de ses groupes de contact
                     foreach ($user["knows"] as $groupe) {
                         //pour chaque membre du groupe demandé
                         if ($groupe["name"] == $scope->id) {
                             foreach ($groupe["members"] as $contact) {
                                 //recupere les donnes du contact
                                 $where = array('_id' => $contact);
                                 $allContact = PHDB::find(Person::COLLECTION, $where);
                                 $allContact = $allContact[$contact->__toString()];
                                 //ajoute un scope de type "contact" dans la news
                                 $news["scope"][] = array("scopeType" => "contact", "at" => "@" . $allContact["name"], "id" => $contact);
                             }
                         }
                     }
                 } else {
                     if ($scope->id == "all_contact" && $scope->scopeType == "contact") {
                         //pour chacun de ses groupes de contact
                         foreach ($user["knows"] as $groupe) {
                             //pour chaque membre d'un groupe
                             foreach ($groupe["members"] as $contact) {
                                 //recupere les donnes du contact
                                 $where = array('_id' => $contact);
                                 $allContact = PHDB::find(PHType::TYPE_CITOYEN, $where);
                                 $allContact = $allContact[$contact->__toString()];
                                 //if(!isset($allContact["name"])) {Rest::json( "pas de name" ); Yii::app()->end(); }
                                 //ajoute un scope de type "contact" dans la news
                                 if (isset($allContact["name"])) {
                                     $news["scope"][] = array("scopeType" => "contact", "at" => "@" . $allContact["name"], "id" => $contact);
                                 }
                             }
                         }
                     } else {
                         if ($scope->id == "all_organisation" && $scope->scopeType == "organisation") {
                             //pour chacun de ses organisations
                             foreach ($user["memberOf"] as $organization) {
                                 //recupere les donnes de l'organisation
                                 $where = array('_id' => $organization);
                                 $allOrga = PHDB::find("organizations", $where);
                                 $allOrga = $allOrga[$organization->__toString()];
                                 //ajoute un scope de type "organisation" dans la news
                                 $news["scope"][] = array("scopeType" => $scope->scopeType, "at" => "@" . $allOrga["name"], "id" => $organization);
                             }
                         } else {
                             $news["scope"][] = $scope;
                         }
                     }
                 }
             }
         }
         PHDB::insert(self::COLLECTION, $news);
         //Link::connect($id, $type, $new["_id"], PHType::TYPE_PROJECTS, $id, "projects" );
         return array("result" => true, "msg" => "Votre news est enregistré.", "id" => $news["_id"], "object" => $news);
     } else {
         return array("result" => false, "msg" => "Please Fill required Fields.");
     }
 }
Beispiel #17
0
 /**
  * Insert a new person from the minimal information inside the parameter
  * @param array $person Minimal information to create a person.
  * @param boolean $minimal : true : a person can be created using only "name" and "email". Else : "postalCode" and "pwd" are also requiered
  * @return array result, msg and id
  */
 public static function insert($person, $minimal = false)
 {
     //Check Person data + business rules
     $person = self::getAndcheckPersonData($person, $minimal);
     $person["@context"] = array("@vocab" => "http://schema.org", "ph" => "http://pixelhumain.com/ph/ontology/");
     //Add aditional information
     $person["tobeactivated"] = true;
     $person["created"] = time();
     PHDB::insert(PHType::TYPE_CITOYEN, $person);
     if (isset($person["_id"])) {
         $newpersonId = (string) $person["_id"];
     } else {
         throw new CTKException("Problem inserting the new person");
     }
     //send validation mail
     //TODO : make emails as cron jobs
     /*$app = new Application($_POST["app"]);
       Mail::send(array("tpl"=>'validation',
            "subject" => 'Confirmer votre compte  pour le site '.$this->name,
            "from"=>Yii::app()->params['adminEmail'],
            "to" => (!PH::notlocalServer()) ? Yii::app()->params['adminEmail']: $email,
            "tplParams" => array( "user"=>$newAccount["_id"] ,
                                  "title" => $app->name ,
                                  "logo"  => $app->logoUrl )
       ));*/
     Mail::validatePerson($person);
     return array("result" => true, "msg" => "You are now communnected", "id" => $newpersonId);
 }
Beispiel #18
0
 public function run()
 {
     /*
             	params = { "title" : $("#titleSaveNews").val() , 
     			    	   "msg" : $("#contentSaveNews").val() , 
     			    	   "tags" : $("#tagsSaveNews").val() ,
     			    	   "nature":$("#natureSaveNews").val(),
     			    	   "scopeType" : scopeType
     			    	};
     			    	
     			if(scopeType == "geoArea"){
     				var bounds = getBoundsValue();
     				params["latMinScope"] = bounds.getSouthWest().lat;
     				params["lngMinScope"] = bounds.getSouthWest().lng;
     				params["latMaxScope"] = bounds.getNorthEast().lat;
     				params["lngMaxScope"] = bounds.getNorthEast().lng;
     			}
     			if(scopeType == "cp")			{ params["cpScope"] = $("#cpScope").val(); }
     			if(scopeType == "departement")	{ params["depScope"] = $("#depScope").val(); }
     			if(scopeType == "groups")		{ params["groupScope"] = $("#groupsListScope").val(); }
     */
     $newsData = array();
     if (isset($_POST['title'])) {
         $newsData['title'] = $_POST['title'];
     }
     if (isset($_POST['msg'])) {
         $newsData['msg'] = $_POST['msg'];
     }
     if (isset($_POST['tags'])) {
         $newsData['tags'] = explode(",", $_POST['tags']);
     }
     if (isset($_POST['nature'])) {
         $newsData['nature'] = $_POST['nature'];
     }
     if (isset($_POST['scopeType'])) {
         $newsData['scope']['scopeType'] = $_POST['scopeType'];
     }
     if ($newsData['scope']['scopeType'] == "geoArea") {
         if (isset($_POST['latMinScope'])) {
             $newsData['scope']['geoArea']['latMinScope'] = floatval($_POST['latMinScope']);
         }
         if (isset($_POST['lngMinScope'])) {
             $newsData['scope']['geoArea']['lngMinScope'] = floatval($_POST['lngMinScope']);
         }
         if (isset($_POST['latMaxScope'])) {
             $newsData['scope']['geoArea']['latMaxScope'] = floatval($_POST['latMaxScope']);
         }
         if (isset($_POST['lngMaxScope'])) {
             $newsData['scope']['geoArea']['lngMaxScope'] = floatval($_POST['lngMaxScope']);
         }
     }
     if ($newsData['scope']['scopeType'] == "cp") {
         if (isset($_POST['cpScope'])) {
             $newsData['scope']['cpScope'] = $_POST['cpScope'];
         }
     }
     if ($newsData['scope']['scopeType'] == "groups") {
         if (isset($_POST['groupScope'])) {
             $newsData['scope']['groupScope'] = $_POST['groupScope'];
         }
     }
     if ($newsData['scope']['scopeType'] == "departement") {
         if (isset($_POST['depScope'])) {
             $newsData['scope']['depScope'] = $_POST['depScope'];
         }
     }
     //recuperation de la position de l'auteur du message
     $myEmail = Yii::app()->session["userEmail"];
     $user = PHDB::findOne(PHType::TYPE_CITOYEN, array("email" => $myEmail));
     $myCp = 0;
     //si l'utilisateur a enregistré sa position, on recopie lat lng
     if (isset($user['geo'])) {
         $newsData['from']['latitude'] = floatval($user['geo']['latitude']);
         $newsData['from']['longitude'] = floatval($user['geo']['longitude']);
     } else {
         //sinon on utilise la position geo de sa ville
         $myCp = $me['cp'];
         $city = PHDB::find('cities', array("cp" => $myCp));
         if ($city != null) {
             $newsData['from']['latitude'] = floatval($city['geo']['latitude']);
             $newsData['from']['longitude'] = floatval($city['geo']['longitude']);
         }
     }
     $newsData['author'] = new MongoId(Yii::app()->session["userId"]);
     PHDB::insert(PHType::TYPE_NEWS, $newsData);
     Rest::json($newsData);
     Yii::app()->end();
 }
Beispiel #19
0
 public static function createUser($email)
 {
     //new user is creating account
     $newAccount = array('email' => $email, 'created' => time());
     PHDB::insert(self::COLLECTION, $newAccount);
     //send validation mail
     //TODO : make emails as cron jobs
     Mail::send(array("tpl" => 'validation', "subject" => 'Confirmer votre compte ' . $title, "from" => Yii::app()->params['adminEmail'], "to" => $email, "tplParams" => array("user" => $newAccount["_id"])));
     return array("userAdded" => true, "id" => (string) $newAccount["_id"]);
 }
Beispiel #20
0
 /**
  * Save an event from Post. Check if it is well format.
  * @param type POST
  * @return save the event
  */
 public static function saveEvent($params)
 {
     self::checkEventData($params);
     $allDay = $params['allDay'] == 'true' ? true : false;
     $newEvent = array("name" => $params['name'], 'type' => $params['type'], 'public' => true, 'created' => time(), "startDate" => new MongoDate(strtotime($params['startDate'])), "endDate" => new MongoDate(strtotime($params['endDate'])), "allDay" => $allDay, 'creator' => $params['userId']);
     //Postal code & geo
     if (!empty($params['postalCode'])) {
         if (!empty($params['city'])) {
             $insee = $params['city'];
             $address = SIG::getAdressSchemaLikeByCodeInsee($insee);
             $newEvent["address"] = $address;
             $newEvent["geo"] = SIG::getGeoPositionByInseeCode($insee);
         }
     }
     //sameAs
     if (!empty($params['description'])) {
         $newEvent["description"] = $params['description'];
     }
     PHDB::insert(self::COLLECTION, $newEvent);
     //add the creator as the admin and the first attendee
     Link::attendee($newEvent["_id"], $params['userId'], true);
     Link::addOrganizer($params["organization"], $newEvent["_id"], $params['userId']);
     //send validation mail
     //TODO : make emails as cron events
     /*$message = new YiiMailMessage; 
       $message->view = 'validation';
       $message->setSubject('Confirmer votre compte Pixel Humain');
       $message->setBody(array("user"=>$new["_id"]), 'text/html');
       $message->addTo("*****@*****.**");//$params['registerEmail']
       $message->from = Yii::app()->params['adminEmail'];
       Yii::app()->mail->send($message);*/
     $creator = Person::getById($params['userId']);
     Mail::newEvent($creator, $newEvent);
     //TODO : add an admin notification
     //Notification::saveNotification(array("type"=>NotificationType::ASSOCIATION_SAVED,"user"=>$new["_id"]));
     return array("result" => true, "msg" => "Votre evenement est communecté.", "id" => $newEvent["_id"], "event" => $newEvent);
 }